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