wsba-hockey 1.0.3__py3-none-any.whl → 1.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. wsba_hockey/__init__.py +1 -1
  2. wsba_hockey/data_pipelines.py +183 -0
  3. wsba_hockey/evidence/weakside-breakout/node_modules/duckdb/vendor.py +146 -0
  4. wsba_hockey/evidence/weakside-breakout/node_modules/flatted/python/flatted.py +149 -0
  5. wsba_hockey/evidence/weakside-breakout/node_modules/flatted/python/test.py +63 -0
  6. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  7. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +367 -0
  8. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  9. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1270 -0
  10. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  11. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  12. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +153 -0
  13. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +271 -0
  14. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  15. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +690 -0
  16. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/common.py +661 -0
  17. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +78 -0
  18. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +165 -0
  19. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +109 -0
  20. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  21. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  22. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +808 -0
  23. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1173 -0
  24. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1321 -0
  25. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +120 -0
  26. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +103 -0
  27. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +464 -0
  28. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  29. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +58 -0
  30. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2714 -0
  31. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3981 -0
  32. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  33. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2936 -0
  34. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +55 -0
  35. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1394 -0
  36. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +25 -0
  37. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/input.py +3130 -0
  38. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +98 -0
  39. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +771 -0
  40. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1271 -0
  41. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  42. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  43. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +374 -0
  44. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1939 -0
  45. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +302 -0
  46. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3197 -0
  47. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  48. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/test_gyp.py +261 -0
  49. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/graphviz.py +102 -0
  50. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/pretty_gyp.py +156 -0
  51. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/pretty_sln.py +181 -0
  52. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/pretty_vcproj.py +339 -0
  53. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/test/fixtures/test-charmap.py +31 -0
  54. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/update-gyp.py +64 -0
  55. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  56. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +367 -0
  57. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  58. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1270 -0
  59. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  60. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  61. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +153 -0
  62. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +271 -0
  63. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  64. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +666 -0
  65. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/common.py +654 -0
  66. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +78 -0
  67. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +165 -0
  68. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +109 -0
  69. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  70. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  71. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +808 -0
  72. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1173 -0
  73. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1321 -0
  74. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +120 -0
  75. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +103 -0
  76. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +464 -0
  77. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  78. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +58 -0
  79. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2518 -0
  80. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3978 -0
  81. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  82. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2936 -0
  83. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +55 -0
  84. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1394 -0
  85. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +25 -0
  86. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/input.py +3137 -0
  87. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +98 -0
  88. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +771 -0
  89. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1271 -0
  90. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  91. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  92. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +374 -0
  93. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1939 -0
  94. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +302 -0
  95. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3197 -0
  96. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  97. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/setup.py +42 -0
  98. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/test_gyp.py +260 -0
  99. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/graphviz.py +102 -0
  100. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/pretty_gyp.py +156 -0
  101. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/pretty_sln.py +181 -0
  102. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/pretty_vcproj.py +339 -0
  103. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/test/fixtures/test-charmap.py +31 -0
  104. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/update-gyp.py +46 -0
  105. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/game_stats/app.py +400 -0
  106. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/game_stats/name_fix.py +47 -0
  107. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/heatmaps/app.py +108 -0
  108. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/heatmaps/plot.py +93 -0
  109. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/heatmaps/rink_plot.py +245 -0
  110. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/matchups/app.py +145 -0
  111. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/matchups/plot.py +77 -0
  112. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/matchups/rink_plot.py +245 -0
  113. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/pbp/app.py +389 -0
  114. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/pbp/plot.py +70 -0
  115. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/pbp/rink_plot.py +245 -0
  116. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/skater/app.py +110 -0
  117. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/skater/plot.py +58 -0
  118. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/skater/rink_plot.py +245 -0
  119. wsba_hockey/tools/agg.py +243 -54
  120. wsba_hockey/tools/plotting.py +25 -25
  121. wsba_hockey/tools/scraping.py +154 -263
  122. wsba_hockey/tools/xg_model.py +369 -315
  123. wsba_hockey/workspace.py +22 -117
  124. wsba_hockey/wsba_main.py +499 -167
  125. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.5.dist-info}/METADATA +1 -1
  126. wsba_hockey-1.0.5.dist-info/RECORD +135 -0
  127. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.5.dist-info}/WHEEL +1 -1
  128. wsba_hockey/stats/calculate_viz/shot_impact.py +0 -2
  129. wsba_hockey-1.0.3.dist-info/RECORD +0 -19
  130. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.5.dist-info}/licenses/LICENSE +0 -0
  131. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.5.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,3197 @@
