sync_project.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. #!/usr/bin/ruby
  2. # Copyright 2018 Google
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # Syncs Xcode project folder and target structure with the filesystem. This
  16. # script finds all files on the filesystem that match the patterns supplied
  17. # below and changes the project to match what it found.
  18. #
  19. # Run this script after adding/removing tests to keep the project in sync.
  20. require 'pathname'
  21. # Note that xcodeproj 1.5.8 appears to be broken
  22. # https://github.com/CocoaPods/Xcodeproj/issues/572
  23. gem 'xcodeproj', '!= 1.5.8'
  24. require 'xcodeproj'
  25. def main()
  26. # Make all filenames relative to the project root.
  27. Dir.chdir(File.join(File.dirname(__FILE__), '..'))
  28. sync_firestore()
  29. end
  30. def sync_firestore()
  31. project = Xcodeproj::Project.open('Firestore/Example/Firestore.xcodeproj')
  32. # Enable warnings after opening the project to avoid the warnings in
  33. # xcodeproj itself
  34. $VERBOSE = true
  35. s = Syncer.new(project, Dir.pwd)
  36. # Files on the filesystem that should be ignored.
  37. s.ignore_files = [
  38. 'CMakeLists.txt',
  39. 'InfoPlist.strings',
  40. '*.plist',
  41. # b/79496027
  42. 'Firestore/core/test/firebase/firestore/remote/serializer_test.cc',
  43. ]
  44. # Folder groups in the Xcode project that contain tests.
  45. s.test_groups = [
  46. 'Tests',
  47. 'CoreTests',
  48. 'SwiftTests',
  49. ]
  50. s.target 'Firestore_Tests_iOS' do |t|
  51. t.source_files = [
  52. 'Firestore/Example/Tests/**',
  53. 'Firestore/core/test/**',
  54. 'Firestore/third_party/Immutable/Tests/**',
  55. ]
  56. t.exclude_files = [
  57. # needs to be in project but not in target
  58. 'Firestore/Example/Tests/Tests-Info.plist',
  59. # These files are integration tests, handled below
  60. 'Firestore/Example/Tests/Integration/**',
  61. ]
  62. end
  63. s.target 'Firestore_IntegrationTests_iOS' do |t|
  64. t.source_files = [
  65. 'Firestore/Example/Tests/Integration/**',
  66. 'Firestore/Example/Tests/Util/FSTEventAccumulator.mm',
  67. 'Firestore/Example/Tests/Util/FSTHelpers.mm',
  68. 'Firestore/Example/Tests/Util/FSTIntegrationTestCase.mm',
  69. 'Firestore/Example/Tests/Util/XCTestCase+Await.mm',
  70. 'Firestore/Example/Tests/en.lproj/InfoPlist.strings',
  71. ]
  72. end
  73. s.sync()
  74. sort_project(project)
  75. if project.dirty?
  76. project.save()
  77. end
  78. end
  79. # The definition of a test target including the target name, its source_files
  80. # and exclude_files. A file is considered part of a target if it matches a
  81. # pattern in source_files but does not match a pattern in exclude_files.
  82. class TargetDef
  83. def initialize(name)
  84. @name = name
  85. @source_files = []
  86. @exclude_files = []
  87. end
  88. attr_accessor :name, :source_files, :exclude_files
  89. # Returns true if the given relative_path matches this target's source_files
  90. # but not its exclude_files.
  91. #
  92. # Args:
  93. # - relative_path: a Pathname instance with a path relative to the project
  94. # root.
  95. def matches?(relative_path)
  96. return matches_patterns(relative_path, @source_files) &&
  97. !matches_patterns(relative_path, @exclude_files)
  98. end
  99. private
  100. # Evaluates the relative_path against the given list of fnmatch patterns.
  101. def matches_patterns(relative_path, patterns)
  102. patterns.each do |pattern|
  103. if relative_path.fnmatch?(pattern)
  104. return true
  105. end
  106. end
  107. return false
  108. end
  109. end
  110. class Syncer
  111. def initialize(project, root_dir)
  112. @project = project
  113. @root_dir = Pathname.new(root_dir)
  114. @finder = DirectoryLister.new(@root_dir)
  115. @seen_groups = {}
  116. @test_groups = []
  117. @targets = []
  118. end
  119. # Considers the given fnmatch glob patterns to be ignored by the syncer.
  120. # Patterns are matched both against the basename and project-relative
  121. # qualified pathname.
  122. def ignore_files=(patterns)
  123. @finder.add_patterns(patterns)
  124. end
  125. # Names the groups within the project that serve as roots for tests within
  126. # the project.
  127. def test_groups=(groups)
  128. @test_groups = []
  129. groups.each do |group|
  130. project_group = @project[group]
  131. if project_group.nil?
  132. raise "Project does not contain group #{group}"
  133. end
  134. @test_groups.push(@project[group])
  135. end
  136. end
  137. # Starts a new target block. Creates a new TargetDef and yields it.
  138. def target(name, &block)
  139. t = TargetDef.new(name)
  140. @targets.push(t)
  141. block.call(t)
  142. end
  143. # Synchronizes the filesystem with the project.
  144. #
  145. # Generally there are three separate ways a file is referenced within a project:
  146. #
  147. # 1. The file must be in the global list of files, assigning it a UUID.
  148. # 2. The file must be added to folder groups, describing where it is in the
  149. # folder view of the Project Navigator.
  150. # 3. The file must be added to a target descrbing how it's built.
  151. #
  152. # The Xcodeproj library handles (1) for us automatically if we do (2).
  153. #
  154. # Synchronization essentially proceeds in two steps:
  155. #
  156. # 1. Sync the filesystem structure with the folder group structure. This has
  157. # the effect of bringing (1) and (2) into sync.
  158. # 2. Sync the global list of files with the targets.
  159. def sync()
  160. group_differ = GroupDiffer.new(@finder)
  161. group_diffs = group_differ.diff(@test_groups)
  162. sync_groups(group_diffs)
  163. @targets.each do |target_def|
  164. sync_target(target_def)
  165. end
  166. end
  167. private
  168. def sync_groups(diff_entries)
  169. diff_entries.each do |entry|
  170. if !entry.in_source && entry.in_target
  171. remove_from_project(entry.ref)
  172. end
  173. if entry.in_source && !entry.in_target
  174. add_to_project(entry.path)
  175. end
  176. end
  177. end
  178. # Removes the given file reference from the project after the file is found
  179. # missing but references to it still exist in the project.
  180. def remove_from_project(file_ref)
  181. group = file_ref.parents[-1]
  182. mark_change_in_group(relative_path(group))
  183. puts " #{basename(file_ref)} - removed"
  184. # If the file is gone, any build phase that refers to must also remove the
  185. # file. Without this, the project will have build file references that
  186. # contain no actual file.
  187. @project.native_targets.each do |target|
  188. target.build_phases.each do |phase|
  189. if phase.include?(file_ref)
  190. phase.remove_file_reference(file_ref)
  191. end
  192. end
  193. end
  194. file_ref.remove_from_project
  195. end
  196. # Adds the given file to the project, in a path starting from the test root
  197. # that fully prefixes the file.
  198. def add_to_project(path)
  199. root_group = find_test_group_containing(path)
  200. # Find or create the group to contain the path.
  201. dir_rel_path = path.relative_path_from(root_group.real_path).dirname
  202. group = root_group.find_subpath(dir_rel_path.to_s, true)
  203. mark_change_in_group(relative_path(group))
  204. file_ref = group.new_file(path.to_s)
  205. puts " #{basename(file_ref)} - added"
  206. return file_ref
  207. end
  208. # Finds a test group whose path prefixes the given entry. Starting from the
  209. # project root may not work since not all test directories exist within the
  210. # example app.
  211. def find_test_group_containing(path)
  212. @test_groups.each do |group|
  213. rel = path.relative_path_from(group.real_path)
  214. next if rel.to_s.start_with?('..')
  215. return group
  216. end
  217. raise "Could not find an existing test group that's a parent of #{entry.path}"
  218. end
  219. def mark_change_in_group(group)
  220. path = group.to_s
  221. if !@seen_groups.has_key?(path)
  222. puts "#{path} ..."
  223. @seen_groups[path] = true
  224. end
  225. end
  226. SOURCES = %w{.c .cc .m .mm}
  227. def sync_target(target_def)
  228. target = @project.native_targets.find { |t| t.name == target_def.name }
  229. if !target
  230. raise "Missing target #{target_def.name}"
  231. end
  232. files = find_files_for_target(target_def)
  233. sources, resources = classify_files(files)
  234. sync_build_phase(target, target.source_build_phase, sources)
  235. end
  236. def classify_files(files)
  237. sources = {}
  238. resources = {}
  239. files.each do |file|
  240. path = file.real_path
  241. ext = path.extname
  242. if SOURCES.include?(ext)
  243. sources[path] = file
  244. end
  245. end
  246. return sources, resources
  247. end
  248. def sync_build_phase(target, phase, sources)
  249. # buffer changes to the phase to avoid modifying the array we're iterating
  250. # over.
  251. to_remove = []
  252. phase.files.each do |build_file|
  253. source_path = build_file.file_ref.real_path
  254. if sources.has_key?(source_path)
  255. # matches spec and existing target no action taken
  256. sources.delete(source_path)
  257. else
  258. # in the phase but now missing in the groups
  259. to_remove.push(build_file)
  260. end
  261. end
  262. to_remove.each do |build_file|
  263. mark_change_in_group(target.name)
  264. source_path = build_file.file_ref.real_path
  265. puts " #{relative_path(source_path)} - removed"
  266. phase.remove_build_file(build_file)
  267. end
  268. sources.each do |path, file_ref|
  269. mark_change_in_group(target.name)
  270. phase.add_file_reference(file_ref)
  271. puts " #{relative_path(file_ref)} - added"
  272. end
  273. end
  274. def find_files_for_target(target_def)
  275. result = []
  276. @project.files.each do |file_ref|
  277. next if file_ref.source_tree != '<group>'
  278. rel = relative_path(file_ref)
  279. if target_def.matches?(rel)
  280. result.push(file_ref)
  281. end
  282. end
  283. return result
  284. end
  285. def normalize_to_pathname(file_ref)
  286. if !file_ref.is_a? Pathname
  287. if file_ref.is_a? String
  288. file_ref = Pathname.new(file_ref)
  289. else
  290. file_ref = file_ref.real_path
  291. end
  292. end
  293. return file_ref
  294. end
  295. def basename(file_ref)
  296. return normalize_to_pathname(file_ref).basename
  297. end
  298. def relative_path(file_ref)
  299. file_ref = normalize_to_pathname(file_ref)
  300. return file_ref.relative_path_from(@root_dir)
  301. end
  302. end
  303. def sort_project(project)
  304. project.groups.each do |group|
  305. sort_group(group)
  306. end
  307. project.targets.each do |target|
  308. target.build_phases.each do |phase|
  309. phase.files.sort! { |a, b|
  310. a.file_ref.real_path.basename <=> b.file_ref.real_path.basename
  311. }
  312. end
  313. end
  314. end
  315. def sort_group(group)
  316. group.groups.each do |child|
  317. sort_group(child)
  318. end
  319. group.children.sort! do |a, b|
  320. # Sort groups first
  321. if a.isa == 'PBXGroup' && b.isa != 'PBXGroup'
  322. -1
  323. elsif a.isa != 'PBXGroup' && b.isa == 'PBXGroup'
  324. 1
  325. elsif a.display_name && b.display_name
  326. File.basename(a.display_name) <=> File.basename(b.display_name)
  327. else
  328. 0
  329. end
  330. end
  331. end
  332. # Tracks how a file is referenced: in the project file, on the filesystem,
  333. # neither, or both.
  334. class DiffEntry
  335. def initialize(path)
  336. @path = path
  337. @in_source = false
  338. @in_target = false
  339. @ref = nil
  340. end
  341. attr_reader :path
  342. attr_accessor :in_source, :in_target, :ref
  343. end
  344. # Diffs folder groups against the filesystem directories referenced by those
  345. # folder groups.
  346. #
  347. # This performs the diff starting from the directories referenced by the test
  348. # groups in the project, finding files contained within them. When comparing
  349. # the files it finds against the project this acts on absolute paths to avoid
  350. # problems with arbitary additional groupings in project structure that are
  351. # standard, e.g. "Supporting Files" or "en.lproj" which either act as aliases
  352. # for the parent or are folders that are omitted from the project view.
  353. # Processing the diff this way allows these warts to be tolerated, even if they
  354. # won't necessarily be recreated if an artifact is added to the filesystem.
  355. class GroupDiffer
  356. def initialize(dir_lister)
  357. @dir_lister = dir_lister
  358. @entries = {}
  359. @dirs = {}
  360. end
  361. # Finds all tests on the filesystem contained within the paths of the given
  362. # test groups and computes a list of DiffEntries describing the state of the
  363. # files.
  364. #
  365. # Args:
  366. # - groups: A list of PBXGroup objects representing folder groups within the
  367. # project that contain tests.
  368. #
  369. # Returns:
  370. # A list of DiffEntry objects, one for each test found. If the test exists on
  371. # the filesystem, :in_source will be true. If the test exists in the project
  372. # :in_target will be true and :ref will be set to the PBXFileReference naming
  373. # the file.
  374. def diff(groups) groups.each do |group| diff_project_files(group) end
  375. return @entries.values.sort { |a, b| a.path.basename <=> b.path.basename }
  376. end
  377. private
  378. # Recursively traverses all the folder groups in the Xcode project and finds
  379. # files both on the filesystem and the group file listing.
  380. def diff_project_files(group)
  381. find_fs_files(group.real_path)
  382. group.groups.each do |child|
  383. diff_project_files(child)
  384. end
  385. group.files.each do |file_ref|
  386. path = file_ref.real_path
  387. entry = track_file(path)
  388. entry.in_target = true
  389. entry.ref = file_ref
  390. if path.file?
  391. entry.in_source = true
  392. end
  393. end
  394. end
  395. def find_fs_files(parent_path)
  396. # Avoid re-traversing the filesystem
  397. if @dirs.has_key?(parent_path)
  398. return
  399. end
  400. @dirs[parent_path] = true
  401. @dir_lister.entries(parent_path).each do |path|
  402. if path.directory?
  403. find_fs_files(path)
  404. next
  405. end
  406. entry = track_file(path)
  407. entry.in_source = true
  408. end
  409. end
  410. def track_file(path)
  411. if @entries.has_key?(path)
  412. return @entries[path]
  413. end
  414. entry = DiffEntry.new(path)
  415. @entries[path] = entry
  416. return entry
  417. end
  418. end
  419. # Finds files on the filesystem while ignoring files that have been declared to
  420. # be ignored.
  421. class DirectoryLister
  422. def initialize(root_dir)
  423. @root_dir = root_dir
  424. @ignore_basenames = ['.', '..']
  425. @ignore_pathnames = []
  426. end
  427. def add_patterns(patterns)
  428. patterns.each do |pattern|
  429. if File.basename(pattern) != pattern
  430. @ignore_pathnames.push(File.join(@root_dir, pattern))
  431. else
  432. @ignore_basenames.push(pattern)
  433. end
  434. end
  435. end
  436. # Finds filesystem entries that are immediate children of the given Pathname,
  437. # ignoring files that match the the global ignore_files patterns.
  438. def entries(path)
  439. result = []
  440. path.entries.each do |entry|
  441. next if ignore_basename?(entry)
  442. file = path.join(entry)
  443. next if ignore_pathname?(file)
  444. result.push(file)
  445. end
  446. return result
  447. end
  448. private
  449. def ignore_basename?(basename)
  450. @ignore_basenames.each do |ignore|
  451. if basename.fnmatch(ignore)
  452. return true
  453. end
  454. end
  455. return false
  456. end
  457. def ignore_pathname?(file)
  458. @ignore_pathnames.each do |ignore|
  459. if file.fnmatch(ignore)
  460. return true
  461. end
  462. end
  463. return false
  464. end
  465. end
  466. if __FILE__ == $0
  467. main()
  468. end