1
+ # Copyright (c) 2012 Google Inc. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ """Xcode project file generator.
6
+
7
+ This module is both an Xcode project file generator and a documentation of the
8
+ Xcode project file format. Knowledge of the project file format was gained
9
+ based on extensive experience with Xcode, and by making changes to projects in
10
+ Xcode.app and observing the resultant changes in the associated project files.
11
+
12
+ XCODE PROJECT FILES
13
+
14
+ The generator targets the file format as written by Xcode 3.2 (specifically,
15
+ 3.2.6), but past experience has taught that the format has not changed
16
+ significantly in the past several years, and future versions of Xcode are able
17
+ to read older project files.
18
+
19
+ Xcode project files are "bundled": the project "file" from an end-user's
20
+ perspective is actually a directory with an ".xcodeproj" extension. The
21
+ project file from this module's perspective is actually a file inside this
22
+ directory, always named "project.pbxproj". This file contains a complete
23
+ description of the project and is all that is needed to use the xcodeproj.
24
+ Other files contained in the xcodeproj directory are simply used to store
25
+ per-user settings, such as the state of various UI elements in the Xcode
26
+ application.
27
+
28
+ The project.pbxproj file is a property list, stored in a format almost
29
+ identical to the NeXTstep property list format. The file is able to carry
30
+ Unicode data, and is encoded in UTF-8. The root element in the property list
31
+ is a dictionary that contains several properties of minimal interest, and two
32
+ properties of immense interest. The most important property is a dictionary
33
+ named "objects". The entire structure of the project is represented by the
34
+ children of this property. The objects dictionary is keyed by unique 96-bit
35
+ values represented by 24 uppercase hexadecimal characters. Each value in the
36
+ objects dictionary is itself a dictionary, describing an individual object.
37
+
38
+ Each object in the dictionary is a member of a class, which is identified by
39
+ the "isa" property of each object. A variety of classes are represented in a
40
+ project file. Objects can refer to other objects by ID, using the 24-character
41
+ hexadecimal object key. A project's objects form a tree, with a root object
42
+ of class PBXProject at the root. As an example, the PBXProject object serves
43
+ as parent to an XCConfigurationList object defining the build configurations
44
+ used in the project, a PBXGroup object serving as a container for all files
45
+ referenced in the project, and a list of target objects, each of which defines
46
+ a target in the project. There are several different types of target object,
47
+ such as PBXNativeTarget and PBXAggregateTarget. In this module, this
48
+ relationship is expressed by having each target type derive from an abstract
49
+ base named XCTarget.
50
+
51
+ The project.pbxproj file's root dictionary also contains a property, sibling to
52
+ the "objects" dictionary, named "rootObject". The value of rootObject is a
53
+ 24-character object key referring to the root PBXProject object in the
54
+ objects dictionary.
55
+
56
+ In Xcode, every file used as input to a target or produced as a final product
57
+ of a target must appear somewhere in the hierarchy rooted at the PBXGroup
58
+ object referenced by the PBXProject's mainGroup property. A PBXGroup is
59
+ generally represented as a folder in the Xcode application. PBXGroups can
60
+ contain other PBXGroups as well as PBXFileReferences, which are pointers to
61
+ actual files.
62
+
63
+ Each XCTarget contains a list of build phases, represented in this module by
64
+ the abstract base XCBuildPhase. Examples of concrete XCBuildPhase derivations
65
+ are PBXSourcesBuildPhase and PBXFrameworksBuildPhase, which correspond to the
66
+ "Compile Sources" and "Link Binary With Libraries" phases displayed in the
67
+ Xcode application. Files used as input to these phases (for example, source
68
+ files in the former case and libraries and frameworks in the latter) are
69
+ represented by PBXBuildFile objects, referenced by elements of "files" lists
70
+ in XCTarget objects. Each PBXBuildFile object refers to a PBXBuildFile
71
+ object as a "weak" reference: it does not "own" the PBXBuildFile, which is
72
+ owned by the root object's mainGroup or a descendant group. In most cases, the
73
+ layer of indirection between an XCBuildPhase and a PBXFileReference via a
74
+ PBXBuildFile appears extraneous, but there's actually one reason for this:
75
+ file-specific compiler flags are added to the PBXBuildFile object so as to
76
+ allow a single file to be a member of multiple targets while having distinct
77
+ compiler flags for each. These flags can be modified in the Xcode applciation
78
+ in the "Build" tab of a File Info window.
79
+
80
+ When a project is open in the Xcode application, Xcode will rewrite it. As
81
+ such, this module is careful to adhere to the formatting used by Xcode, to
82
+ avoid insignificant changes appearing in the file when it is used in the
83
+ Xcode application. This will keep version control repositories happy, and
84
+ makes it possible to compare a project file used in Xcode to one generated by
85
+ this module to determine if any significant changes were made in the
86
+ application.
87
+
88
+ Xcode has its own way of assigning 24-character identifiers to each object,
89
+ which is not duplicated here. Because the identifier only is only generated
90
+ once, when an object is created, and is then left unchanged, there is no need
91
+ to attempt to duplicate Xcode's behavior in this area. The generator is free
92
+ to select any identifier, even at random, to refer to the objects it creates,
93
+ and Xcode will retain those identifiers and use them when subsequently
94
+ rewriting the project file. However, the generator would choose new random
95
+ identifiers each time the project files are generated, leading to difficulties
96
+ comparing "used" project files to "pristine" ones produced by this module,
97
+ and causing the appearance of changes as every object identifier is changed
98
+ when updated projects are checked in to a version control repository. To
99
+ mitigate this problem, this module chooses identifiers in a more deterministic
100
+ way, by hashing a description of each object as well as its parent and ancestor
101
+ objects. This strategy should result in minimal "shift" in IDs as successive
102
+ generations of project files are produced.
103
+
104
+ THIS MODULE
105
+
106
+ This module introduces several classes, all derived from the XCObject class.
107
+ Nearly all of the "brains" are built into the XCObject class, which understands
108
+ how to create and modify objects, maintain the proper tree structure, compute
109
+ identifiers, and print objects. For the most part, classes derived from
110
+ XCObject need only provide a _schema class object, a dictionary that
111
+ expresses what properties objects of the class may contain.
112
+
113
+ Given this structure, it's possible to build a minimal project file by creating
114
+ objects of the appropriate types and making the proper connections:
115
+
116
+ config_list = XCConfigurationList()
117
+ group = PBXGroup()
118
+ project = PBXProject({'buildConfigurationList': config_list,
119
+ 'mainGroup': group})
120
+
121
+ With the project object set up, it can be added to an XCProjectFile object.
122
+ XCProjectFile is a pseudo-class in the sense that it is a concrete XCObject
123
+ subclass that does not actually correspond to a class type found in a project
124
+ file. Rather, it is used to represent the project file's root dictionary.
125
+ Printing an XCProjectFile will print the entire project file, including the
126
+ full "objects" dictionary.
127
+
128
+ project_file = XCProjectFile({'rootObject': project})
129
+ project_file.ComputeIDs()
130
+ project_file.Print()
131
+
132
+ Xcode project files are always encoded in UTF-8. This module will accept
133
+ strings of either the str class or the unicode class. Strings of class str
134
+ are assumed to already be encoded in UTF-8. Obviously, if you're just using
135
+ ASCII, you won't encounter difficulties because ASCII is a UTF-8 subset.
136
+ Strings of class unicode are handled properly and encoded in UTF-8 when
137
+ a project file is output.
138
+ """
139
+
140
+ import gyp.common
141
+ from functools import cmp_to_key
142
+ import hashlib
143
+ from operator import attrgetter
144
+ import posixpath
145
+ import re
146
+ import struct
147
+ import sys
148
+
149
+
150
+ def cmp(x, y):
151
+ return (x > y) - (x < y)
152
+
153
+
154
+ # See XCObject._EncodeString. This pattern is used to determine when a string
155
+ # can be printed unquoted. Strings that match this pattern may be printed
156
+ # unquoted. Strings that do not match must be quoted and may be further
157
+ # transformed to be properly encoded. Note that this expression matches the
158
+ # characters listed with "+", for 1 or more occurrences: if a string is empty,
159
+ # it must not match this pattern, because it needs to be encoded as "".
160
+ _unquoted = re.compile("^[A-Za-z0-9$./_]+$")
161
+
162
+ # Strings that match this pattern are quoted regardless of what _unquoted says.
163
+ # Oddly, Xcode will quote any string with a run of three or more underscores.
164
+ _quoted = re.compile("___")
165
+
166
+ # This pattern should match any character that needs to be escaped by
167
+ # XCObject._EncodeString. See that function.
168
+ _escaped = re.compile('[\\\\"]|[\x00-\x1f]')
169
+
170
+
171
+ # Used by SourceTreeAndPathFromPath
172
+ _path_leading_variable = re.compile(r"^\$\((.*?)\)(/(.*))?$")
173
+
174
+
175
+ def SourceTreeAndPathFromPath(input_path):
176
+ """Given input_path, returns a tuple with sourceTree and path values.
177
+
178
+ Examples:
179
+ input_path (source_tree, output_path)
180
+ '$(VAR)/path' ('VAR', 'path')
181
+ '$(VAR)' ('VAR', None)
182
+ 'path' (None, 'path')
183
+ """
184
+
185
+ source_group_match = _path_leading_variable.match(input_path)
186
+ if source_group_match:
187
+ source_tree = source_group_match.group(1)
188
+ output_path = source_group_match.group(3) # This may be None.
189
+ else:
190
+ source_tree = None
191
+ output_path = input_path
192
+
193
+ return (source_tree, output_path)
194
+
195
+
196
+ def ConvertVariablesToShellSyntax(input_string):
197
+ return re.sub(r"\$\((.*?)\)", "${\\1}", input_string)
198
+
199
+
200
+ class XCObject:
201
+ """The abstract base of all class types used in Xcode project files.
202
+
203
+ Class variables:
204
+ _schema: A dictionary defining the properties of this class. The keys to
205
+ _schema are string property keys as used in project files. Values
206
+ are a list of four or five elements:
207
+ [ is_list, property_type, is_strong, is_required, default ]
208
+ is_list: True if the property described is a list, as opposed
209
+ to a single element.
210
+ property_type: The type to use as the value of the property,
211
+ or if is_list is True, the type to use for each
212
+ element of the value's list. property_type must
213
+ be an XCObject subclass, or one of the built-in
214
+ types str, int, or dict.
215
+ is_strong: If property_type is an XCObject subclass, is_strong
216
+ is True to assert that this class "owns," or serves
217
+ as parent, to the property value (or, if is_list is
218
+ True, values). is_strong must be False if
219
+ property_type is not an XCObject subclass.
220
+ is_required: True if the property is required for the class.
221
+ Note that is_required being True does not preclude
222
+ an empty string ("", in the case of property_type
223
+ str) or list ([], in the case of is_list True) from
224
+ being set for the property.
225
+ default: Optional. If is_required is True, default may be set
226
+ to provide a default value for objects that do not supply
227
+ their own value. If is_required is True and default
228
+ is not provided, users of the class must supply their own
229
+ value for the property.
230
+ Note that although the values of the array are expressed in
231
+ boolean terms, subclasses provide values as integers to conserve
232
+ horizontal space.
233
+ _should_print_single_line: False in XCObject. Subclasses whose objects
234
+ should be written to the project file in the
235
+ alternate single-line format, such as
236
+ PBXFileReference and PBXBuildFile, should
237
+ set this to True.
238
+ _encode_transforms: Used by _EncodeString to encode unprintable characters.
239
+ The index into this list is the ordinal of the
240
+ character to transform; each value is a string
241
+ used to represent the character in the output. XCObject
242
+ provides an _encode_transforms list suitable for most
243
+ XCObject subclasses.
244
+ _alternate_encode_transforms: Provided for subclasses that wish to use
245
+ the alternate encoding rules. Xcode seems
246
+ to use these rules when printing objects in
247
+ single-line format. Subclasses that desire
248
+ this behavior should set _encode_transforms
249
+ to _alternate_encode_transforms.
250
+ _hashables: A list of XCObject subclasses that can be hashed by ComputeIDs
251
+ to construct this object's ID. Most classes that need custom
252
+ hashing behavior should do it by overriding Hashables,
253
+ but in some cases an object's parent may wish to push a
254
+ hashable value into its child, and it can do so by appending
255
+ to _hashables.
256
+ Attributes:
257
+ id: The object's identifier, a 24-character uppercase hexadecimal string.
258
+ Usually, objects being created should not set id until the entire
259
+ project file structure is built. At that point, UpdateIDs() should
260
+ be called on the root object to assign deterministic values for id to
261
+ each object in the tree.
262
+ parent: The object's parent. This is set by a parent XCObject when a child
263
+ object is added to it.
264
+ _properties: The object's property dictionary. An object's properties are
265
+ described by its class' _schema variable.
266
+ """
267
+
268
+ _schema = {}
269
+ _should_print_single_line = False
270
+
271
+ # See _EncodeString.
272
+ _encode_transforms = []
273
+ i = 0
274
+ while i < ord(" "):
275
+ _encode_transforms.append("\\U%04x" % i)
276
+ i = i + 1
277
+ _encode_transforms[7] = "\\a"
278
+ _encode_transforms[8] = "\\b"
279
+ _encode_transforms[9] = "\\t"
280
+ _encode_transforms[10] = "\\n"
281
+ _encode_transforms[11] = "\\v"
282
+ _encode_transforms[12] = "\\f"
283
+ _encode_transforms[13] = "\\n"
284
+
285
+ _alternate_encode_transforms = list(_encode_transforms)
286
+ _alternate_encode_transforms[9] = chr(9)
287
+ _alternate_encode_transforms[10] = chr(10)
288
+ _alternate_encode_transforms[11] = chr(11)
289
+
290
+ def __init__(self, properties=None, id=None, parent=None):
291
+ self.id = id
292
+ self.parent = parent
293
+ self._properties = {}
294
+ self._hashables = []
295
+ self._SetDefaultsFromSchema()
296
+ self.UpdateProperties(properties)
297
+
298
+ def __repr__(self):
299
+ try:
300
+ name = self.Name()
301
+ except NotImplementedError:
302
+ return f"<{self.__class__.__name__} at 0x{id(self):x}>"
303
+ return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>"
304
+
305
+ def Copy(self):
306
+ """Make a copy of this object.
307
+
308
+ The new object will have its own copy of lists and dicts. Any XCObject
309
+ objects owned by this object (marked "strong") will be copied in the
310
+ new object, even those found in lists. If this object has any weak
311
+ references to other XCObjects, the same references are added to the new
312
+ object without making a copy.
313
+ """
314
+
315
+ that = self.__class__(id=self.id, parent=self.parent)
316
+ for key, value in self._properties.items():
317
+ is_strong = self._schema[key][2]
318
+
319
+ if isinstance(value, XCObject):
320
+ if is_strong:
321
+ new_value = value.Copy()
322
+ new_value.parent = that
323
+ that._properties[key] = new_value
324
+ else:
325
+ that._properties[key] = value
326
+ elif isinstance(value, (str, int)):
327
+ that._properties[key] = value
328
+ elif isinstance(value, list):
329
+ if is_strong:
330
+ # If is_strong is True, each element is an XCObject, so it's safe to
331
+ # call Copy.
332
+ that._properties[key] = []
333
+ for item in value:
334
+ new_item = item.Copy()
335
+ new_item.parent = that
336
+ that._properties[key].append(new_item)
337
+ else:
338
+ that._properties[key] = value[:]
339
+ elif isinstance(value, dict):
340
+ # dicts are never strong.
341
+ if is_strong:
342
+ raise TypeError(
343
+ "Strong dict for key " + key + " in " + self.__class__.__name__
344
+ )
345
+ else:
346
+ that._properties[key] = value.copy()
347
+ else:
348
+ raise TypeError(
349
+ "Unexpected type "
350
+ + value.__class__.__name__
351
+ + " for key "
352
+ + key
353
+ + " in "
354
+ + self.__class__.__name__
355
+ )
356
+
357
+ return that
358
+
359
+ def Name(self):
360
+ """Return the name corresponding to an object.
361
+
362
+ Not all objects necessarily need to be nameable, and not all that do have
363
+ a "name" property. Override as needed.
364
+ """
365
+
366
+ # If the schema indicates that "name" is required, try to access the
367
+ # property even if it doesn't exist. This will result in a KeyError
368
+ # being raised for the property that should be present, which seems more
369
+ # appropriate than NotImplementedError in this case.
370
+ if "name" in self._properties or (
371
+ "name" in self._schema and self._schema["name"][3]
372
+ ):
373
+ return self._properties["name"]
374
+
375
+ raise NotImplementedError(self.__class__.__name__ + " must implement Name")
376
+
377
+ def Comment(self):
378
+ """Return a comment string for the object.
379
+
380
+ Most objects just use their name as the comment, but PBXProject uses
381
+ different values.
382
+
383
+ The returned comment is not escaped and does not have any comment marker
384
+ strings applied to it.
385
+ """
386
+
387
+ return self.Name()
388
+
389
+ def Hashables(self):
390
+ hashables = [self.__class__.__name__]
391
+
392
+ name = self.Name()
393
+ if name is not None:
394
+ hashables.append(name)
395
+
396
+ hashables.extend(self._hashables)
397
+
398
+ return hashables
399
+
400
+ def HashablesForChild(self):
401
+ return None
402
+
403
+ def ComputeIDs(self, recursive=True, overwrite=True, seed_hash=None):
404
+ """Set "id" properties deterministically.
405
+
406
+ An object's "id" property is set based on a hash of its class type and
407
+ name, as well as the class type and name of all ancestor objects. As
408
+ such, it is only advisable to call ComputeIDs once an entire project file
409
+ tree is built.
410
+
411
+ If recursive is True, recurse into all descendant objects and update their
412
+ hashes.
413
+
414
+ If overwrite is True, any existing value set in the "id" property will be
415
+ replaced.
416
+ """
417
+
418
+ def _HashUpdate(hash, data):
419
+ """Update hash with data's length and contents.
420
+
421
+ If the hash were updated only with the value of data, it would be
422
+ possible for clowns to induce collisions by manipulating the names of
423
+ their objects. By adding the length, it's exceedingly less likely that
424
+ ID collisions will be encountered, intentionally or not.
425
+ """
426
+
427
+ hash.update(struct.pack(">i", len(data)))
428
+ if isinstance(data, str):
429
+ data = data.encode("utf-8")
430
+ hash.update(data)
431
+
432
+ if seed_hash is None:
433
+ seed_hash = hashlib.sha1()
434
+
435
+ hash = seed_hash.copy()
436
+
437
+ hashables = self.Hashables()
438
+ assert len(hashables) > 0
439
+ for hashable in hashables:
440
+ _HashUpdate(hash, hashable)
441
+
442
+ if recursive:
443
+ hashables_for_child = self.HashablesForChild()
444
+ if hashables_for_child is None:
445
+ child_hash = hash
446
+ else:
447
+ assert len(hashables_for_child) > 0
448
+ child_hash = seed_hash.copy()
449
+ for hashable in hashables_for_child:
450
+ _HashUpdate(child_hash, hashable)
451
+
452
+ for child in self.Children():
453
+ child.ComputeIDs(recursive, overwrite, child_hash)
454
+
455
+ if overwrite or self.id is None:
456
+ # Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is
457
+ # is 160 bits. Instead of throwing out 64 bits of the digest, xor them
458
+ # into the portion that gets used.
459
+ assert hash.digest_size % 4 == 0
460
+ digest_int_count = hash.digest_size // 4
461
+ digest_ints = struct.unpack(">" + "I" * digest_int_count, hash.digest())
462
+ id_ints = [0, 0, 0]
463
+ for index in range(0, digest_int_count):
464
+ id_ints[index % 3] ^= digest_ints[index]
465
+ self.id = "%08X%08X%08X" % tuple(id_ints)
466
+
467
+ def EnsureNoIDCollisions(self):
468
+ """Verifies that no two objects have the same ID. Checks all descendants.
469
+ """
470
+
471
+ ids = {}
472
+ descendants = self.Descendants()
473
+ for descendant in descendants:
474
+ if descendant.id in ids:
475
+ other = ids[descendant.id]
476
+ raise KeyError(
477
+ 'Duplicate ID %s, objects "%s" and "%s" in "%s"'
478
+ % (
479
+ descendant.id,
480
+ str(descendant._properties),
481
+ str(other._properties),
482
+ self._properties["rootObject"].Name(),
483
+ )
484
+ )
485
+ ids[descendant.id] = descendant
486
+
487
+ def Children(self):
488
+ """Returns a list of all of this object's owned (strong) children."""
489
+
490
+ children = []
491
+ for property, attributes in self._schema.items():
492
+ (is_list, property_type, is_strong) = attributes[0:3]
493
+ if is_strong and property in self._properties:
494
+ if not is_list:
495
+ children.append(self._properties[property])
496
+ else:
497
+ children.extend(self._properties[property])
498
+ return children
499
+
500
+ def Descendants(self):
501
+ """Returns a list of all of this object's descendants, including this
502
+ object.
503
+ """
504
+
505
+ children = self.Children()
506
+ descendants = [self]
507
+ for child in children:
508
+ descendants.extend(child.Descendants())
509
+ return descendants
510
+
511
+ def PBXProjectAncestor(self):
512
+ # The base case for recursion is defined at PBXProject.PBXProjectAncestor.
513
+ if self.parent:
514
+ return self.parent.PBXProjectAncestor()
515
+ return None
516
+
517
+ def _EncodeComment(self, comment):
518
+ """Encodes a comment to be placed in the project file output, mimicking
519
+ Xcode behavior.
520
+ """
521
+
522
+ # This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If
523
+ # the string already contains a "*/", it is turned into "(*)/". This keeps
524
+ # the file writer from outputting something that would be treated as the
525
+ # end of a comment in the middle of something intended to be entirely a
526
+ # comment.
527
+
528
+ return "/* " + comment.replace("*/", "(*)/") + " */"
529
+
530
+ def _EncodeTransform(self, match):
531
+ # This function works closely with _EncodeString. It will only be called
532
+ # by re.sub with match.group(0) containing a character matched by the
533
+ # the _escaped expression.
534
+ char = match.group(0)
535
+
536
+ # Backslashes (\) and quotation marks (") are always replaced with a
537
+ # backslash-escaped version of the same. Everything else gets its
538
+ # replacement from the class' _encode_transforms array.
539
+ if char == "\\":
540
+ return "\\\\"
541
+ if char == '"':
542
+ return '\\"'
543
+ return self._encode_transforms[ord(char)]
544
+
545
+ def _EncodeString(self, value):
546
+ """Encodes a string to be placed in the project file output, mimicking
547
+ Xcode behavior.
548
+ """
549
+
550
+ # Use quotation marks when any character outside of the range A-Z, a-z, 0-9,
551
+ # $ (dollar sign), . (period), and _ (underscore) is present. Also use
552
+ # quotation marks to represent empty strings.
553
+ #
554
+ # Escape " (double-quote) and \ (backslash) by preceding them with a
555
+ # backslash.
556
+ #
557
+ # Some characters below the printable ASCII range are encoded specially:
558
+ # 7 ^G BEL is encoded as "\a"
559
+ # 8 ^H BS is encoded as "\b"
560
+ # 11 ^K VT is encoded as "\v"
561
+ # 12 ^L NP is encoded as "\f"
562
+ # 127 ^? DEL is passed through as-is without escaping
563
+ # - In PBXFileReference and PBXBuildFile objects:
564
+ # 9 ^I HT is passed through as-is without escaping
565
+ # 10 ^J NL is passed through as-is without escaping
566
+ # 13 ^M CR is passed through as-is without escaping
567
+ # - In other objects:
568
+ # 9 ^I HT is encoded as "\t"
569
+ # 10 ^J NL is encoded as "\n"
570
+ # 13 ^M CR is encoded as "\n" rendering it indistinguishable from
571
+ # 10 ^J NL
572
+ # All other characters within the ASCII control character range (0 through
573
+ # 31 inclusive) are encoded as "\U001f" referring to the Unicode code point
574
+ # in hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e".
575
+ # Characters above the ASCII range are passed through to the output encoded
576
+ # as UTF-8 without any escaping. These mappings are contained in the
577
+ # class' _encode_transforms list.
578
+
579
+ if _unquoted.search(value) and not _quoted.search(value):
580
+ return value
581
+
582
+ return '"' + _escaped.sub(self._EncodeTransform, value) + '"'
583
+
584
+ def _XCPrint(self, file, tabs, line):
585
+ file.write("\t" * tabs + line)
586
+
587
+ def _XCPrintableValue(self, tabs, value, flatten_list=False):
588
+ """Returns a representation of value that may be printed in a project file,
589
+ mimicking Xcode's behavior.
590
+
591
+ _XCPrintableValue can handle str and int values, XCObjects (which are
592
+ made printable by returning their id property), and list and dict objects
593
+ composed of any of the above types. When printing a list or dict, and
594
+ _should_print_single_line is False, the tabs parameter is used to determine
595
+ how much to indent the lines corresponding to the items in the list or
596
+ dict.
597
+
598
+ If flatten_list is True, single-element lists will be transformed into
599
+ strings.
600
+ """
601
+
602
+ printable = ""
603
+ comment = None
604
+
605
+ if self._should_print_single_line:
606
+ sep = " "
607
+ element_tabs = ""
608
+ end_tabs = ""
609
+ else:
610
+ sep = "\n"
611
+ element_tabs = "\t" * (tabs + 1)
612
+ end_tabs = "\t" * tabs
613
+
614
+ if isinstance(value, XCObject):
615
+ printable += value.id
616
+ comment = value.Comment()
617
+ elif isinstance(value, str):
618
+ printable += self._EncodeString(value)
619
+ elif isinstance(value, str):
620
+ printable += self._EncodeString(value.encode("utf-8"))
621
+ elif isinstance(value, int):
622
+ printable += str(value)
623
+ elif isinstance(value, list):
624
+ if flatten_list and len(value) <= 1:
625
+ if len(value) == 0:
626
+ printable += self._EncodeString("")
627
+ else:
628
+ printable += self._EncodeString(value[0])
629
+ else:
630
+ printable = "(" + sep
631
+ for item in value:
632
+ printable += (
633
+ element_tabs
634
+ + self._XCPrintableValue(tabs + 1, item, flatten_list)
635
+ + ","
636
+ + sep
637
+ )
638
+ printable += end_tabs + ")"
639
+ elif isinstance(value, dict):
640
+ printable = "{" + sep
641
+ for item_key, item_value in sorted(value.items()):
642
+ printable += (
643
+ element_tabs
644
+ + self._XCPrintableValue(tabs + 1, item_key, flatten_list)
645
+ + " = "
646
+ + self._XCPrintableValue(tabs + 1, item_value, flatten_list)
647
+ + ";"
648
+ + sep
649
+ )
650
+ printable += end_tabs + "}"
651
+ else:
652
+ raise TypeError("Can't make " + value.__class__.__name__ + " printable")
653
+
654
+ if comment:
655
+ printable += " " + self._EncodeComment(comment)
656
+
657
+ return printable
658
+
659
+ def _XCKVPrint(self, file, tabs, key, value):
660
+ """Prints a key and value, members of an XCObject's _properties dictionary,
661
+ to file.
662
+
663
+ tabs is an int identifying the indentation level. If the class'
664
+ _should_print_single_line variable is True, tabs is ignored and the
665
+ key-value pair will be followed by a space insead of a newline.
666
+ """
667
+
668
+ if self._should_print_single_line:
669
+ printable = ""
670
+ after_kv = " "
671
+ else:
672
+ printable = "\t" * tabs
673
+ after_kv = "\n"
674
+
675
+ # Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy
676
+ # objects without comments. Sometimes it prints them with comments, but
677
+ # the majority of the time, it doesn't. To avoid unnecessary changes to
678
+ # the project file after Xcode opens it, don't write comments for
679
+ # remoteGlobalIDString. This is a sucky hack and it would certainly be
680
+ # cleaner to extend the schema to indicate whether or not a comment should
681
+ # be printed, but since this is the only case where the problem occurs and
682
+ # Xcode itself can't seem to make up its mind, the hack will suffice.
683
+ #
684
+ # Also see PBXContainerItemProxy._schema['remoteGlobalIDString'].
685
+ if key == "remoteGlobalIDString" and isinstance(self, PBXContainerItemProxy):
686
+ value_to_print = value.id
687
+ else:
688
+ value_to_print = value
689
+
690
+ # PBXBuildFile's settings property is represented in the output as a dict,
691
+ # but a hack here has it represented as a string. Arrange to strip off the
692
+ # quotes so that it shows up in the output as expected.
693
+ if key == "settings" and isinstance(self, PBXBuildFile):
694
+ strip_value_quotes = True
695
+ else:
696
+ strip_value_quotes = False
697
+
698
+ # In another one-off, let's set flatten_list on buildSettings properties
699
+ # of XCBuildConfiguration objects, because that's how Xcode treats them.
700
+ if key == "buildSettings" and isinstance(self, XCBuildConfiguration):
701
+ flatten_list = True
702
+ else:
703
+ flatten_list = False
704
+
705
+ try:
706
+ printable_key = self._XCPrintableValue(tabs, key, flatten_list)
707
+ printable_value = self._XCPrintableValue(tabs, value_to_print, flatten_list)
708
+ if (
709
+ strip_value_quotes
710
+ and len(printable_value) > 1
711
+ and printable_value[0] == '"'
712
+ and printable_value[-1] == '"'
713
+ ):
714
+ printable_value = printable_value[1:-1]
715
+ printable += printable_key + " = " + printable_value + ";" + after_kv
716
+ except TypeError as e:
717
+ gyp.common.ExceptionAppend(e, 'while printing key "%s"' % key)
718
+ raise
719
+
720
+ self._XCPrint(file, 0, printable)
721
+
722
+ def Print(self, file=sys.stdout):
723
+ """Prints a reprentation of this object to file, adhering to Xcode output
724
+ formatting.
725
+ """
726
+
727
+ self.VerifyHasRequiredProperties()
728
+
729
+ if self._should_print_single_line:
730
+ # When printing an object in a single line, Xcode doesn't put any space
731
+ # between the beginning of a dictionary (or presumably a list) and the
732
+ # first contained item, so you wind up with snippets like
733
+ # ...CDEF = {isa = PBXFileReference; fileRef = 0123...
734
+ # If it were me, I would have put a space in there after the opening
735
+ # curly, but I guess this is just another one of those inconsistencies
736
+ # between how Xcode prints PBXFileReference and PBXBuildFile objects as
737
+ # compared to other objects. Mimic Xcode's behavior here by using an
738
+ # empty string for sep.
739
+ sep = ""
740
+ end_tabs = 0
741
+ else:
742
+ sep = "\n"
743
+ end_tabs = 2
744
+
745
+ # Start the object. For example, '\t\tPBXProject = {\n'.
746
+ self._XCPrint(file, 2, self._XCPrintableValue(2, self) + " = {" + sep)
747
+
748
+ # "isa" isn't in the _properties dictionary, it's an intrinsic property
749
+ # of the class which the object belongs to. Xcode always outputs "isa"
750
+ # as the first element of an object dictionary.
751
+ self._XCKVPrint(file, 3, "isa", self.__class__.__name__)
752
+
753
+ # The remaining elements of an object dictionary are sorted alphabetically.
754
+ for property, value in sorted(self._properties.items()):
755
+ self._XCKVPrint(file, 3, property, value)
756
+
757
+ # End the object.
758
+ self._XCPrint(file, end_tabs, "};\n")
759
+
760
+ def UpdateProperties(self, properties, do_copy=False):
761
+ """Merge the supplied properties into the _properties dictionary.
762
+
763
+ The input properties must adhere to the class schema or a KeyError or
764
+ TypeError exception will be raised. If adding an object of an XCObject
765
+ subclass and the schema indicates a strong relationship, the object's
766
+ parent will be set to this object.
767
+
768
+ If do_copy is True, then lists, dicts, strong-owned XCObjects, and
769
+ strong-owned XCObjects in lists will be copied instead of having their
770
+ references added.
771
+ """
772
+
773
+ if properties is None:
774
+ return
775
+
776
+ for property, value in properties.items():
777
+ # Make sure the property is in the schema.
778
+ if property not in self._schema:
779
+ raise KeyError(property + " not in " + self.__class__.__name__)
780
+
781
+ # Make sure the property conforms to the schema.
782
+ (is_list, property_type, is_strong) = self._schema[property][0:3]
783
+ if is_list:
784
+ if value.__class__ != list:
785
+ raise TypeError(
786
+ property
787
+ + " of "
788
+ + self.__class__.__name__
789
+ + " must be list, not "
790
+ + value.__class__.__name__
791
+ )
792
+ for item in value:
793
+ if not isinstance(item, property_type) and not (
794
+ isinstance(item, str) and property_type == str
795
+ ):
796
+ # Accept unicode where str is specified. str is treated as
797
+ # UTF-8-encoded.
798
+ raise TypeError(
799
+ "item of "
800
+ + property
801
+ + " of "
802
+ + self.__class__.__name__
803
+ + " must be "
804
+ + property_type.__name__
805
+ + ", not "
806
+ + item.__class__.__name__
807
+ )
808
+ elif not isinstance(value, property_type) and not (
809
+ isinstance(value, str) and property_type == str
810
+ ):
811
+ # Accept unicode where str is specified. str is treated as
812
+ # UTF-8-encoded.
813
+ raise TypeError(
814
+ property
815
+ + " of "
816
+ + self.__class__.__name__
817
+ + " must be "
818
+ + property_type.__name__
819
+ + ", not "
820
+ + value.__class__.__name__
821
+ )
822
+
823
+ # Checks passed, perform the assignment.
824
+ if do_copy:
825
+ if isinstance(value, XCObject):
826
+ if is_strong:
827
+ self._properties[property] = value.Copy()
828
+ else:
829
+ self._properties[property] = value
830
+ elif isinstance(value, (str, int)):
831
+ self._properties[property] = value
832
+ elif isinstance(value, list):
833
+ if is_strong:
834
+ # If is_strong is True, each element is an XCObject,
835
+ # so it's safe to call Copy.
836
+ self._properties[property] = []
837
+ for item in value:
838
+ self._properties[property].append(item.Copy())
839
+ else:
840
+ self._properties[property] = value[:]
841
+ elif isinstance(value, dict):
842
+ self._properties[property] = value.copy()
843
+ else:
844
+ raise TypeError(
845
+ "Don't know how to copy a "
846
+ + value.__class__.__name__
847
+ + " object for "
848
+ + property
849
+ + " in "
850
+ + self.__class__.__name__
851
+ )
852
+ else:
853
+ self._properties[property] = value
854
+
855
+ # Set up the child's back-reference to this object. Don't use |value|
856
+ # any more because it may not be right if do_copy is true.
857
+ if is_strong:
858
+ if not is_list:
859
+ self._properties[property].parent = self
860
+ else:
861
+ for item in self._properties[property]:
862
+ item.parent = self
863
+
864
+ def HasProperty(self, key):
865
+ return key in self._properties
866
+
867
+ def GetProperty(self, key):
868
+ return self._properties[key]
869
+
870
+ def SetProperty(self, key, value):
871
+ self.UpdateProperties({key: value})
872
+
873
+ def DelProperty(self, key):
874
+ if key in self._properties:
875
+ del self._properties[key]
876
+
877
+ def AppendProperty(self, key, value):
878
+ # TODO(mark): Support ExtendProperty too (and make this call that)?
879
+
880
+ # Schema validation.
881
+ if key not in self._schema:
882
+ raise KeyError(key + " not in " + self.__class__.__name__)
883
+
884
+ (is_list, property_type, is_strong) = self._schema[key][0:3]
885
+ if not is_list:
886
+ raise TypeError(key + " of " + self.__class__.__name__ + " must be list")
887
+ if not isinstance(value, property_type):
888
+ raise TypeError(
889
+ "item of "
890
+ + key
891
+ + " of "
892
+ + self.__class__.__name__
893
+ + " must be "
894
+ + property_type.__name__
895
+ + ", not "
896
+ + value.__class__.__name__
897
+ )
898
+
899
+ # If the property doesn't exist yet, create a new empty list to receive the
900
+ # item.
901
+ self._properties[key] = self._properties.get(key, [])
902
+
903
+ # Set up the ownership link.
904
+ if is_strong:
905
+ value.parent = self
906
+
907
+ # Store the item.
908
+ self._properties[key].append(value)
909
+
910
+ def VerifyHasRequiredProperties(self):
911
+ """Ensure that all properties identified as required by the schema are
912
+ set.
913
+ """
914
+
915
+ # TODO(mark): A stronger verification mechanism is needed. Some
916
+ # subclasses need to perform validation beyond what the schema can enforce.
917
+ for property, attributes in self._schema.items():
918
+ (is_list, property_type, is_strong, is_required) = attributes[0:4]
919
+ if is_required and property not in self._properties:
920
+ raise KeyError(self.__class__.__name__ + " requires " + property)
921
+
922
+ def _SetDefaultsFromSchema(self):
923
+ """Assign object default values according to the schema. This will not
924
+ overwrite properties that have already been set."""
925
+
926
+ defaults = {}
927
+ for property, attributes in self._schema.items():
928
+ (is_list, property_type, is_strong, is_required) = attributes[0:4]
929
+ if (
930
+ is_required
931
+ and len(attributes) >= 5
932
+ and property not in self._properties
933
+ ):
934
+ default = attributes[4]
935
+
936
+ defaults[property] = default
937
+
938
+ if len(defaults) > 0:
939
+ # Use do_copy=True so that each new object gets its own copy of strong
940
+ # objects, lists, and dicts.
941
+ self.UpdateProperties(defaults, do_copy=True)
942
+
943
+
944
+ class XCHierarchicalElement(XCObject):
945
+ """Abstract base for PBXGroup and PBXFileReference. Not represented in a
946
+ project file."""
947
+
948
+ # TODO(mark): Do name and path belong here? Probably so.
949
+ # If path is set and name is not, name may have a default value. Name will
950
+ # be set to the basename of path, if the basename of path is different from
951
+ # the full value of path. If path is already just a leaf name, name will
952
+ # not be set.
953
+ _schema = XCObject._schema.copy()
954
+ _schema.update(
955
+ {
956
+ "comments": [0, str, 0, 0],
957
+ "fileEncoding": [0, str, 0, 0],
958
+ "includeInIndex": [0, int, 0, 0],
959
+ "indentWidth": [0, int, 0, 0],
960
+ "lineEnding": [0, int, 0, 0],
961
+ "sourceTree": [0, str, 0, 1, "<group>"],
962
+ "tabWidth": [0, int, 0, 0],
963
+ "usesTabs": [0, int, 0, 0],
964
+ "wrapsLines": [0, int, 0, 0],
965
+ }
966
+ )
967
+
968
+ def __init__(self, properties=None, id=None, parent=None):
969
+ # super
970
+ XCObject.__init__(self, properties, id, parent)
971
+ if "path" in self._properties and "name" not in self._properties:
972
+ path = self._properties["path"]
973
+ name = posixpath.basename(path)
974
+ if name != "" and path != name:
975
+ self.SetProperty("name", name)
976
+
977
+ if "path" in self._properties and (
978
+ "sourceTree" not in self._properties
979
+ or self._properties["sourceTree"] == "<group>"
980
+ ):
981
+ # If the pathname begins with an Xcode variable like "$(SDKROOT)/", take
982
+ # the variable out and make the path be relative to that variable by
983
+ # assigning the variable name as the sourceTree.
984
+ (source_tree, path) = SourceTreeAndPathFromPath(self._properties["path"])
985
+ if source_tree is not None:
986
+ self._properties["sourceTree"] = source_tree
987
+ if path is not None:
988
+ self._properties["path"] = path
989
+ if (
990
+ source_tree is not None
991
+ and path is None
992
+ and "name" not in self._properties
993
+ ):
994
+ # The path was of the form "$(SDKROOT)" with no path following it.
995
+ # This object is now relative to that variable, so it has no path
996
+ # attribute of its own. It does, however, keep a name.
997
+ del self._properties["path"]
998
+ self._properties["name"] = source_tree
999
+
1000
+ def Name(self):
1001
+ if "name" in self._properties:
1002
+ return self._properties["name"]
1003
+ elif "path" in self._properties:
1004
+ return self._properties["path"]
1005
+ else:
1006
+ # This happens in the case of the root PBXGroup.
1007
+ return None
1008
+
1009
+ def Hashables(self):
1010
+ """Custom hashables for XCHierarchicalElements.
1011
+
1012
+ XCHierarchicalElements are special. Generally, their hashes shouldn't
1013
+ change if the paths don't change. The normal XCObject implementation of
1014
+ Hashables adds a hashable for each object, which means that if
1015
+ the hierarchical structure changes (possibly due to changes caused when
1016
+ TakeOverOnlyChild runs and encounters slight changes in the hierarchy),
1017
+ the hashes will change. For example, if a project file initially contains
1018
+ a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent
1019
+ a/b. If someone later adds a/f2 to the project file, a/b can no longer be
1020
+ collapsed, and f1 winds up with parent b and grandparent a. That would
1021
+ be sufficient to change f1's hash.
1022
+
1023
+ To counteract this problem, hashables for all XCHierarchicalElements except
1024
+ for the main group (which has neither a name nor a path) are taken to be
1025
+ just the set of path components. Because hashables are inherited from
1026
+ parents, this provides assurance that a/b/f1 has the same set of hashables
1027
+ whether its parent is b or a/b.
1028
+
1029
+ The main group is a special case. As it is permitted to have no name or
1030
+ path, it is permitted to use the standard XCObject hash mechanism. This
1031
+ is not considered a problem because there can be only one main group.
1032
+ """
1033
+
1034
+ if self == self.PBXProjectAncestor()._properties["mainGroup"]:
1035
+ # super
1036
+ return XCObject.Hashables(self)
1037
+
1038
+ hashables = []
1039
+
1040
+ # Put the name in first, ensuring that if TakeOverOnlyChild collapses
1041
+ # children into a top-level group like "Source", the name always goes
1042
+ # into the list of hashables without interfering with path components.
1043
+ if "name" in self._properties:
1044
+ # Make it less likely for people to manipulate hashes by following the
1045
+ # pattern of always pushing an object type value onto the list first.
1046
+ hashables.append(self.__class__.__name__ + ".name")
1047
+ hashables.append(self._properties["name"])
1048
+
1049
+ # NOTE: This still has the problem that if an absolute path is encountered,
1050
+ # including paths with a sourceTree, they'll still inherit their parents'
1051
+ # hashables, even though the paths aren't relative to their parents. This
1052
+ # is not expected to be much of a problem in practice.
1053
+ path = self.PathFromSourceTreeAndPath()
1054
+ if path is not None:
1055
+ components = path.split(posixpath.sep)
1056
+ for component in components:
1057
+ hashables.append(self.__class__.__name__ + ".path")
1058
+ hashables.append(component)
1059
+
1060
+ hashables.extend(self._hashables)
1061
+
1062
+ return hashables
1063
+
1064
+ def Compare(self, other):
1065
+ # Allow comparison of these types. PBXGroup has the highest sort rank;
1066
+ # PBXVariantGroup is treated as equal to PBXFileReference.
1067
+ valid_class_types = {
1068
+ PBXFileReference: "file",
1069
+ PBXGroup: "group",
1070
+ PBXVariantGroup: "file",
1071
+ }
1072
+ self_type = valid_class_types[self.__class__]
1073
+ other_type = valid_class_types[other.__class__]
1074
+
1075
+ if self_type == other_type:
1076
+ # If the two objects are of the same sort rank, compare their names.
1077
+ return cmp(self.Name(), other.Name())
1078
+
1079
+ # Otherwise, sort groups before everything else.
1080
+ if self_type == "group":
1081
+ return -1
1082
+ return 1
1083
+
1084
+ def CompareRootGroup(self, other):
1085
+ # This function should be used only to compare direct children of the
1086
+ # containing PBXProject's mainGroup. These groups should appear in the
1087
+ # listed order.
1088
+ # TODO(mark): "Build" is used by gyp.generator.xcode, perhaps the
1089
+ # generator should have a way of influencing this list rather than having
1090
+ # to hardcode for the generator here.
1091
+ order = [
1092
+ "Source",
1093
+ "Intermediates",
1094
+ "Projects",
1095
+ "Frameworks",
1096
+ "Products",
1097
+ "Build",
1098
+ ]
1099
+
1100
+ # If the groups aren't in the listed order, do a name comparison.
1101
+ # Otherwise, groups in the listed order should come before those that
1102
+ # aren't.
1103
+ self_name = self.Name()
1104
+ other_name = other.Name()
1105
+ self_in = isinstance(self, PBXGroup) and self_name in order
1106
+ other_in = isinstance(self, PBXGroup) and other_name in order
1107
+ if not self_in and not other_in:
1108
+ return self.Compare(other)
1109
+ if self_name in order and other_name not in order:
1110
+ return -1
1111
+ if other_name in order and self_name not in order:
1112
+ return 1
1113
+
1114
+ # If both groups are in the listed order, go by the defined order.
1115
+ self_index = order.index(self_name)
1116
+ other_index = order.index(other_name)
1117
+ if self_index < other_index:
1118
+ return -1
1119
+ if self_index > other_index:
1120
+ return 1
1121
+ return 0
1122
+
1123
+ def PathFromSourceTreeAndPath(self):
1124
+ # Turn the object's sourceTree and path properties into a single flat
1125
+ # string of a form comparable to the path parameter. If there's a
1126
+ # sourceTree property other than "<group>", wrap it in $(...) for the
1127
+ # comparison.
1128
+ components = []
1129
+ if self._properties["sourceTree"] != "<group>":
1130
+ components.append("$(" + self._properties["sourceTree"] + ")")
1131
+ if "path" in self._properties:
1132
+ components.append(self._properties["path"])
1133
+
1134
+ if len(components) > 0:
1135
+ return posixpath.join(*components)
1136
+
1137
+ return None
1138
+
1139
+ def FullPath(self):
1140
+ # Returns a full path to self relative to the project file, or relative
1141
+ # to some other source tree. Start with self, and walk up the chain of
1142
+ # parents prepending their paths, if any, until no more parents are
1143
+ # available (project-relative path) or until a path relative to some
1144
+ # source tree is found.
1145
+ xche = self
1146
+ path = None
1147
+ while isinstance(xche, XCHierarchicalElement) and (
1148
+ path is None or (not path.startswith("/") and not path.startswith("$"))
1149
+ ):
1150
+ this_path = xche.PathFromSourceTreeAndPath()
1151
+ if this_path is not None and path is not None:
1152
+ path = posixpath.join(this_path, path)
1153
+ elif this_path is not None:
1154
+ path = this_path
1155
+ xche = xche.parent
1156
+
1157
+ return path
1158
+
1159
+
1160
+ class PBXGroup(XCHierarchicalElement):
1161
+ """
1162
+ Attributes:
1163
+ _children_by_path: Maps pathnames of children of this PBXGroup to the
1164
+ actual child XCHierarchicalElement objects.
1165
+ _variant_children_by_name_and_path: Maps (name, path) tuples of
1166
+ PBXVariantGroup children to the actual child PBXVariantGroup objects.
1167
+ """
1168
+
1169
+ _schema = XCHierarchicalElement._schema.copy()
1170
+ _schema.update(
1171
+ {
1172
+ "children": [1, XCHierarchicalElement, 1, 1, []],
1173
+ "name": [0, str, 0, 0],
1174
+ "path": [0, str, 0, 0],
1175
+ }
1176
+ )
1177
+
1178
+ def __init__(self, properties=None, id=None, parent=None):
1179
+ # super
1180
+ XCHierarchicalElement.__init__(self, properties, id, parent)
1181
+ self._children_by_path = {}
1182
+ self._variant_children_by_name_and_path = {}
1183
+ for child in self._properties.get("children", []):
1184
+ self._AddChildToDicts(child)
1185
+
1186
+ def Hashables(self):
1187
+ # super
1188
+ hashables = XCHierarchicalElement.Hashables(self)
1189
+
1190
+ # It is not sufficient to just rely on name and parent to build a unique
1191
+ # hashable : a node could have two child PBXGroup sharing a common name.
1192
+ # To add entropy the hashable is enhanced with the names of all its
1193
+ # children.
1194
+ for child in self._properties.get("children", []):
1195
+ child_name = child.Name()
1196
+ if child_name is not None:
1197
+ hashables.append(child_name)
1198
+
1199
+ return hashables
1200
+
1201
+ def HashablesForChild(self):
1202
+ # To avoid a circular reference the hashables used to compute a child id do
1203
+ # not include the child names.
1204
+ return XCHierarchicalElement.Hashables(self)
1205
+
1206
+ def _AddChildToDicts(self, child):
1207
+ # Sets up this PBXGroup object's dicts to reference the child properly.
1208
+ child_path = child.PathFromSourceTreeAndPath()
1209
+ if child_path:
1210
+ if child_path in self._children_by_path:
1211
+ raise ValueError("Found multiple children with path " + child_path)
1212
+ self._children_by_path[child_path] = child
1213
+
1214
+ if isinstance(child, PBXVariantGroup):
1215
+ child_name = child._properties.get("name", None)
1216
+ key = (child_name, child_path)
1217
+ if key in self._variant_children_by_name_and_path:
1218
+ raise ValueError(
1219
+ "Found multiple PBXVariantGroup children with "
1220
+ + "name "
1221
+ + str(child_name)
1222
+ + " and path "
1223
+ + str(child_path)
1224
+ )
1225
+ self._variant_children_by_name_and_path[key] = child
1226
+
1227
+ def AppendChild(self, child):
1228
+ # Callers should use this instead of calling
1229
+ # AppendProperty('children', child) directly because this function
1230
+ # maintains the group's dicts.
1231
+ self.AppendProperty("children", child)
1232
+ self._AddChildToDicts(child)
1233
+
1234
+ def GetChildByName(self, name):
1235
+ # This is not currently optimized with a dict as GetChildByPath is because
1236
+ # it has few callers. Most callers probably want GetChildByPath. This
1237
+ # function is only useful to get children that have names but no paths,
1238
+ # which is rare. The children of the main group ("Source", "Products",
1239
+ # etc.) is pretty much the only case where this likely to come up.
1240
+ #
1241
+ # TODO(mark): Maybe this should raise an error if more than one child is
1242
+ # present with the same name.
1243
+ if "children" not in self._properties:
1244
+ return None
1245
+
1246
+ for child in self._properties["children"]:
1247
+ if child.Name() == name:
1248
+ return child
1249
+
1250
+ return None
1251
+
1252
+ def GetChildByPath(self, path):
1253
+ if not path:
1254
+ return None
1255
+
1256
+ if path in self._children_by_path:
1257
+ return self._children_by_path[path]
1258
+
1259
+ return None
1260
+
1261
+ def GetChildByRemoteObject(self, remote_object):
1262
+ # This method is a little bit esoteric. Given a remote_object, which
1263
+ # should be a PBXFileReference in another project file, this method will
1264
+ # return this group's PBXReferenceProxy object serving as a local proxy
1265
+ # for the remote PBXFileReference.
1266
+ #
1267
+ # This function might benefit from a dict optimization as GetChildByPath
1268
+ # for some workloads, but profiling shows that it's not currently a
1269
+ # problem.
1270
+ if "children" not in self._properties:
1271
+ return None
1272
+
1273
+ for child in self._properties["children"]:
1274
+ if not isinstance(child, PBXReferenceProxy):
1275
+ continue
1276
+
1277
+ container_proxy = child._properties["remoteRef"]
1278
+ if container_proxy._properties["remoteGlobalIDString"] == remote_object:
1279
+ return child
1280
+
1281
+ return None
1282
+
1283
+ def AddOrGetFileByPath(self, path, hierarchical):
1284
+ """Returns an existing or new file reference corresponding to path.
1285
+
1286
+ If hierarchical is True, this method will create or use the necessary
1287
+ hierarchical group structure corresponding to path. Otherwise, it will
1288
+ look in and create an item in the current group only.
1289
+
1290
+ If an existing matching reference is found, it is returned, otherwise, a
1291
+ new one will be created, added to the correct group, and returned.
1292
+
1293
+ If path identifies a directory by virtue of carrying a trailing slash,
1294
+ this method returns a PBXFileReference of "folder" type. If path
1295
+ identifies a variant, by virtue of it identifying a file inside a directory
1296
+ with an ".lproj" extension, this method returns a PBXVariantGroup
1297
+ containing the variant named by path, and possibly other variants. For
1298
+ all other paths, a "normal" PBXFileReference will be returned.
1299
+ """
1300
+
1301
+ # Adding or getting a directory? Directories end with a trailing slash.
1302
+ is_dir = False
1303
+ if path.endswith("/"):
1304
+ is_dir = True
1305
+ path = posixpath.normpath(path)
1306
+ if is_dir:
1307
+ path = path + "/"
1308
+
1309
+ # Adding or getting a variant? Variants are files inside directories
1310
+ # with an ".lproj" extension. Xcode uses variants for localization. For
1311
+ # a variant path/to/Language.lproj/MainMenu.nib, put a variant group named
1312
+ # MainMenu.nib inside path/to, and give it a variant named Language. In
1313
+ # this example, grandparent would be set to path/to and parent_root would
1314
+ # be set to Language.
1315
+ variant_name = None
1316
+ parent = posixpath.dirname(path)
1317
+ grandparent = posixpath.dirname(parent)
1318
+ parent_basename = posixpath.basename(parent)
1319
+ (parent_root, parent_ext) = posixpath.splitext(parent_basename)
1320
+ if parent_ext == ".lproj":
1321
+ variant_name = parent_root
1322
+ if grandparent == "":
1323
+ grandparent = None
1324
+
1325
+ # Putting a directory inside a variant group is not currently supported.
1326
+ assert not is_dir or variant_name is None
1327
+
1328
+ path_split = path.split(posixpath.sep)
1329
+ if (
1330
+ len(path_split) == 1
1331
+ or ((is_dir or variant_name is not None) and len(path_split) == 2)
1332
+ or not hierarchical
1333
+ ):
1334
+ # The PBXFileReference or PBXVariantGroup will be added to or gotten from
1335
+ # this PBXGroup, no recursion necessary.
1336
+ if variant_name is None:
1337
+ # Add or get a PBXFileReference.
1338
+ file_ref = self.GetChildByPath(path)
1339
+ if file_ref is not None:
1340
+ assert file_ref.__class__ == PBXFileReference
1341
+ else:
1342
+ file_ref = PBXFileReference({"path": path})
1343
+ self.AppendChild(file_ref)
1344
+ else:
1345
+ # Add or get a PBXVariantGroup. The variant group name is the same
1346
+ # as the basename (MainMenu.nib in the example above). grandparent
1347
+ # specifies the path to the variant group itself, and path_split[-2:]
1348
+ # is the path of the specific variant relative to its group.
1349
+ variant_group_name = posixpath.basename(path)
1350
+ variant_group_ref = self.AddOrGetVariantGroupByNameAndPath(
1351
+ variant_group_name, grandparent
1352
+ )
1353
+ variant_path = posixpath.sep.join(path_split[-2:])
1354
+ variant_ref = variant_group_ref.GetChildByPath(variant_path)
1355
+ if variant_ref is not None:
1356
+ assert variant_ref.__class__ == PBXFileReference
1357
+ else:
1358
+ variant_ref = PBXFileReference(
1359
+ {"name": variant_name, "path": variant_path}
1360
+ )
1361
+ variant_group_ref.AppendChild(variant_ref)
1362
+ # The caller is interested in the variant group, not the specific
1363
+ # variant file.
1364
+ file_ref = variant_group_ref
1365
+ return file_ref
1366
+ else:
1367
+ # Hierarchical recursion. Add or get a PBXGroup corresponding to the
1368
+ # outermost path component, and then recurse into it, chopping off that
1369
+ # path component.
1370
+ next_dir = path_split[0]
1371
+ group_ref = self.GetChildByPath(next_dir)
1372
+ if group_ref is not None:
1373
+ assert group_ref.__class__ == PBXGroup
1374
+ else:
1375
+ group_ref = PBXGroup({"path": next_dir})
1376
+ self.AppendChild(group_ref)
1377
+ return group_ref.AddOrGetFileByPath(
1378
+ posixpath.sep.join(path_split[1:]), hierarchical
1379
+ )
1380
+
1381
+ def AddOrGetVariantGroupByNameAndPath(self, name, path):
1382
+ """Returns an existing or new PBXVariantGroup for name and path.
1383
+
1384
+ If a PBXVariantGroup identified by the name and path arguments is already
1385
+ present as a child of this object, it is returned. Otherwise, a new
1386
+ PBXVariantGroup with the correct properties is created, added as a child,
1387
+ and returned.
1388
+
1389
+ This method will generally be called by AddOrGetFileByPath, which knows
1390
+ when to create a variant group based on the structure of the pathnames
1391
+ passed to it.
1392
+ """
1393
+
1394
+ key = (name, path)
1395
+ if key in self._variant_children_by_name_and_path:
1396
+ variant_group_ref = self._variant_children_by_name_and_path[key]
1397
+ assert variant_group_ref.__class__ == PBXVariantGroup
1398
+ return variant_group_ref
1399
+
1400
+ variant_group_properties = {"name": name}
1401
+ if path is not None:
1402
+ variant_group_properties["path"] = path
1403
+ variant_group_ref = PBXVariantGroup(variant_group_properties)
1404
+ self.AppendChild(variant_group_ref)
1405
+
1406
+ return variant_group_ref
1407
+
1408
+ def TakeOverOnlyChild(self, recurse=False):
1409
+ """If this PBXGroup has only one child and it's also a PBXGroup, take
1410
+ it over by making all of its children this object's children.
1411
+
1412
+ This function will continue to take over only children when those children
1413
+ are groups. If there are three PBXGroups representing a, b, and c, with
1414
+ c inside b and b inside a, and a and b have no other children, this will
1415
+ result in a taking over both b and c, forming a PBXGroup for a/b/c.
1416
+
1417
+ If recurse is True, this function will recurse into children and ask them
1418
+ to collapse themselves by taking over only children as well. Assuming
1419
+ an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
1420
+ (d1, d2, and f are files, the rest are groups), recursion will result in
1421
+ a group for a/b/c containing a group for d3/e.
1422
+ """
1423
+
1424
+ # At this stage, check that child class types are PBXGroup exactly,
1425
+ # instead of using isinstance. The only subclass of PBXGroup,
1426
+ # PBXVariantGroup, should not participate in reparenting in the same way:
1427
+ # reparenting by merging different object types would be wrong.
1428
+ while (
1429
+ len(self._properties["children"]) == 1
1430
+ and self._properties["children"][0].__class__ == PBXGroup
1431
+ ):
1432
+ # Loop to take over the innermost only-child group possible.
1433
+
1434
+ child = self._properties["children"][0]
1435
+
1436
+ # Assume the child's properties, including its children. Save a copy
1437
+ # of this object's old properties, because they'll still be needed.
1438
+ # This object retains its existing id and parent attributes.
1439
+ old_properties = self._properties
1440
+ self._properties = child._properties
1441
+ self._children_by_path = child._children_by_path
1442
+
1443
+ if (
1444
+ "sourceTree" not in self._properties
1445
+ or self._properties["sourceTree"] == "<group>"
1446
+ ):
1447
+ # The child was relative to its parent. Fix up the path. Note that
1448
+ # children with a sourceTree other than "<group>" are not relative to
1449
+ # their parents, so no path fix-up is needed in that case.
1450
+ if "path" in old_properties:
1451
+ if "path" in self._properties:
1452
+ # Both the original parent and child have paths set.
1453
+ self._properties["path"] = posixpath.join(
1454
+ old_properties["path"], self._properties["path"]
1455
+ )
1456
+ else:
1457
+ # Only the original parent has a path, use it.
1458
+ self._properties["path"] = old_properties["path"]
1459
+ if "sourceTree" in old_properties:
1460
+ # The original parent had a sourceTree set, use it.
1461
+ self._properties["sourceTree"] = old_properties["sourceTree"]
1462
+
1463
+ # If the original parent had a name set, keep using it. If the original
1464
+ # parent didn't have a name but the child did, let the child's name
1465
+ # live on. If the name attribute seems unnecessary now, get rid of it.
1466
+ if "name" in old_properties and old_properties["name"] not in (
1467
+ None,
1468
+ self.Name(),
1469
+ ):
1470
+ self._properties["name"] = old_properties["name"]
1471
+ if (
1472
+ "name" in self._properties
1473
+ and "path" in self._properties
1474
+ and self._properties["name"] == self._properties["path"]
1475
+ ):
1476
+ del self._properties["name"]
1477
+
1478
+ # Notify all children of their new parent.
1479
+ for child in self._properties["children"]:
1480
+ child.parent = self
1481
+
1482
+ # If asked to recurse, recurse.
1483
+ if recurse:
1484
+ for child in self._properties["children"]:
1485
+ if child.__class__ == PBXGroup:
1486
+ child.TakeOverOnlyChild(recurse)
1487
+
1488
+ def SortGroup(self):
1489
+ self._properties["children"] = sorted(
1490
+ self._properties["children"], key=cmp_to_key(lambda x, y: x.Compare(y))
1491
+ )
1492
+
1493
+ # Recurse.
1494
+ for child in self._properties["children"]:
1495
+ if isinstance(child, PBXGroup):
1496
+ child.SortGroup()
1497
+
1498
+
1499
+ class XCFileLikeElement(XCHierarchicalElement):
1500
+ # Abstract base for objects that can be used as the fileRef property of
1501
+ # PBXBuildFile.
1502
+
1503
+ def PathHashables(self):
1504
+ # A PBXBuildFile that refers to this object will call this method to
1505
+ # obtain additional hashables specific to this XCFileLikeElement. Don't
1506
+ # just use this object's hashables, they're not specific and unique enough
1507
+ # on their own (without access to the parent hashables.) Instead, provide
1508
+ # hashables that identify this object by path by getting its hashables as
1509
+ # well as the hashables of ancestor XCHierarchicalElement objects.
1510
+
1511
+ hashables = []
1512
+ xche = self
1513
+ while isinstance(xche, XCHierarchicalElement):
1514
+ xche_hashables = xche.Hashables()
1515
+ for index, xche_hashable in enumerate(xche_hashables):
1516
+ hashables.insert(index, xche_hashable)
1517
+ xche = xche.parent
1518
+ return hashables
1519
+
1520
+
1521
+ class XCContainerPortal(XCObject):
1522
+ # Abstract base for objects that can be used as the containerPortal property
1523
+ # of PBXContainerItemProxy.
1524
+ pass
1525
+
1526
+
1527
+ class XCRemoteObject(XCObject):
1528
+ # Abstract base for objects that can be used as the remoteGlobalIDString
1529
+ # property of PBXContainerItemProxy.
1530
+ pass
1531
+
1532
+
1533
+ class PBXFileReference(XCFileLikeElement, XCContainerPortal, XCRemoteObject):
1534
+ _schema = XCFileLikeElement._schema.copy()
1535
+ _schema.update(
1536
+ {
1537
+ "explicitFileType": [0, str, 0, 0],
1538
+ "lastKnownFileType": [0, str, 0, 0],
1539
+ "name": [0, str, 0, 0],
1540
+ "path": [0, str, 0, 1],
1541
+ }
1542
+ )
1543
+
1544
+ # Weird output rules for PBXFileReference.
1545
+ _should_print_single_line = True
1546
+ # super
1547
+ _encode_transforms = XCFileLikeElement._alternate_encode_transforms
1548
+
1549
+ def __init__(self, properties=None, id=None, parent=None):
1550
+ # super
1551
+ XCFileLikeElement.__init__(self, properties, id, parent)
1552
+ if "path" in self._properties and self._properties["path"].endswith("/"):
1553
+ self._properties["path"] = self._properties["path"][:-1]
1554
+ is_dir = True
1555
+ else:
1556
+ is_dir = False
1557
+
1558
+ if (
1559
+ "path" in self._properties
1560
+ and "lastKnownFileType" not in self._properties
1561
+ and "explicitFileType" not in self._properties
1562
+ ):
1563
+ # TODO(mark): This is the replacement for a replacement for a quick hack.
1564
+ # It is no longer incredibly sucky, but this list needs to be extended.
1565
+ extension_map = {
1566
+ "a": "archive.ar",
1567
+ "app": "wrapper.application",
1568
+ "bdic": "file",
1569
+ "bundle": "wrapper.cfbundle",
1570
+ "c": "sourcecode.c.c",
1571
+ "cc": "sourcecode.cpp.cpp",
1572
+ "cpp": "sourcecode.cpp.cpp",
1573
+ "css": "text.css",
1574
+ "cxx": "sourcecode.cpp.cpp",
1575
+ "dart": "sourcecode",
1576
+ "dylib": "compiled.mach-o.dylib",
1577
+ "framework": "wrapper.framework",
1578
+ "gyp": "sourcecode",
1579
+ "gypi": "sourcecode",
1580
+ "h": "sourcecode.c.h",
1581
+ "hxx": "sourcecode.cpp.h",
1582
+ "icns": "image.icns",
1583
+ "java": "sourcecode.java",
1584
+ "js": "sourcecode.javascript",
1585
+ "kext": "wrapper.kext",
1586
+ "m": "sourcecode.c.objc",
1587
+ "mm": "sourcecode.cpp.objcpp",
1588
+ "nib": "wrapper.nib",
1589
+ "o": "compiled.mach-o.objfile",
1590
+ "pdf": "image.pdf",
1591
+ "pl": "text.script.perl",
1592
+ "plist": "text.plist.xml",
1593
+ "pm": "text.script.perl",
1594
+ "png": "image.png",
1595
+ "py": "text.script.python",
1596
+ "r": "sourcecode.rez",
1597
+ "rez": "sourcecode.rez",
1598
+ "s": "sourcecode.asm",
1599
+ "storyboard": "file.storyboard",
1600
+ "strings": "text.plist.strings",
1601
+ "swift": "sourcecode.swift",
1602
+ "ttf": "file",
1603
+ "xcassets": "folder.assetcatalog",
1604
+ "xcconfig": "text.xcconfig",
1605
+ "xcdatamodel": "wrapper.xcdatamodel",
1606
+ "xcdatamodeld": "wrapper.xcdatamodeld",
1607
+ "xib": "file.xib",
1608
+ "y": "sourcecode.yacc",
1609
+ }
1610
+
1611
+ prop_map = {
1612
+ "dart": "explicitFileType",
1613
+ "gyp": "explicitFileType",
1614
+ "gypi": "explicitFileType",
1615
+ }
1616
+
1617
+ if is_dir:
1618
+ file_type = "folder"
1619
+ prop_name = "lastKnownFileType"
1620
+ else:
1621
+ basename = posixpath.basename(self._properties["path"])
1622
+ (root, ext) = posixpath.splitext(basename)
1623
+ # Check the map using a lowercase extension.
1624
+ # TODO(mark): Maybe it should try with the original case first and fall
1625
+ # back to lowercase, in case there are any instances where case
1626
+ # matters. There currently aren't.
1627
+ if ext != "":
1628
+ ext = ext[1:].lower()
1629
+
1630
+ # TODO(mark): "text" is the default value, but "file" is appropriate
1631
+ # for unrecognized files not containing text. Xcode seems to choose
1632
+ # based on content.
1633
+ file_type = extension_map.get(ext, "text")
1634
+ prop_name = prop_map.get(ext, "lastKnownFileType")
1635
+
1636
+ self._properties[prop_name] = file_type
1637
+
1638
+
1639
+ class PBXVariantGroup(PBXGroup, XCFileLikeElement):
1640
+ """PBXVariantGroup is used by Xcode to represent localizations."""
1641
+
1642
+ # No additions to the schema relative to PBXGroup.
1643
+ pass
1644
+
1645
+
1646
+ # PBXReferenceProxy is also an XCFileLikeElement subclass. It is defined below
1647
+ # because it uses PBXContainerItemProxy, defined below.
1648
+
1649
+
1650
+ class XCBuildConfiguration(XCObject):
1651
+ _schema = XCObject._schema.copy()
1652
+ _schema.update(
1653
+ {
1654
+ "baseConfigurationReference": [0, PBXFileReference, 0, 0],
1655
+ "buildSettings": [0, dict, 0, 1, {}],
1656
+ "name": [0, str, 0, 1],
1657
+ }
1658
+ )
1659
+
1660
+ def HasBuildSetting(self, key):
1661
+ return key in self._properties["buildSettings"]
1662
+
1663
+ def GetBuildSetting(self, key):
1664
+ return self._properties["buildSettings"][key]
1665
+
1666
+ def SetBuildSetting(self, key, value):
1667
+ # TODO(mark): If a list, copy?
1668
+ self._properties["buildSettings"][key] = value
1669
+
1670
+ def AppendBuildSetting(self, key, value):
1671
+ if key not in self._properties["buildSettings"]:
1672
+ self._properties["buildSettings"][key] = []
1673
+ self._properties["buildSettings"][key].append(value)
1674
+
1675
+ def DelBuildSetting(self, key):
1676
+ if key in self._properties["buildSettings"]:
1677
+ del self._properties["buildSettings"][key]
1678
+
1679
+ def SetBaseConfiguration(self, value):
1680
+ self._properties["baseConfigurationReference"] = value
1681
+
1682
+
1683
+ class XCConfigurationList(XCObject):
1684
+ # _configs is the default list of configurations.
1685
+ _configs = [
1686
+ XCBuildConfiguration({"name": "Debug"}),
1687
+ XCBuildConfiguration({"name": "Release"}),
1688
+ ]
1689
+
1690
+ _schema = XCObject._schema.copy()
1691
+ _schema.update(
1692
+ {
1693
+ "buildConfigurations": [1, XCBuildConfiguration, 1, 1, _configs],
1694
+ "defaultConfigurationIsVisible": [0, int, 0, 1, 1],
1695
+ "defaultConfigurationName": [0, str, 0, 1, "Release"],
1696
+ }
1697
+ )
1698
+
1699
+ def Name(self):
1700
+ return (
1701
+ "Build configuration list for "
1702
+ + self.parent.__class__.__name__
1703
+ + ' "'
1704
+ + self.parent.Name()
1705
+ + '"'
1706
+ )
1707
+
1708
+ def ConfigurationNamed(self, name):
1709
+ """Convenience accessor to obtain an XCBuildConfiguration by name."""
1710
+ for configuration in self._properties["buildConfigurations"]:
1711
+ if configuration._properties["name"] == name:
1712
+ return configuration
1713
+
1714
+ raise KeyError(name)
1715
+
1716
+ def DefaultConfiguration(self):
1717
+ """Convenience accessor to obtain the default XCBuildConfiguration."""
1718
+ return self.ConfigurationNamed(self._properties["defaultConfigurationName"])
1719
+
1720
+ def HasBuildSetting(self, key):
1721
+ """Determines the state of a build setting in all XCBuildConfiguration
1722
+ child objects.
1723
+
1724
+ If all child objects have key in their build settings, and the value is the
1725
+ same in all child objects, returns 1.
1726
+
1727
+ If no child objects have the key in their build settings, returns 0.
1728
+
1729
+ If some, but not all, child objects have the key in their build settings,
1730
+ or if any children have different values for the key, returns -1.
1731
+ """
1732
+
1733
+ has = None
1734
+ value = None
1735
+ for configuration in self._properties["buildConfigurations"]:
1736
+ configuration_has = configuration.HasBuildSetting(key)
1737
+ if has is None:
1738
+ has = configuration_has
1739
+ elif has != configuration_has:
1740
+ return -1
1741
+
1742
+ if configuration_has:
1743
+ configuration_value = configuration.GetBuildSetting(key)
1744
+ if value is None:
1745
+ value = configuration_value
1746
+ elif value != configuration_value:
1747
+ return -1
1748
+
1749
+ if not has:
1750
+ return 0
1751
+
1752
+ return 1
1753
+
1754
+ def GetBuildSetting(self, key):
1755
+ """Gets the build setting for key.
1756
+
1757
+ All child XCConfiguration objects must have the same value set for the
1758
+ setting, or a ValueError will be raised.
1759
+ """
1760
+
1761
+ # TODO(mark): This is wrong for build settings that are lists. The list
1762
+ # contents should be compared (and a list copy returned?)
1763
+
1764
+ value = None
1765
+ for configuration in self._properties["buildConfigurations"]:
1766
+ configuration_value = configuration.GetBuildSetting(key)
1767
+ if value is None:
1768
+ value = configuration_value
1769
+ else:
1770
+ if value != configuration_value:
1771
+ raise ValueError("Variant values for " + key)
1772
+
1773
+ return value
1774
+
1775
+ def SetBuildSetting(self, key, value):
1776
+ """Sets the build setting for key to value in all child
1777
+ XCBuildConfiguration objects.
1778
+ """
1779
+
1780
+ for configuration in self._properties["buildConfigurations"]:
1781
+ configuration.SetBuildSetting(key, value)
1782
+
1783
+ def AppendBuildSetting(self, key, value):
1784
+ """Appends value to the build setting for key, which is treated as a list,
1785
+ in all child XCBuildConfiguration objects.
1786
+ """
1787
+
1788
+ for configuration in self._properties["buildConfigurations"]:
1789
+ configuration.AppendBuildSetting(key, value)
1790
+
1791
+ def DelBuildSetting(self, key):
1792
+ """Deletes the build setting key from all child XCBuildConfiguration
1793
+ objects.
1794
+ """
1795
+
1796
+ for configuration in self._properties["buildConfigurations"]:
1797
+ configuration.DelBuildSetting(key)
1798
+
1799
+ def SetBaseConfiguration(self, value):
1800
+ """Sets the build configuration in all child XCBuildConfiguration objects.
1801
+ """
1802
+
1803
+ for configuration in self._properties["buildConfigurations"]:
1804
+ configuration.SetBaseConfiguration(value)
1805
+
1806
+
1807
+ class PBXBuildFile(XCObject):
1808
+ _schema = XCObject._schema.copy()
1809
+ _schema.update(
1810
+ {
1811
+ "fileRef": [0, XCFileLikeElement, 0, 1],
1812
+ "settings": [0, str, 0, 0], # hack, it's a dict
1813
+ }
1814
+ )
1815
+
1816
+ # Weird output rules for PBXBuildFile.
1817
+ _should_print_single_line = True
1818
+ _encode_transforms = XCObject._alternate_encode_transforms
1819
+
1820
+ def Name(self):
1821
+ # Example: "main.cc in Sources"
1822
+ return self._properties["fileRef"].Name() + " in " + self.parent.Name()
1823
+
1824
+ def Hashables(self):
1825
+ # super
1826
+ hashables = XCObject.Hashables(self)
1827
+
1828
+ # It is not sufficient to just rely on Name() to get the
1829
+ # XCFileLikeElement's name, because that is not a complete pathname.
1830
+ # PathHashables returns hashables unique enough that no two
1831
+ # PBXBuildFiles should wind up with the same set of hashables, unless
1832
+ # someone adds the same file multiple times to the same target. That
1833
+ # would be considered invalid anyway.
1834
+ hashables.extend(self._properties["fileRef"].PathHashables())
1835
+
1836
+ return hashables
1837
+
1838
+
1839
+ class XCBuildPhase(XCObject):
1840
+ """Abstract base for build phase classes. Not represented in a project
1841
+ file.
1842
+
1843
+ Attributes:
1844
+ _files_by_path: A dict mapping each path of a child in the files list by
1845
+ path (keys) to the corresponding PBXBuildFile children (values).
1846
+ _files_by_xcfilelikeelement: A dict mapping each XCFileLikeElement (keys)
1847
+ to the corresponding PBXBuildFile children (values).
1848
+ """
1849
+
1850
+ # TODO(mark): Some build phase types, like PBXShellScriptBuildPhase, don't
1851
+ # actually have a "files" list. XCBuildPhase should not have "files" but
1852
+ # another abstract subclass of it should provide this, and concrete build
1853
+ # phase types that do have "files" lists should be derived from that new
1854
+ # abstract subclass. XCBuildPhase should only provide buildActionMask and
1855
+ # runOnlyForDeploymentPostprocessing, and not files or the various
1856
+ # file-related methods and attributes.
1857
+
1858
+ _schema = XCObject._schema.copy()
1859
+ _schema.update(
1860
+ {
1861
+ "buildActionMask": [0, int, 0, 1, 0x7FFFFFFF],
1862
+ "files": [1, PBXBuildFile, 1, 1, []],
1863
+ "runOnlyForDeploymentPostprocessing": [0, int, 0, 1, 0],
1864
+ }
1865
+ )
1866
+
1867
+ def __init__(self, properties=None, id=None, parent=None):
1868
+ # super
1869
+ XCObject.__init__(self, properties, id, parent)
1870
+
1871
+ self._files_by_path = {}
1872
+ self._files_by_xcfilelikeelement = {}
1873
+ for pbxbuildfile in self._properties.get("files", []):
1874
+ self._AddBuildFileToDicts(pbxbuildfile)
1875
+
1876
+ def FileGroup(self, path):
1877
+ # Subclasses must override this by returning a two-element tuple. The
1878
+ # first item in the tuple should be the PBXGroup to which "path" should be
1879
+ # added, either as a child or deeper descendant. The second item should
1880
+ # be a boolean indicating whether files should be added into hierarchical
1881
+ # groups or one single flat group.
1882
+ raise NotImplementedError(self.__class__.__name__ + " must implement FileGroup")
1883
+
1884
+ def _AddPathToDict(self, pbxbuildfile, path):
1885
+ """Adds path to the dict tracking paths belonging to this build phase.
1886
+
1887
+ If the path is already a member of this build phase, raises an exception.
1888
+ """
1889
+
1890
+ if path in self._files_by_path:
1891
+ raise ValueError("Found multiple build files with path " + path)
1892
+ self._files_by_path[path] = pbxbuildfile
1893
+
1894
+ def _AddBuildFileToDicts(self, pbxbuildfile, path=None):
1895
+ """Maintains the _files_by_path and _files_by_xcfilelikeelement dicts.
1896
+
1897
+ If path is specified, then it is the path that is being added to the
1898
+ phase, and pbxbuildfile must contain either a PBXFileReference directly
1899
+ referencing that path, or it must contain a PBXVariantGroup that itself
1900
+ contains a PBXFileReference referencing the path.
1901
+
1902
+ If path is not specified, either the PBXFileReference's path or the paths
1903
+ of all children of the PBXVariantGroup are taken as being added to the
1904
+ phase.
1905
+
1906
+ If the path is already present in the phase, raises an exception.
1907
+
1908
+ If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile
1909
+ are already present in the phase, referenced by a different PBXBuildFile
1910
+ object, raises an exception. This does not raise an exception when
1911
+ a PBXFileReference or PBXVariantGroup reappear and are referenced by the
1912
+ same PBXBuildFile that has already introduced them, because in the case
1913
+ of PBXVariantGroup objects, they may correspond to multiple paths that are
1914
+ not all added simultaneously. When this situation occurs, the path needs
1915
+ to be added to _files_by_path, but nothing needs to change in
1916
+ _files_by_xcfilelikeelement, and the caller should have avoided adding
1917
+ the PBXBuildFile if it is already present in the list of children.
1918
+ """
1919
+
1920
+ xcfilelikeelement = pbxbuildfile._properties["fileRef"]
1921
+
1922
+ paths = []
1923
+ if path is not None:
1924
+ # It's best when the caller provides the path.
1925
+ if isinstance(xcfilelikeelement, PBXVariantGroup):
1926
+ paths.append(path)
1927
+ else:
1928
+ # If the caller didn't provide a path, there can be either multiple
1929
+ # paths (PBXVariantGroup) or one.
1930
+ if isinstance(xcfilelikeelement, PBXVariantGroup):
1931
+ for variant in xcfilelikeelement._properties["children"]:
1932
+ paths.append(variant.FullPath())
1933
+ else:
1934
+ paths.append(xcfilelikeelement.FullPath())
1935
+
1936
+ # Add the paths first, because if something's going to raise, the
1937
+ # messages provided by _AddPathToDict are more useful owing to its
1938
+ # having access to a real pathname and not just an object's Name().
1939
+ for a_path in paths:
1940
+ self._AddPathToDict(pbxbuildfile, a_path)
1941
+
1942
+ # If another PBXBuildFile references this XCFileLikeElement, there's a
1943
+ # problem.
1944
+ if (
1945
+ xcfilelikeelement in self._files_by_xcfilelikeelement
1946
+ and self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile
1947
+ ):
1948
+ raise ValueError(
1949
+ "Found multiple build files for " + xcfilelikeelement.Name()
1950
+ )
1951
+ self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile
1952
+
1953
+ def AppendBuildFile(self, pbxbuildfile, path=None):
1954
+ # Callers should use this instead of calling
1955
+ # AppendProperty('files', pbxbuildfile) directly because this function
1956
+ # maintains the object's dicts. Better yet, callers can just call AddFile
1957
+ # with a pathname and not worry about building their own PBXBuildFile
1958
+ # objects.
1959
+ self.AppendProperty("files", pbxbuildfile)
1960
+ self._AddBuildFileToDicts(pbxbuildfile, path)
1961
+
1962
+ def AddFile(self, path, settings=None):
1963
+ (file_group, hierarchical) = self.FileGroup(path)
1964
+ file_ref = file_group.AddOrGetFileByPath(path, hierarchical)
1965
+
1966
+ if file_ref in self._files_by_xcfilelikeelement and isinstance(
1967
+ file_ref, PBXVariantGroup
1968
+ ):
1969
+ # There's already a PBXBuildFile in this phase corresponding to the
1970
+ # PBXVariantGroup. path just provides a new variant that belongs to
1971
+ # the group. Add the path to the dict.
1972
+ pbxbuildfile = self._files_by_xcfilelikeelement[file_ref]
1973
+ self._AddBuildFileToDicts(pbxbuildfile, path)
1974
+ else:
1975
+ # Add a new PBXBuildFile to get file_ref into the phase.
1976
+ if settings is None:
1977
+ pbxbuildfile = PBXBuildFile({"fileRef": file_ref})
1978
+ else:
1979
+ pbxbuildfile = PBXBuildFile({"fileRef": file_ref, "settings": settings})
1980
+ self.AppendBuildFile(pbxbuildfile, path)
1981
+
1982
+
1983
+ class PBXHeadersBuildPhase(XCBuildPhase):
1984
+ # No additions to the schema relative to XCBuildPhase.
1985
+
1986
+ def Name(self):
1987
+ return "Headers"
1988
+
1989
+ def FileGroup(self, path):
1990
+ return self.PBXProjectAncestor().RootGroupForPath(path)
1991
+
1992
+
1993
+ class PBXResourcesBuildPhase(XCBuildPhase):
1994
+ # No additions to the schema relative to XCBuildPhase.
1995
+
1996
+ def Name(self):
1997
+ return "Resources"
1998
+
1999
+ def FileGroup(self, path):
2000
+ return self.PBXProjectAncestor().RootGroupForPath(path)
2001
+
2002
+
2003
+ class PBXSourcesBuildPhase(XCBuildPhase):
2004
+ # No additions to the schema relative to XCBuildPhase.
2005
+
2006
+ def Name(self):
2007
+ return "Sources"
2008
+
2009
+ def FileGroup(self, path):
2010
+ return self.PBXProjectAncestor().RootGroupForPath(path)
2011
+
2012
+
2013
+ class PBXFrameworksBuildPhase(XCBuildPhase):
2014
+ # No additions to the schema relative to XCBuildPhase.
2015
+
2016
+ def Name(self):
2017
+ return "Frameworks"
2018
+
2019
+ def FileGroup(self, path):
2020
+ (root, ext) = posixpath.splitext(path)
2021
+ if ext != "":
2022
+ ext = ext[1:].lower()
2023
+ if ext == "o":
2024
+ # .o files are added to Xcode Frameworks phases, but conceptually aren't
2025
+ # frameworks, they're more like sources or intermediates. Redirect them
2026
+ # to show up in one of those other groups.
2027
+ return self.PBXProjectAncestor().RootGroupForPath(path)
2028
+ else:
2029
+ return (self.PBXProjectAncestor().FrameworksGroup(), False)
2030
+
2031
+
2032
+ class PBXShellScriptBuildPhase(XCBuildPhase):
2033
+ _schema = XCBuildPhase._schema.copy()
2034
+ _schema.update(
2035
+ {
2036
+ "inputPaths": [1, str, 0, 1, []],
2037
+ "name": [0, str, 0, 0],
2038
+ "outputPaths": [1, str, 0, 1, []],
2039
+ "shellPath": [0, str, 0, 1, "/bin/sh"],
2040
+ "shellScript": [0, str, 0, 1],
2041
+ "showEnvVarsInLog": [0, int, 0, 0],
2042
+ }
2043
+ )
2044
+
2045
+ def Name(self):
2046
+ if "name" in self._properties:
2047
+ return self._properties["name"]
2048
+
2049
+ return "ShellScript"
2050
+
2051
+
2052
+ class PBXCopyFilesBuildPhase(XCBuildPhase):
2053
+ _schema = XCBuildPhase._schema.copy()
2054
+ _schema.update(
2055
+ {
2056
+ "dstPath": [0, str, 0, 1],
2057
+ "dstSubfolderSpec": [0, int, 0, 1],
2058
+ "name": [0, str, 0, 0],
2059
+ }
2060
+ )
2061
+
2062
+ # path_tree_re matches "$(DIR)/path", "$(DIR)/$(DIR2)/path" or just "$(DIR)".
2063
+ # Match group 1 is "DIR", group 3 is "path" or "$(DIR2") or "$(DIR2)/path"
2064
+ # or None. If group 3 is "path", group 4 will be None otherwise group 4 is
2065
+ # "DIR2" and group 6 is "path".
2066
+ path_tree_re = re.compile(r"^\$\((.*?)\)(/(\$\((.*?)\)(/(.*)|)|(.*)|)|)$")
2067
+
2068
+ # path_tree_{first,second}_to_subfolder map names of Xcode variables to the
2069
+ # associated dstSubfolderSpec property value used in a PBXCopyFilesBuildPhase
2070
+ # object.
2071
+ path_tree_first_to_subfolder = {
2072
+ # Types that can be chosen via the Xcode UI.
2073
+ "BUILT_PRODUCTS_DIR": 16, # Products Directory
2074
+ "BUILT_FRAMEWORKS_DIR": 10, # Not an official Xcode macro.
2075
+ # Existed before support for the
2076
+ # names below was added. Maps to
2077
+ # "Frameworks".
2078
+ }
2079
+
2080
+ path_tree_second_to_subfolder = {
2081
+ "WRAPPER_NAME": 1, # Wrapper
2082
+ # Although Xcode's friendly name is "Executables", the destination
2083
+ # is demonstrably the value of the build setting
2084
+ # EXECUTABLE_FOLDER_PATH not EXECUTABLES_FOLDER_PATH.
2085
+ "EXECUTABLE_FOLDER_PATH": 6, # Executables.
2086
+ "UNLOCALIZED_RESOURCES_FOLDER_PATH": 7, # Resources
2087
+ "JAVA_FOLDER_PATH": 15, # Java Resources
2088
+ "FRAMEWORKS_FOLDER_PATH": 10, # Frameworks
2089
+ "SHARED_FRAMEWORKS_FOLDER_PATH": 11, # Shared Frameworks
2090
+ "SHARED_SUPPORT_FOLDER_PATH": 12, # Shared Support
2091
+ "PLUGINS_FOLDER_PATH": 13, # PlugIns
2092
+ # For XPC Services, Xcode sets both dstPath and dstSubfolderSpec.
2093
+ # Note that it re-uses the BUILT_PRODUCTS_DIR value for
2094
+ # dstSubfolderSpec. dstPath is set below.
2095
+ "XPCSERVICES_FOLDER_PATH": 16, # XPC Services.
2096
+ }
2097
+
2098
+ def Name(self):
2099
+ if "name" in self._properties:
2100
+ return self._properties["name"]
2101
+
2102
+ return "CopyFiles"
2103
+
2104
+ def FileGroup(self, path):
2105
+ return self.PBXProjectAncestor().RootGroupForPath(path)
2106
+
2107
+ def SetDestination(self, path):
2108
+ """Set the dstSubfolderSpec and dstPath properties from path.
2109
+
2110
+ path may be specified in the same notation used for XCHierarchicalElements,
2111
+ specifically, "$(DIR)/path".
2112
+ """
2113
+
2114
+ path_tree_match = self.path_tree_re.search(path)
2115
+ if path_tree_match:
2116
+ path_tree = path_tree_match.group(1)
2117
+ if path_tree in self.path_tree_first_to_subfolder:
2118
+ subfolder = self.path_tree_first_to_subfolder[path_tree]
2119
+ relative_path = path_tree_match.group(3)
2120
+ if relative_path is None:
2121
+ relative_path = ""
2122
+
2123
+ if subfolder == 16 and path_tree_match.group(4) is not None:
2124
+ # BUILT_PRODUCTS_DIR (16) is the first element in a path whose
2125
+ # second element is possibly one of the variable names in
2126
+ # path_tree_second_to_subfolder. Xcode sets the values of all these
2127
+ # variables to relative paths so .gyp files must prefix them with
2128
+ # BUILT_PRODUCTS_DIR, e.g.
2129
+ # $(BUILT_PRODUCTS_DIR)/$(PLUGINS_FOLDER_PATH). Then
2130
+ # xcode_emulation.py can export these variables with the same values
2131
+ # as Xcode yet make & ninja files can determine the absolute path
2132
+ # to the target. Xcode uses the dstSubfolderSpec value set here
2133
+ # to determine the full path.
2134
+ #
2135
+ # An alternative of xcode_emulation.py setting the values to
2136
+ # absolute paths when exporting these variables has been
2137
+ # ruled out because then the values would be different
2138
+ # depending on the build tool.
2139
+ #
2140
+ # Another alternative is to invent new names for the variables used
2141
+ # to match to the subfolder indices in the second table. .gyp files
2142
+ # then will not need to prepend $(BUILT_PRODUCTS_DIR) because
2143
+ # xcode_emulation.py can set the values of those variables to
2144
+ # the absolute paths when exporting. This is possibly the thinking
2145
+ # behind BUILT_FRAMEWORKS_DIR which is used in exactly this manner.
2146
+ #
2147
+ # Requiring prepending BUILT_PRODUCTS_DIR has been chosen because
2148
+ # this same way could be used to specify destinations in .gyp files
2149
+ # that pre-date this addition to GYP. However they would only work
2150
+ # with the Xcode generator.
2151
+ # The previous version of xcode_emulation.py
2152
+ # does not export these variables. Such files will get the benefit
2153
+ # of the Xcode UI showing the proper destination name simply by
2154
+ # regenerating the projects with this version of GYP.
2155
+ path_tree = path_tree_match.group(4)
2156
+ relative_path = path_tree_match.group(6)
2157
+ separator = "/"
2158
+
2159
+ if path_tree in self.path_tree_second_to_subfolder:
2160
+ subfolder = self.path_tree_second_to_subfolder[path_tree]
2161
+ if relative_path is None:
2162
+ relative_path = ""
2163
+ separator = ""
2164
+ if path_tree == "XPCSERVICES_FOLDER_PATH":
2165
+ relative_path = (
2166
+ "$(CONTENTS_FOLDER_PATH)/XPCServices"
2167
+ + separator
2168
+ + relative_path
2169
+ )
2170
+ else:
2171
+ # subfolder = 16 from above
2172
+ # The second element of the path is an unrecognized variable.
2173
+ # Include it and any remaining elements in relative_path.
2174
+ relative_path = path_tree_match.group(3)
2175
+
2176
+ else:
2177
+ # The path starts with an unrecognized Xcode variable
2178
+ # name like $(SRCROOT). Xcode will still handle this
2179
+ # as an "absolute path" that starts with the variable.
2180
+ subfolder = 0
2181
+ relative_path = path
2182
+ elif path.startswith("/"):
2183
+ # Special case. Absolute paths are in dstSubfolderSpec 0.
2184
+ subfolder = 0
2185
+ relative_path = path[1:]
2186
+ else:
2187
+ raise ValueError(
2188
+ f"Can't use path {path} in a {self.__class__.__name__}"
2189
+ )
2190
+
2191
+ self._properties["dstPath"] = relative_path
2192
+ self._properties["dstSubfolderSpec"] = subfolder
2193
+
2194
+
2195
+ class PBXBuildRule(XCObject):
2196
+ _schema = XCObject._schema.copy()
2197
+ _schema.update(
2198
+ {
2199
+ "compilerSpec": [0, str, 0, 1],
2200
+ "filePatterns": [0, str, 0, 0],
2201
+ "fileType": [0, str, 0, 1],
2202
+ "isEditable": [0, int, 0, 1, 1],
2203
+ "outputFiles": [1, str, 0, 1, []],
2204
+ "script": [0, str, 0, 0],
2205
+ }
2206
+ )
2207
+
2208
+ def Name(self):
2209
+ # Not very inspired, but it's what Xcode uses.
2210
+ return self.__class__.__name__
2211
+
2212
+ def Hashables(self):
2213
+ # super
2214
+ hashables = XCObject.Hashables(self)
2215
+
2216
+ # Use the hashables of the weak objects that this object refers to.
2217
+ hashables.append(self._properties["fileType"])
2218
+ if "filePatterns" in self._properties:
2219
+ hashables.append(self._properties["filePatterns"])
2220
+ return hashables
2221
+
2222
+
2223
+ class PBXContainerItemProxy(XCObject):
2224
+ # When referencing an item in this project file, containerPortal is the
2225
+ # PBXProject root object of this project file. When referencing an item in
2226
+ # another project file, containerPortal is a PBXFileReference identifying
2227
+ # the other project file.
2228
+ #
2229
+ # When serving as a proxy to an XCTarget (in this project file or another),
2230
+ # proxyType is 1. When serving as a proxy to a PBXFileReference (in another
2231
+ # project file), proxyType is 2. Type 2 is used for references to the
2232
+ # producs of the other project file's targets.
2233
+ #
2234
+ # Xcode is weird about remoteGlobalIDString. Usually, it's printed without
2235
+ # a comment, indicating that it's tracked internally simply as a string, but
2236
+ # sometimes it's printed with a comment (usually when the object is initially
2237
+ # created), indicating that it's tracked as a project file object at least
2238
+ # sometimes. This module always tracks it as an object, but contains a hack
2239
+ # to prevent it from printing the comment in the project file output. See
2240
+ # _XCKVPrint.
2241
+ _schema = XCObject._schema.copy()
2242
+ _schema.update(
2243
+ {
2244
+ "containerPortal": [0, XCContainerPortal, 0, 1],
2245
+ "proxyType": [0, int, 0, 1],
2246
+ "remoteGlobalIDString": [0, XCRemoteObject, 0, 1],
2247
+ "remoteInfo": [0, str, 0, 1],
2248
+ }
2249
+ )
2250
+
2251
+ def __repr__(self):
2252
+ props = self._properties
2253
+ name = "{}.gyp:{}".format(props["containerPortal"].Name(), props["remoteInfo"])
2254
+ return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>"
2255
+
2256
+ def Name(self):
2257
+ # Admittedly not the best name, but it's what Xcode uses.
2258
+ return self.__class__.__name__
2259
+
2260
+ def Hashables(self):
2261
+ # super
2262
+ hashables = XCObject.Hashables(self)
2263
+
2264
+ # Use the hashables of the weak objects that this object refers to.
2265
+ hashables.extend(self._properties["containerPortal"].Hashables())
2266
+ hashables.extend(self._properties["remoteGlobalIDString"].Hashables())
2267
+ return hashables
2268
+
2269
+
2270
+ class PBXTargetDependency(XCObject):
2271
+ # The "target" property accepts an XCTarget object, and obviously not
2272
+ # NoneType. But XCTarget is defined below, so it can't be put into the
2273
+ # schema yet. The definition of PBXTargetDependency can't be moved below
2274
+ # XCTarget because XCTarget's own schema references PBXTargetDependency.
2275
+ # Python doesn't deal well with this circular relationship, and doesn't have
2276
+ # a real way to do forward declarations. To work around, the type of
2277
+ # the "target" property is reset below, after XCTarget is defined.
2278
+ #
2279
+ # At least one of "name" and "target" is required.
2280
+ _schema = XCObject._schema.copy()
2281
+ _schema.update(
2282
+ {
2283
+ "name": [0, str, 0, 0],
2284
+ "target": [0, None.__class__, 0, 0],
2285
+ "targetProxy": [0, PBXContainerItemProxy, 1, 1],
2286
+ }
2287
+ )
2288
+
2289
+ def __repr__(self):
2290
+ name = self._properties.get("name") or self._properties["target"].Name()
2291
+ return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>"
2292
+
2293
+ def Name(self):
2294
+ # Admittedly not the best name, but it's what Xcode uses.
2295
+ return self.__class__.__name__
2296
+
2297
+ def Hashables(self):
2298
+ # super
2299
+ hashables = XCObject.Hashables(self)
2300
+
2301
+ # Use the hashables of the weak objects that this object refers to.
2302
+ hashables.extend(self._properties["targetProxy"].Hashables())
2303
+ return hashables
2304
+
2305
+
2306
+ class PBXReferenceProxy(XCFileLikeElement):
2307
+ _schema = XCFileLikeElement._schema.copy()
2308
+ _schema.update(
2309
+ {
2310
+ "fileType": [0, str, 0, 1],
2311
+ "path": [0, str, 0, 1],
2312
+ "remoteRef": [0, PBXContainerItemProxy, 1, 1],
2313
+ }
2314
+ )
2315
+
2316
+
2317
+ class XCTarget(XCRemoteObject):
2318
+ # An XCTarget is really just an XCObject, the XCRemoteObject thing is just
2319
+ # to allow PBXProject to be used in the remoteGlobalIDString property of
2320
+ # PBXContainerItemProxy.
2321
+ #
2322
+ # Setting a "name" property at instantiation may also affect "productName",
2323
+ # which may in turn affect the "PRODUCT_NAME" build setting in children of
2324
+ # "buildConfigurationList". See __init__ below.
2325
+ _schema = XCRemoteObject._schema.copy()
2326
+ _schema.update(
2327
+ {
2328
+ "buildConfigurationList": [
2329
+ 0,
2330
+ XCConfigurationList,
2331
+ 1,
2332
+ 1,
2333
+ XCConfigurationList(),
2334
+ ],
2335
+ "buildPhases": [1, XCBuildPhase, 1, 1, []],
2336
+ "dependencies": [1, PBXTargetDependency, 1, 1, []],
2337
+ "name": [0, str, 0, 1],
2338
+ "productName": [0, str, 0, 1],
2339
+ }
2340
+ )
2341
+
2342
+ def __init__(
2343
+ self,
2344
+ properties=None,
2345
+ id=None,
2346
+ parent=None,
2347
+ force_outdir=None,
2348
+ force_prefix=None,
2349
+ force_extension=None,
2350
+ ):
2351
+ # super
2352
+ XCRemoteObject.__init__(self, properties, id, parent)
2353
+
2354
+ # Set up additional defaults not expressed in the schema. If a "name"
2355
+ # property was supplied, set "productName" if it is not present. Also set
2356
+ # the "PRODUCT_NAME" build setting in each configuration, but only if
2357
+ # the setting is not present in any build configuration.
2358
+ if "name" in self._properties:
2359
+ if "productName" not in self._properties:
2360
+ self.SetProperty("productName", self._properties["name"])
2361
+
2362
+ if "productName" in self._properties:
2363
+ if "buildConfigurationList" in self._properties:
2364
+ configs = self._properties["buildConfigurationList"]
2365
+ if configs.HasBuildSetting("PRODUCT_NAME") == 0:
2366
+ configs.SetBuildSetting(
2367
+ "PRODUCT_NAME", self._properties["productName"]
2368
+ )
2369
+
2370
+ def AddDependency(self, other):
2371
+ pbxproject = self.PBXProjectAncestor()
2372
+ other_pbxproject = other.PBXProjectAncestor()
2373
+ if pbxproject == other_pbxproject:
2374
+ # Add a dependency to another target in the same project file.
2375
+ container = PBXContainerItemProxy(
2376
+ {
2377
+ "containerPortal": pbxproject,
2378
+ "proxyType": 1,
2379
+ "remoteGlobalIDString": other,
2380
+ "remoteInfo": other.Name(),
2381
+ }
2382
+ )
2383
+ dependency = PBXTargetDependency(
2384
+ {"target": other, "targetProxy": container}
2385
+ )
2386
+ self.AppendProperty("dependencies", dependency)
2387
+ else:
2388
+ # Add a dependency to a target in a different project file.
2389
+ other_project_ref = pbxproject.AddOrGetProjectReference(other_pbxproject)[1]
2390
+ container = PBXContainerItemProxy(
2391
+ {
2392
+ "containerPortal": other_project_ref,
2393
+ "proxyType": 1,
2394
+ "remoteGlobalIDString": other,
2395
+ "remoteInfo": other.Name(),
2396
+ }
2397
+ )
2398
+ dependency = PBXTargetDependency(
2399
+ {"name": other.Name(), "targetProxy": container}
2400
+ )
2401
+ self.AppendProperty("dependencies", dependency)
2402
+
2403
+ # Proxy all of these through to the build configuration list.
2404
+
2405
+ def ConfigurationNamed(self, name):
2406
+ return self._properties["buildConfigurationList"].ConfigurationNamed(name)
2407
+
2408
+ def DefaultConfiguration(self):
2409
+ return self._properties["buildConfigurationList"].DefaultConfiguration()
2410
+
2411
+ def HasBuildSetting(self, key):
2412
+ return self._properties["buildConfigurationList"].HasBuildSetting(key)
2413
+
2414
+ def GetBuildSetting(self, key):
2415
+ return self._properties["buildConfigurationList"].GetBuildSetting(key)
2416
+
2417
+ def SetBuildSetting(self, key, value):
2418
+ return self._properties["buildConfigurationList"].SetBuildSetting(key, value)
2419
+
2420
+ def AppendBuildSetting(self, key, value):
2421
+ return self._properties["buildConfigurationList"].AppendBuildSetting(key, value)
2422
+
2423
+ def DelBuildSetting(self, key):
2424
+ return self._properties["buildConfigurationList"].DelBuildSetting(key)
2425
+
2426
+
2427
+ # Redefine the type of the "target" property. See PBXTargetDependency._schema
2428
+ # above.
2429
+ PBXTargetDependency._schema["target"][1] = XCTarget
2430
+
2431
+
2432
+ class PBXNativeTarget(XCTarget):
2433
+ # buildPhases is overridden in the schema to be able to set defaults.
2434
+ #
2435
+ # NOTE: Contrary to most objects, it is advisable to set parent when
2436
+ # constructing PBXNativeTarget. A parent of an XCTarget must be a PBXProject
2437
+ # object. A parent reference is required for a PBXNativeTarget during
2438
+ # construction to be able to set up the target defaults for productReference,
2439
+ # because a PBXBuildFile object must be created for the target and it must
2440
+ # be added to the PBXProject's mainGroup hierarchy.
2441
+ _schema = XCTarget._schema.copy()
2442
+ _schema.update(
2443
+ {
2444
+ "buildPhases": [
2445
+ 1,
2446
+ XCBuildPhase,
2447
+ 1,
2448
+ 1,
2449
+ [PBXSourcesBuildPhase(), PBXFrameworksBuildPhase()],
2450
+ ],
2451
+ "buildRules": [1, PBXBuildRule, 1, 1, []],
2452
+ "productReference": [0, PBXFileReference, 0, 1],
2453
+ "productType": [0, str, 0, 1],
2454
+ }
2455
+ )
2456
+
2457
+ # Mapping from Xcode product-types to settings. The settings are:
2458
+ # filetype : used for explicitFileType in the project file
2459
+ # prefix : the prefix for the file name
2460
+ # suffix : the suffix for the file name
2461
+ _product_filetypes = {
2462
+ "com.apple.product-type.application": ["wrapper.application", "", ".app"],
2463
+ "com.apple.product-type.application.watchapp": [
2464
+ "wrapper.application",
2465
+ "",
2466
+ ".app",
2467
+ ],
2468
+ "com.apple.product-type.watchkit-extension": [
2469
+ "wrapper.app-extension",
2470
+ "",
2471
+ ".appex",
2472
+ ],
2473
+ "com.apple.product-type.app-extension": ["wrapper.app-extension", "", ".appex"],
2474
+ "com.apple.product-type.bundle": ["wrapper.cfbundle", "", ".bundle"],
2475
+ "com.apple.product-type.framework": ["wrapper.framework", "", ".framework"],
2476
+ "com.apple.product-type.library.dynamic": [
2477
+ "compiled.mach-o.dylib",
2478
+ "lib",
2479
+ ".dylib",
2480
+ ],
2481
+ "com.apple.product-type.library.static": ["archive.ar", "lib", ".a"],
2482
+ "com.apple.product-type.tool": ["compiled.mach-o.executable", "", ""],
2483
+ "com.apple.product-type.bundle.unit-test": ["wrapper.cfbundle", "", ".xctest"],
2484
+ "com.apple.product-type.bundle.ui-testing": ["wrapper.cfbundle", "", ".xctest"],
2485
+ "com.googlecode.gyp.xcode.bundle": ["compiled.mach-o.dylib", "", ".so"],
2486
+ "com.apple.product-type.kernel-extension": ["wrapper.kext", "", ".kext"],
2487
+ }
2488
+
2489
+ def __init__(
2490
+ self,
2491
+ properties=None,
2492
+ id=None,
2493
+ parent=None,
2494
+ force_outdir=None,
2495
+ force_prefix=None,
2496
+ force_extension=None,
2497
+ ):
2498
+ # super
2499
+ XCTarget.__init__(self, properties, id, parent)
2500
+
2501
+ if (
2502
+ "productName" in self._properties
2503
+ and "productType" in self._properties
2504
+ and "productReference" not in self._properties
2505
+ and self._properties["productType"] in self._product_filetypes
2506
+ ):
2507
+ products_group = None
2508
+ pbxproject = self.PBXProjectAncestor()
2509
+ if pbxproject is not None:
2510
+ products_group = pbxproject.ProductsGroup()
2511
+
2512
+ if products_group is not None:
2513
+ (filetype, prefix, suffix) = self._product_filetypes[
2514
+ self._properties["productType"]
2515
+ ]
2516
+ # Xcode does not have a distinct type for loadable modules that are
2517
+ # pure BSD targets (not in a bundle wrapper). GYP allows such modules
2518
+ # to be specified by setting a target type to loadable_module without
2519
+ # having mac_bundle set. These are mapped to the pseudo-product type
2520
+ # com.googlecode.gyp.xcode.bundle.
2521
+ #
2522
+ # By picking up this special type and converting it to a dynamic
2523
+ # library (com.apple.product-type.library.dynamic) with fix-ups,
2524
+ # single-file loadable modules can be produced.
2525
+ #
2526
+ # MACH_O_TYPE is changed to mh_bundle to produce the proper file type
2527
+ # (as opposed to mh_dylib). In order for linking to succeed,
2528
+ # DYLIB_CURRENT_VERSION and DYLIB_COMPATIBILITY_VERSION must be
2529
+ # cleared. They are meaningless for type mh_bundle.
2530
+ #
2531
+ # Finally, the .so extension is forcibly applied over the default
2532
+ # (.dylib), unless another forced extension is already selected.
2533
+ # .dylib is plainly wrong, and .bundle is used by loadable_modules in
2534
+ # bundle wrappers (com.apple.product-type.bundle). .so seems an odd
2535
+ # choice because it's used as the extension on many other systems that
2536
+ # don't distinguish between linkable shared libraries and non-linkable
2537
+ # loadable modules, but there's precedent: Python loadable modules on
2538
+ # Mac OS X use an .so extension.
2539
+ if self._properties["productType"] == "com.googlecode.gyp.xcode.bundle":
2540
+ self._properties[
2541
+ "productType"
2542
+ ] = "com.apple.product-type.library.dynamic"
2543
+ self.SetBuildSetting("MACH_O_TYPE", "mh_bundle")
2544
+ self.SetBuildSetting("DYLIB_CURRENT_VERSION", "")
2545
+ self.SetBuildSetting("DYLIB_COMPATIBILITY_VERSION", "")
2546
+ if force_extension is None:
2547
+ force_extension = suffix[1:]
2548
+
2549
+ if (
2550
+ self._properties["productType"]
2551
+ == "com.apple.product-type-bundle.unit.test"
2552
+ or self._properties["productType"]
2553
+ == "com.apple.product-type-bundle.ui-testing"
2554
+ ):
2555
+ if force_extension is None:
2556
+ force_extension = suffix[1:]
2557
+
2558
+ if force_extension is not None:
2559
+ # If it's a wrapper (bundle), set WRAPPER_EXTENSION.
2560
+ # Extension override.
2561
+ suffix = "." + force_extension
2562
+ if filetype.startswith("wrapper."):
2563
+ self.SetBuildSetting("WRAPPER_EXTENSION", force_extension)
2564
+ else:
2565
+ self.SetBuildSetting("EXECUTABLE_EXTENSION", force_extension)
2566
+
2567
+ if filetype.startswith("compiled.mach-o.executable"):
2568
+ product_name = self._properties["productName"]
2569
+ product_name += suffix
2570
+ suffix = ""
2571
+ self.SetProperty("productName", product_name)
2572
+ self.SetBuildSetting("PRODUCT_NAME", product_name)
2573
+
2574
+ # Xcode handles most prefixes based on the target type, however there
2575
+ # are exceptions. If a "BSD Dynamic Library" target is added in the
2576
+ # Xcode UI, Xcode sets EXECUTABLE_PREFIX. This check duplicates that
2577
+ # behavior.
2578
+ if force_prefix is not None:
2579
+ prefix = force_prefix
2580
+ if filetype.startswith("wrapper."):
2581
+ self.SetBuildSetting("WRAPPER_PREFIX", prefix)
2582
+ else:
2583
+ self.SetBuildSetting("EXECUTABLE_PREFIX", prefix)
2584
+
2585
+ if force_outdir is not None:
2586
+ self.SetBuildSetting("TARGET_BUILD_DIR", force_outdir)
2587
+
2588
+ # TODO(tvl): Remove the below hack.
2589
+ # http://code.google.com/p/gyp/issues/detail?id=122
2590
+
2591
+ # Some targets include the prefix in the target_name. These targets
2592
+ # really should just add a product_name setting that doesn't include
2593
+ # the prefix. For example:
2594
+ # target_name = 'libevent', product_name = 'event'
2595
+ # This check cleans up for them.
2596
+ product_name = self._properties["productName"]
2597
+ prefix_len = len(prefix)
2598
+ if prefix_len and (product_name[:prefix_len] == prefix):
2599
+ product_name = product_name[prefix_len:]
2600
+ self.SetProperty("productName", product_name)
2601
+ self.SetBuildSetting("PRODUCT_NAME", product_name)
2602
+
2603
+ ref_props = {
2604
+ "explicitFileType": filetype,
2605
+ "includeInIndex": 0,
2606
+ "path": prefix + product_name + suffix,
2607
+ "sourceTree": "BUILT_PRODUCTS_DIR",
2608
+ }
2609
+ file_ref = PBXFileReference(ref_props)
2610
+ products_group.AppendChild(file_ref)
2611
+ self.SetProperty("productReference", file_ref)
2612
+
2613
+ def GetBuildPhaseByType(self, type):
2614
+ if "buildPhases" not in self._properties:
2615
+ return None
2616
+
2617
+ the_phase = None
2618
+ for phase in self._properties["buildPhases"]:
2619
+ if isinstance(phase, type):
2620
+ # Some phases may be present in multiples in a well-formed project file,
2621
+ # but phases like PBXSourcesBuildPhase may only be present singly, and
2622
+ # this function is intended as an aid to GetBuildPhaseByType. Loop
2623
+ # over the entire list of phases and assert if more than one of the
2624
+ # desired type is found.
2625
+ assert the_phase is None
2626
+ the_phase = phase
2627
+
2628
+ return the_phase
2629
+
2630
+ def HeadersPhase(self):
2631
+ headers_phase = self.GetBuildPhaseByType(PBXHeadersBuildPhase)
2632
+ if headers_phase is None:
2633
+ headers_phase = PBXHeadersBuildPhase()
2634
+
2635
+ # The headers phase should come before the resources, sources, and
2636
+ # frameworks phases, if any.
2637
+ insert_at = len(self._properties["buildPhases"])
2638
+ for index, phase in enumerate(self._properties["buildPhases"]):
2639
+ if (
2640
+ isinstance(phase, PBXResourcesBuildPhase)
2641
+ or isinstance(phase, PBXSourcesBuildPhase)
2642
+ or isinstance(phase, PBXFrameworksBuildPhase)
2643
+ ):
2644
+ insert_at = index
2645
+ break
2646
+
2647
+ self._properties["buildPhases"].insert(insert_at, headers_phase)
2648
+ headers_phase.parent = self
2649
+
2650
+ return headers_phase
2651
+
2652
+ def ResourcesPhase(self):
2653
+ resources_phase = self.GetBuildPhaseByType(PBXResourcesBuildPhase)
2654
+ if resources_phase is None:
2655
+ resources_phase = PBXResourcesBuildPhase()
2656
+
2657
+ # The resources phase should come before the sources and frameworks
2658
+ # phases, if any.
2659
+ insert_at = len(self._properties["buildPhases"])
2660
+ for index, phase in enumerate(self._properties["buildPhases"]):
2661
+ if isinstance(phase, PBXSourcesBuildPhase) or isinstance(
2662
+ phase, PBXFrameworksBuildPhase
2663
+ ):
2664
+ insert_at = index
2665
+ break
2666
+
2667
+ self._properties["buildPhases"].insert(insert_at, resources_phase)
2668
+ resources_phase.parent = self
2669
+
2670
+ return resources_phase
2671
+
2672
+ def SourcesPhase(self):
2673
+ sources_phase = self.GetBuildPhaseByType(PBXSourcesBuildPhase)
2674
+ if sources_phase is None:
2675
+ sources_phase = PBXSourcesBuildPhase()
2676
+ self.AppendProperty("buildPhases", sources_phase)
2677
+
2678
+ return sources_phase
2679
+
2680
+ def FrameworksPhase(self):
2681
+ frameworks_phase = self.GetBuildPhaseByType(PBXFrameworksBuildPhase)
2682
+ if frameworks_phase is None:
2683
+ frameworks_phase = PBXFrameworksBuildPhase()
2684
+ self.AppendProperty("buildPhases", frameworks_phase)
2685
+
2686
+ return frameworks_phase
2687
+
2688
+ def AddDependency(self, other):
2689
+ # super
2690
+ XCTarget.AddDependency(self, other)
2691
+
2692
+ static_library_type = "com.apple.product-type.library.static"
2693
+ shared_library_type = "com.apple.product-type.library.dynamic"
2694
+ framework_type = "com.apple.product-type.framework"
2695
+ if (
2696
+ isinstance(other, PBXNativeTarget)
2697
+ and "productType" in self._properties
2698
+ and self._properties["productType"] != static_library_type
2699
+ and "productType" in other._properties
2700
+ and (
2701
+ other._properties["productType"] == static_library_type
2702
+ or (
2703
+ (
2704
+ other._properties["productType"] == shared_library_type
2705
+ or other._properties["productType"] == framework_type
2706
+ )
2707
+ and (
2708
+ (not other.HasBuildSetting("MACH_O_TYPE"))
2709
+ or other.GetBuildSetting("MACH_O_TYPE") != "mh_bundle"
2710
+ )
2711
+ )
2712
+ )
2713
+ ):
2714
+
2715
+ file_ref = other.GetProperty("productReference")
2716
+
2717
+ pbxproject = self.PBXProjectAncestor()
2718
+ other_pbxproject = other.PBXProjectAncestor()
2719
+ if pbxproject != other_pbxproject:
2720
+ other_project_product_group = pbxproject.AddOrGetProjectReference(
2721
+ other_pbxproject
2722
+ )[0]
2723
+ file_ref = other_project_product_group.GetChildByRemoteObject(file_ref)
2724
+
2725
+ self.FrameworksPhase().AppendProperty(
2726
+ "files", PBXBuildFile({"fileRef": file_ref})
2727
+ )
2728
+
2729
+
2730
+ class PBXAggregateTarget(XCTarget):
2731
+ pass
2732
+
2733
+
2734
+ class PBXProject(XCContainerPortal):
2735
+ # A PBXProject is really just an XCObject, the XCContainerPortal thing is
2736
+ # just to allow PBXProject to be used in the containerPortal property of
2737
+ # PBXContainerItemProxy.
2738
+ """
2739
+
2740
+ Attributes:
2741
+ path: "sample.xcodeproj". TODO(mark) Document me!
2742
+ _other_pbxprojects: A dictionary, keyed by other PBXProject objects. Each
2743
+ value is a reference to the dict in the
2744
+ projectReferences list associated with the keyed
2745
+ PBXProject.
2746
+ """
2747
+
2748
+ _schema = XCContainerPortal._schema.copy()
2749
+ _schema.update(
2750
+ {
2751
+ "attributes": [0, dict, 0, 0],
2752
+ "buildConfigurationList": [
2753
+ 0,
2754
+ XCConfigurationList,
2755
+ 1,
2756
+ 1,
2757
+ XCConfigurationList(),
2758
+ ],
2759
+ "compatibilityVersion": [0, str, 0, 1, "Xcode 3.2"],
2760
+ "hasScannedForEncodings": [0, int, 0, 1, 1],
2761
+ "mainGroup": [0, PBXGroup, 1, 1, PBXGroup()],
2762
+ "projectDirPath": [0, str, 0, 1, ""],
2763
+ "projectReferences": [1, dict, 0, 0],
2764
+ "projectRoot": [0, str, 0, 1, ""],
2765
+ "targets": [1, XCTarget, 1, 1, []],
2766
+ }
2767
+ )
2768
+
2769
+ def __init__(self, properties=None, id=None, parent=None, path=None):
2770
+ self.path = path
2771
+ self._other_pbxprojects = {}
2772
+ # super
2773
+ return XCContainerPortal.__init__(self, properties, id, parent)
2774
+
2775
+ def Name(self):
2776
+ name = self.path
2777
+ if name[-10:] == ".xcodeproj":
2778
+ name = name[:-10]
2779
+ return posixpath.basename(name)
2780
+
2781
+ def Path(self):
2782
+ return self.path
2783
+
2784
+ def Comment(self):
2785
+ return "Project object"
2786
+
2787
+ def Children(self):
2788
+ # super
2789
+ children = XCContainerPortal.Children(self)
2790
+
2791
+ # Add children that the schema doesn't know about. Maybe there's a more
2792
+ # elegant way around this, but this is the only case where we need to own
2793
+ # objects in a dictionary (that is itself in a list), and three lines for
2794
+ # a one-off isn't that big a deal.
2795
+ if "projectReferences" in self._properties:
2796
+ for reference in self._properties["projectReferences"]:
2797
+ children.append(reference["ProductGroup"])
2798
+
2799
+ return children
2800
+
2801
+ def PBXProjectAncestor(self):
2802
+ return self
2803
+
2804
+ def _GroupByName(self, name):
2805
+ if "mainGroup" not in self._properties:
2806
+ self.SetProperty("mainGroup", PBXGroup())
2807
+
2808
+ main_group = self._properties["mainGroup"]
2809
+ group = main_group.GetChildByName(name)
2810
+ if group is None:
2811
+ group = PBXGroup({"name": name})
2812
+ main_group.AppendChild(group)
2813
+
2814
+ return group
2815
+
2816
+ # SourceGroup and ProductsGroup are created by default in Xcode's own
2817
+ # templates.
2818
+ def SourceGroup(self):
2819
+ return self._GroupByName("Source")
2820
+
2821
+ def ProductsGroup(self):
2822
+ return self._GroupByName("Products")
2823
+
2824
+ # IntermediatesGroup is used to collect source-like files that are generated
2825
+ # by rules or script phases and are placed in intermediate directories such
2826
+ # as DerivedSources.
2827
+ def IntermediatesGroup(self):
2828
+ return self._GroupByName("Intermediates")
2829
+
2830
+ # FrameworksGroup and ProjectsGroup are top-level groups used to collect
2831
+ # frameworks and projects.
2832
+ def FrameworksGroup(self):
2833
+ return self._GroupByName("Frameworks")
2834
+
2835
+ def ProjectsGroup(self):
2836
+ return self._GroupByName("Projects")
2837
+
2838
+ def RootGroupForPath(self, path):
2839
+ """Returns a PBXGroup child of this object to which path should be added.
2840
+
2841
+ This method is intended to choose between SourceGroup and
2842
+ IntermediatesGroup on the basis of whether path is present in a source
2843
+ directory or an intermediates directory. For the purposes of this
2844
+ determination, any path located within a derived file directory such as
2845
+ PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates
2846
+ directory.
2847
+
2848
+ The returned value is a two-element tuple. The first element is the
2849
+ PBXGroup, and the second element specifies whether that group should be
2850
+ organized hierarchically (True) or as a single flat list (False).
2851
+ """
2852
+
2853
+ # TODO(mark): make this a class variable and bind to self on call?
2854
+ # Also, this list is nowhere near exhaustive.
2855
+ # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by
2856
+ # gyp.generator.xcode. There should probably be some way for that module
2857
+ # to push the names in, rather than having to hard-code them here.
2858
+ source_tree_groups = {
2859
+ "DERIVED_FILE_DIR": (self.IntermediatesGroup, True),
2860
+ "INTERMEDIATE_DIR": (self.IntermediatesGroup, True),
2861
+ "PROJECT_DERIVED_FILE_DIR": (self.IntermediatesGroup, True),
2862
+ "SHARED_INTERMEDIATE_DIR": (self.IntermediatesGroup, True),
2863
+ }
2864
+
2865
+ (source_tree, path) = SourceTreeAndPathFromPath(path)
2866
+ if source_tree is not None and source_tree in source_tree_groups:
2867
+ (group_func, hierarchical) = source_tree_groups[source_tree]
2868
+ group = group_func()
2869
+ return (group, hierarchical)
2870
+
2871
+ # TODO(mark): make additional choices based on file extension.
2872
+
2873
+ return (self.SourceGroup(), True)
2874
+
2875
+ def AddOrGetFileInRootGroup(self, path):
2876
+ """Returns a PBXFileReference corresponding to path in the correct group
2877
+ according to RootGroupForPath's heuristics.
2878
+
2879
+ If an existing PBXFileReference for path exists, it will be returned.
2880
+ Otherwise, one will be created and returned.
2881
+ """
2882
+
2883
+ (group, hierarchical) = self.RootGroupForPath(path)
2884
+ return group.AddOrGetFileByPath(path, hierarchical)
2885
+
2886
+ def RootGroupsTakeOverOnlyChildren(self, recurse=False):
2887
+ """Calls TakeOverOnlyChild for all groups in the main group."""
2888
+
2889
+ for group in self._properties["mainGroup"]._properties["children"]:
2890
+ if isinstance(group, PBXGroup):
2891
+ group.TakeOverOnlyChild(recurse)
2892
+
2893
+ def SortGroups(self):
2894
+ # Sort the children of the mainGroup (like "Source" and "Products")
2895
+ # according to their defined order.
2896
+ self._properties["mainGroup"]._properties["children"] = sorted(
2897
+ self._properties["mainGroup"]._properties["children"],
2898
+ key=cmp_to_key(lambda x, y: x.CompareRootGroup(y)),
2899
+ )
2900
+
2901
+ # Sort everything else by putting group before files, and going
2902
+ # alphabetically by name within sections of groups and files. SortGroup
2903
+ # is recursive.
2904
+ for group in self._properties["mainGroup"]._properties["children"]:
2905
+ if not isinstance(group, PBXGroup):
2906
+ continue
2907
+
2908
+ if group.Name() == "Products":
2909
+ # The Products group is a special case. Instead of sorting
2910
+ # alphabetically, sort things in the order of the targets that
2911
+ # produce the products. To do this, just build up a new list of
2912
+ # products based on the targets.
2913
+ products = []
2914
+ for target in self._properties["targets"]:
2915
+ if not isinstance(target, PBXNativeTarget):
2916
+ continue
2917
+ product = target._properties["productReference"]
2918
+ # Make sure that the product is already in the products group.
2919
+ assert product in group._properties["children"]
2920
+ products.append(product)
2921
+
2922
+ # Make sure that this process doesn't miss anything that was already
2923
+ # in the products group.
2924
+ assert len(products) == len(group._properties["children"])
2925
+ group._properties["children"] = products
2926
+ else:
2927
+ group.SortGroup()
2928
+
2929
+ def AddOrGetProjectReference(self, other_pbxproject):
2930
+ """Add a reference to another project file (via PBXProject object) to this
2931
+ one.
2932
+
2933
+ Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in
2934
+ this project file that contains a PBXReferenceProxy object for each
2935
+ product of each PBXNativeTarget in the other project file. ProjectRef is
2936
+ a PBXFileReference to the other project file.
2937
+
2938
+ If this project file already references the other project file, the
2939
+ existing ProductGroup and ProjectRef are returned. The ProductGroup will
2940
+ still be updated if necessary.
2941
+ """
2942
+
2943
+ if "projectReferences" not in self._properties:
2944
+ self._properties["projectReferences"] = []
2945
+
2946
+ product_group = None
2947
+ project_ref = None
2948
+
2949
+ if other_pbxproject not in self._other_pbxprojects:
2950
+ # This project file isn't yet linked to the other one. Establish the
2951
+ # link.
2952
+ product_group = PBXGroup({"name": "Products"})
2953
+
2954
+ # ProductGroup is strong.
2955
+ product_group.parent = self
2956
+
2957
+ # There's nothing unique about this PBXGroup, and if left alone, it will
2958
+ # wind up with the same set of hashables as all other PBXGroup objects
2959
+ # owned by the projectReferences list. Add the hashables of the
2960
+ # remote PBXProject that it's related to.
2961
+ product_group._hashables.extend(other_pbxproject.Hashables())
2962
+
2963
+ # The other project reports its path as relative to the same directory
2964
+ # that this project's path is relative to. The other project's path
2965
+ # is not necessarily already relative to this project. Figure out the
2966
+ # pathname that this project needs to use to refer to the other one.
2967
+ this_path = posixpath.dirname(self.Path())
2968
+ projectDirPath = self.GetProperty("projectDirPath")
2969
+ if projectDirPath:
2970
+ if posixpath.isabs(projectDirPath[0]):
2971
+ this_path = projectDirPath
2972
+ else:
2973
+ this_path = posixpath.join(this_path, projectDirPath)
2974
+ other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path)
2975
+
2976
+ # ProjectRef is weak (it's owned by the mainGroup hierarchy).
2977
+ project_ref = PBXFileReference(
2978
+ {
2979
+ "lastKnownFileType": "wrapper.pb-project",
2980
+ "path": other_path,
2981
+ "sourceTree": "SOURCE_ROOT",
2982
+ }
2983
+ )
2984
+ self.ProjectsGroup().AppendChild(project_ref)
2985
+
2986
+ ref_dict = {"ProductGroup": product_group, "ProjectRef": project_ref}
2987
+ self._other_pbxprojects[other_pbxproject] = ref_dict
2988
+ self.AppendProperty("projectReferences", ref_dict)
2989
+
2990
+ # Xcode seems to sort this list case-insensitively
2991
+ self._properties["projectReferences"] = sorted(
2992
+ self._properties["projectReferences"],
2993
+ key=lambda x: x["ProjectRef"].Name().lower
2994
+ )
2995
+ else:
2996
+ # The link already exists. Pull out the relevnt data.
2997
+ project_ref_dict = self._other_pbxprojects[other_pbxproject]
2998
+ product_group = project_ref_dict["ProductGroup"]
2999
+ project_ref = project_ref_dict["ProjectRef"]
3000
+
3001
+ self._SetUpProductReferences(other_pbxproject, product_group, project_ref)
3002
+
3003
+ inherit_unique_symroot = self._AllSymrootsUnique(other_pbxproject, False)
3004
+ targets = other_pbxproject.GetProperty("targets")
3005
+ if all(self._AllSymrootsUnique(t, inherit_unique_symroot) for t in targets):
3006
+ dir_path = project_ref._properties["path"]
3007
+ product_group._hashables.extend(dir_path)
3008
+
3009
+ return [product_group, project_ref]
3010
+
3011
+ def _AllSymrootsUnique(self, target, inherit_unique_symroot):
3012
+ # Returns True if all configurations have a unique 'SYMROOT' attribute.
3013
+ # The value of inherit_unique_symroot decides, if a configuration is assumed
3014
+ # to inherit a unique 'SYMROOT' attribute from its parent, if it doesn't
3015
+ # define an explicit value for 'SYMROOT'.
3016
+ symroots = self._DefinedSymroots(target)
3017
+ for s in self._DefinedSymroots(target):
3018
+ if (
3019
+ s is not None
3020
+ and not self._IsUniqueSymrootForTarget(s)
3021
+ or s is None
3022
+ and not inherit_unique_symroot
3023
+ ):
3024
+ return False
3025
+ return True if symroots else inherit_unique_symroot
3026
+
3027
+ def _DefinedSymroots(self, target):
3028
+ # Returns all values for the 'SYMROOT' attribute defined in all
3029
+ # configurations for this target. If any configuration doesn't define the
3030
+ # 'SYMROOT' attribute, None is added to the returned set. If all
3031
+ # configurations don't define the 'SYMROOT' attribute, an empty set is
3032
+ # returned.
3033
+ config_list = target.GetProperty("buildConfigurationList")
3034
+ symroots = set()
3035
+ for config in config_list.GetProperty("buildConfigurations"):
3036
+ setting = config.GetProperty("buildSettings")
3037
+ if "SYMROOT" in setting:
3038
+ symroots.add(setting["SYMROOT"])
3039
+ else:
3040
+ symroots.add(None)
3041
+ if len(symroots) == 1 and None in symroots:
3042
+ return set()
3043
+ return symroots
3044
+
3045
+ def _IsUniqueSymrootForTarget(self, symroot):
3046
+ # This method returns True if all configurations in target contain a
3047
+ # 'SYMROOT' attribute that is unique for the given target. A value is
3048
+ # unique, if the Xcode macro '$SRCROOT' appears in it in any form.
3049
+ uniquifier = ["$SRCROOT", "$(SRCROOT)"]
3050
+ if any(x in symroot for x in uniquifier):
3051
+ return True
3052
+ return False
3053
+
3054
+ def _SetUpProductReferences(self, other_pbxproject, product_group, project_ref):
3055
+ # TODO(mark): This only adds references to products in other_pbxproject
3056
+ # when they don't exist in this pbxproject. Perhaps it should also
3057
+ # remove references from this pbxproject that are no longer present in
3058
+ # other_pbxproject. Perhaps it should update various properties if they
3059
+ # change.
3060
+ for target in other_pbxproject._properties["targets"]:
3061
+ if not isinstance(target, PBXNativeTarget):
3062
+ continue
3063
+
3064
+ other_fileref = target._properties["productReference"]
3065
+ if product_group.GetChildByRemoteObject(other_fileref) is None:
3066
+ # Xcode sets remoteInfo to the name of the target and not the name
3067
+ # of its product, despite this proxy being a reference to the product.
3068
+ container_item = PBXContainerItemProxy(
3069
+ {
3070
+ "containerPortal": project_ref,
3071
+ "proxyType": 2,
3072
+ "remoteGlobalIDString": other_fileref,
3073
+ "remoteInfo": target.Name(),
3074
+ }
3075
+ )
3076
+ # TODO(mark): Does sourceTree get copied straight over from the other
3077
+ # project? Can the other project ever have lastKnownFileType here
3078
+ # instead of explicitFileType? (Use it if so?) Can path ever be
3079
+ # unset? (I don't think so.) Can other_fileref have name set, and
3080
+ # does it impact the PBXReferenceProxy if so? These are the questions
3081
+ # that perhaps will be answered one day.
3082
+ reference_proxy = PBXReferenceProxy(
3083
+ {
3084
+ "fileType": other_fileref._properties["explicitFileType"],
3085
+ "path": other_fileref._properties["path"],
3086
+ "sourceTree": other_fileref._properties["sourceTree"],
3087
+ "remoteRef": container_item,
3088
+ }
3089
+ )
3090
+
3091
+ product_group.AppendChild(reference_proxy)
3092
+
3093
+ def SortRemoteProductReferences(self):
3094
+ # For each remote project file, sort the associated ProductGroup in the
3095
+ # same order that the targets are sorted in the remote project file. This
3096
+ # is the sort order used by Xcode.
3097
+
3098
+ def CompareProducts(x, y, remote_products):
3099
+ # x and y are PBXReferenceProxy objects. Go through their associated
3100
+ # PBXContainerItem to get the remote PBXFileReference, which will be
3101
+ # present in the remote_products list.
3102
+ x_remote = x._properties["remoteRef"]._properties["remoteGlobalIDString"]
3103
+ y_remote = y._properties["remoteRef"]._properties["remoteGlobalIDString"]
3104
+ x_index = remote_products.index(x_remote)
3105
+ y_index = remote_products.index(y_remote)
3106
+
3107
+ # Use the order of each remote PBXFileReference in remote_products to
3108
+ # determine the sort order.
3109
+ return cmp(x_index, y_index)
3110
+
3111
+ for other_pbxproject, ref_dict in self._other_pbxprojects.items():
3112
+ # Build up a list of products in the remote project file, ordered the
3113
+ # same as the targets that produce them.
3114
+ remote_products = []
3115
+ for target in other_pbxproject._properties["targets"]:
3116
+ if not isinstance(target, PBXNativeTarget):
3117
+ continue
3118
+ remote_products.append(target._properties["productReference"])
3119
+
3120
+ # Sort the PBXReferenceProxy children according to the list of remote
3121
+ # products.
3122
+ product_group = ref_dict["ProductGroup"]
3123
+ product_group._properties["children"] = sorted(
3124
+ product_group._properties["children"],
3125
+ key=cmp_to_key(
3126
+ lambda x, y, rp=remote_products: CompareProducts(x, y, rp)),
3127
+ )
3128
+
3129
+
3130
+ class XCProjectFile(XCObject):
3131
+ _schema = XCObject._schema.copy()
3132
+ _schema.update(
3133
+ {
3134
+ "archiveVersion": [0, int, 0, 1, 1],
3135
+ "classes": [0, dict, 0, 1, {}],
3136
+ "objectVersion": [0, int, 0, 1, 46],
3137
+ "rootObject": [0, PBXProject, 1, 1],
3138
+ }
3139
+ )
3140
+
3141
+ def ComputeIDs(self, recursive=True, overwrite=True, hash=None):
3142
+ # Although XCProjectFile is implemented here as an XCObject, it's not a
3143
+ # proper object in the Xcode sense, and it certainly doesn't have its own
3144
+ # ID. Pass through an attempt to update IDs to the real root object.
3145
+ if recursive:
3146
+ self._properties["rootObject"].ComputeIDs(recursive, overwrite, hash)
3147
+
3148
+ def Print(self, file=sys.stdout):
3149
+ self.VerifyHasRequiredProperties()
3150
+
3151
+ # Add the special "objects" property, which will be caught and handled
3152
+ # separately during printing. This structure allows a fairly standard
3153
+ # loop do the normal printing.
3154
+ self._properties["objects"] = {}
3155
+ self._XCPrint(file, 0, "// !$*UTF8*$!\n")
3156
+ if self._should_print_single_line:
3157
+ self._XCPrint(file, 0, "{ ")
3158
+ else:
3159
+ self._XCPrint(file, 0, "{\n")
3160
+ for property, value in sorted(
3161
+ self._properties.items()
3162
+ ):
3163
+ if property == "objects":
3164
+ self._PrintObjects(file)
3165
+ else:
3166
+ self._XCKVPrint(file, 1, property, value)
3167
+ self._XCPrint(file, 0, "}\n")
3168
+ del self._properties["objects"]
3169
+
3170
+ def _PrintObjects(self, file):
3171
+ if self._should_print_single_line:
3172
+ self._XCPrint(file, 0, "objects = {")
3173
+ else:
3174
+ self._XCPrint(file, 1, "objects = {\n")
3175
+
3176
+ objects_by_class = {}
3177
+ for object in self.Descendants():
3178
+ if object == self:
3179
+ continue
3180
+ class_name = object.__class__.__name__
3181
+ if class_name not in objects_by_class:
3182
+ objects_by_class[class_name] = []
3183
+ objects_by_class[class_name].append(object)
3184
+
3185
+ for class_name in sorted(objects_by_class):
3186
+ self._XCPrint(file, 0, "\n")
3187
+ self._XCPrint(file, 0, "/* Begin " + class_name + " section */\n")
3188
+ for object in sorted(
3189
+ objects_by_class[class_name], key=attrgetter("id")
3190
+ ):
3191
+ object.Print(file)
3192
+ self._XCPrint(file, 0, "/* End " + class_name + " section */\n")
3193
+
3194
+ if self._should_print_single_line:
3195
+ self._XCPrint(file, 0, "}; ")
3196
+ else:
3197
+ self._XCPrint(file, 1, "};\n")