PageRenderTime 88ms CodeModel.GetById 24ms RepoModel.GetById 12ms app.codeStats 0ms

/media/webrtc/trunk/tools/gyp/pylib/gyp/xcodeproj_file.py

https://bitbucket.org/hsoft/mozilla-central
Python | 2834 lines | 2642 code | 55 blank | 137 comment | 66 complexity | 5f96f8c76b9100e62d188c2eecf06ea3 MD5 | raw file
Possible License(s): JSON, LGPL-2.1, LGPL-3.0, AGPL-1.0, MIT, MPL-2.0-no-copyleft-exception, Apache-2.0, GPL-2.0, BSD-2-Clause, MPL-2.0, BSD-3-Clause, 0BSD
  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. """Xcode project file generator.
  5. This module is both an Xcode project file generator and a documentation of the
  6. Xcode project file format. Knowledge of the project file format was gained
  7. based on extensive experience with Xcode, and by making changes to projects in
  8. Xcode.app and observing the resultant changes in the associated project files.
  9. XCODE PROJECT FILES
  10. The generator targets the file format as written by Xcode 3.2 (specifically,
  11. 3.2.6), but past experience has taught that the format has not changed
  12. significantly in the past several years, and future versions of Xcode are able
  13. to read older project files.
  14. Xcode project files are "bundled": the project "file" from an end-user's
  15. perspective is actually a directory with an ".xcodeproj" extension. The
  16. project file from this module's perspective is actually a file inside this
  17. directory, always named "project.pbxproj". This file contains a complete
  18. description of the project and is all that is needed to use the xcodeproj.
  19. Other files contained in the xcodeproj directory are simply used to store
  20. per-user settings, such as the state of various UI elements in the Xcode
  21. application.
  22. The project.pbxproj file is a property list, stored in a format almost
  23. identical to the NeXTstep property list format. The file is able to carry
  24. Unicode data, and is encoded in UTF-8. The root element in the property list
  25. is a dictionary that contains several properties of minimal interest, and two
  26. properties of immense interest. The most important property is a dictionary
  27. named "objects". The entire structure of the project is represented by the
  28. children of this property. The objects dictionary is keyed by unique 96-bit
  29. values represented by 24 uppercase hexadecimal characters. Each value in the
  30. objects dictionary is itself a dictionary, describing an individual object.
  31. Each object in the dictionary is a member of a class, which is identified by
  32. the "isa" property of each object. A variety of classes are represented in a
  33. project file. Objects can refer to other objects by ID, using the 24-character
  34. hexadecimal object key. A project's objects form a tree, with a root object
  35. of class PBXProject at the root. As an example, the PBXProject object serves
  36. as parent to an XCConfigurationList object defining the build configurations
  37. used in the project, a PBXGroup object serving as a container for all files
  38. referenced in the project, and a list of target objects, each of which defines
  39. a target in the project. There are several different types of target object,
  40. such as PBXNativeTarget and PBXAggregateTarget. In this module, this
  41. relationship is expressed by having each target type derive from an abstract
  42. base named XCTarget.
  43. The project.pbxproj file's root dictionary also contains a property, sibling to
  44. the "objects" dictionary, named "rootObject". The value of rootObject is a
  45. 24-character object key referring to the root PBXProject object in the
  46. objects dictionary.
  47. In Xcode, every file used as input to a target or produced as a final product
  48. of a target must appear somewhere in the hierarchy rooted at the PBXGroup
  49. object referenced by the PBXProject's mainGroup property. A PBXGroup is
  50. generally represented as a folder in the Xcode application. PBXGroups can
  51. contain other PBXGroups as well as PBXFileReferences, which are pointers to
  52. actual files.
  53. Each XCTarget contains a list of build phases, represented in this module by
  54. the abstract base XCBuildPhase. Examples of concrete XCBuildPhase derivations
  55. are PBXSourcesBuildPhase and PBXFrameworksBuildPhase, which correspond to the
  56. "Compile Sources" and "Link Binary With Libraries" phases displayed in the
  57. Xcode application. Files used as input to these phases (for example, source
  58. files in the former case and libraries and frameworks in the latter) are
  59. represented by PBXBuildFile objects, referenced by elements of "files" lists
  60. in XCTarget objects. Each PBXBuildFile object refers to a PBXBuildFile
  61. object as a "weak" reference: it does not "own" the PBXBuildFile, which is
  62. owned by the root object's mainGroup or a descendant group. In most cases, the
  63. layer of indirection between an XCBuildPhase and a PBXFileReference via a
  64. PBXBuildFile appears extraneous, but there's actually one reason for this:
  65. file-specific compiler flags are added to the PBXBuildFile object so as to
  66. allow a single file to be a member of multiple targets while having distinct
  67. compiler flags for each. These flags can be modified in the Xcode applciation
  68. in the "Build" tab of a File Info window.
  69. When a project is open in the Xcode application, Xcode will rewrite it. As
  70. such, this module is careful to adhere to the formatting used by Xcode, to
  71. avoid insignificant changes appearing in the file when it is used in the
  72. Xcode application. This will keep version control repositories happy, and
  73. makes it possible to compare a project file used in Xcode to one generated by
  74. this module to determine if any significant changes were made in the
  75. application.
  76. Xcode has its own way of assigning 24-character identifiers to each object,
  77. which is not duplicated here. Because the identifier only is only generated
  78. once, when an object is created, and is then left unchanged, there is no need
  79. to attempt to duplicate Xcode's behavior in this area. The generator is free
  80. to select any identifier, even at random, to refer to the objects it creates,
  81. and Xcode will retain those identifiers and use them when subsequently
  82. rewriting the project file. However, the generator would choose new random
  83. identifiers each time the project files are generated, leading to difficulties
  84. comparing "used" project files to "pristine" ones produced by this module,
  85. and causing the appearance of changes as every object identifier is changed
  86. when updated projects are checked in to a version control repository. To
  87. mitigate this problem, this module chooses identifiers in a more deterministic
  88. way, by hashing a description of each object as well as its parent and ancestor
  89. objects. This strategy should result in minimal "shift" in IDs as successive
  90. generations of project files are produced.
  91. THIS MODULE
  92. This module introduces several classes, all derived from the XCObject class.
  93. Nearly all of the "brains" are built into the XCObject class, which understands
  94. how to create and modify objects, maintain the proper tree structure, compute
  95. identifiers, and print objects. For the most part, classes derived from
  96. XCObject need only provide a _schema class object, a dictionary that
  97. expresses what properties objects of the class may contain.
  98. Given this structure, it's possible to build a minimal project file by creating
  99. objects of the appropriate types and making the proper connections:
  100. config_list = XCConfigurationList()
  101. group = PBXGroup()
  102. project = PBXProject({'buildConfigurationList': config_list,
  103. 'mainGroup': group})
  104. With the project object set up, it can be added to an XCProjectFile object.
  105. XCProjectFile is a pseudo-class in the sense that it is a concrete XCObject
  106. subclass that does not actually correspond to a class type found in a project
  107. file. Rather, it is used to represent the project file's root dictionary.
  108. Printing an XCProjectFile will print the entire project file, including the
  109. full "objects" dictionary.
  110. project_file = XCProjectFile({'rootObject': project})
  111. project_file.ComputeIDs()
  112. project_file.Print()
  113. Xcode project files are always encoded in UTF-8. This module will accept
  114. strings of either the str class or the unicode class. Strings of class str
  115. are assumed to already be encoded in UTF-8. Obviously, if you're just using
  116. ASCII, you won't encounter difficulties because ASCII is a UTF-8 subset.
  117. Strings of class unicode are handled properly and encoded in UTF-8 when
  118. a project file is output.
  119. """
  120. import gyp.common
  121. import posixpath
  122. import re
  123. import struct
  124. import sys
  125. # hashlib is supplied as of Python 2.5 as the replacement interface for sha
  126. # and other secure hashes. In 2.6, sha is deprecated. Import hashlib if
  127. # available, avoiding a deprecation warning under 2.6. Import sha otherwise,
  128. # preserving 2.4 compatibility.
  129. try:
  130. import hashlib
  131. _new_sha1 = hashlib.sha1
  132. except ImportError:
  133. import sha
  134. _new_sha1 = sha.new
  135. # See XCObject._EncodeString. This pattern is used to determine when a string
  136. # can be printed unquoted. Strings that match this pattern may be printed
  137. # unquoted. Strings that do not match must be quoted and may be further
  138. # transformed to be properly encoded. Note that this expression matches the
  139. # characters listed with "+", for 1 or more occurrences: if a string is empty,
  140. # it must not match this pattern, because it needs to be encoded as "".
  141. _unquoted = re.compile('^[A-Za-z0-9$./_]+$')
  142. # Strings that match this pattern are quoted regardless of what _unquoted says.
  143. # Oddly, Xcode will quote any string with a run of three or more underscores.
  144. _quoted = re.compile('___')
  145. # This pattern should match any character that needs to be escaped by
  146. # XCObject._EncodeString. See that function.
  147. _escaped = re.compile('[\\\\"]|[^ -~]')
  148. # Used by SourceTreeAndPathFromPath
  149. _path_leading_variable = re.compile('^\$\((.*?)\)(/(.*))?$')
  150. def SourceTreeAndPathFromPath(input_path):
  151. """Given input_path, returns a tuple with sourceTree and path values.
  152. Examples:
  153. input_path (source_tree, output_path)
  154. '$(VAR)/path' ('VAR', 'path')
  155. '$(VAR)' ('VAR', None)
  156. 'path' (None, 'path')
  157. """
  158. source_group_match = _path_leading_variable.match(input_path)
  159. if source_group_match:
  160. source_tree = source_group_match.group(1)
  161. output_path = source_group_match.group(3) # This may be None.
  162. else:
  163. source_tree = None
  164. output_path = input_path
  165. return (source_tree, output_path)
  166. def ConvertVariablesToShellSyntax(input_string):
  167. return re.sub('\$\((.*?)\)', '${\\1}', input_string)
  168. class XCObject(object):
  169. """The abstract base of all class types used in Xcode project files.
  170. Class variables:
  171. _schema: A dictionary defining the properties of this class. The keys to
  172. _schema are string property keys as used in project files. Values
  173. are a list of four or five elements:
  174. [ is_list, property_type, is_strong, is_required, default ]
  175. is_list: True if the property described is a list, as opposed
  176. to a single element.
  177. property_type: The type to use as the value of the property,
  178. or if is_list is True, the type to use for each
  179. element of the value's list. property_type must
  180. be an XCObject subclass, or one of the built-in
  181. types str, int, or dict.
  182. is_strong: If property_type is an XCObject subclass, is_strong
  183. is True to assert that this class "owns," or serves
  184. as parent, to the property value (or, if is_list is
  185. True, values). is_strong must be False if
  186. property_type is not an XCObject subclass.
  187. is_required: True if the property is required for the class.
  188. Note that is_required being True does not preclude
  189. an empty string ("", in the case of property_type
  190. str) or list ([], in the case of is_list True) from
  191. being set for the property.
  192. default: Optional. If is_requried is True, default may be set
  193. to provide a default value for objects that do not supply
  194. their own value. If is_required is True and default
  195. is not provided, users of the class must supply their own
  196. value for the property.
  197. Note that although the values of the array are expressed in
  198. boolean terms, subclasses provide values as integers to conserve
  199. horizontal space.
  200. _should_print_single_line: False in XCObject. Subclasses whose objects
  201. should be written to the project file in the
  202. alternate single-line format, such as
  203. PBXFileReference and PBXBuildFile, should
  204. set this to True.
  205. _encode_transforms: Used by _EncodeString to encode unprintable characters.
  206. The index into this list is the ordinal of the
  207. character to transform; each value is a string
  208. used to represent the character in the output. XCObject
  209. provides an _encode_transforms list suitable for most
  210. XCObject subclasses.
  211. _alternate_encode_transforms: Provided for subclasses that wish to use
  212. the alternate encoding rules. Xcode seems
  213. to use these rules when printing objects in
  214. single-line format. Subclasses that desire
  215. this behavior should set _encode_transforms
  216. to _alternate_encode_transforms.
  217. _hashables: A list of XCObject subclasses that can be hashed by ComputeIDs
  218. to construct this object's ID. Most classes that need custom
  219. hashing behavior should do it by overriding Hashables,
  220. but in some cases an object's parent may wish to push a
  221. hashable value into its child, and it can do so by appending
  222. to _hashables.
  223. Attribues:
  224. id: The object's identifier, a 24-character uppercase hexadecimal string.
  225. Usually, objects being created should not set id until the entire
  226. project file structure is built. At that point, UpdateIDs() should
  227. be called on the root object to assign deterministic values for id to
  228. each object in the tree.
  229. parent: The object's parent. This is set by a parent XCObject when a child
  230. object is added to it.
  231. _properties: The object's property dictionary. An object's properties are
  232. described by its class' _schema variable.
  233. """
  234. _schema = {}
  235. _should_print_single_line = False
  236. # See _EncodeString.
  237. _encode_transforms = []
  238. i = 0
  239. while i < ord(' '):
  240. _encode_transforms.append('\\U%04x' % i)
  241. i = i + 1
  242. _encode_transforms[7] = '\\a'
  243. _encode_transforms[8] = '\\b'
  244. _encode_transforms[9] = '\\t'
  245. _encode_transforms[10] = '\\n'
  246. _encode_transforms[11] = '\\v'
  247. _encode_transforms[12] = '\\f'
  248. _encode_transforms[13] = '\\n'
  249. _alternate_encode_transforms = list(_encode_transforms)
  250. _alternate_encode_transforms[9] = chr(9)
  251. _alternate_encode_transforms[10] = chr(10)
  252. _alternate_encode_transforms[11] = chr(11)
  253. def __init__(self, properties=None, id=None, parent=None):
  254. self.id = id
  255. self.parent = parent
  256. self._properties = {}
  257. self._hashables = []
  258. self._SetDefaultsFromSchema()
  259. self.UpdateProperties(properties)
  260. def __repr__(self):
  261. try:
  262. name = self.Name()
  263. except NotImplementedError:
  264. return '<%s at 0x%x>' % (self.__class__.__name__, id(self))
  265. return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self))
  266. def Copy(self):
  267. """Make a copy of this object.
  268. The new object will have its own copy of lists and dicts. Any XCObject
  269. objects owned by this object (marked "strong") will be copied in the
  270. new object, even those found in lists. If this object has any weak
  271. references to other XCObjects, the same references are added to the new
  272. object without making a copy.
  273. """
  274. that = self.__class__(id=self.id, parent=self.parent)
  275. for key, value in self._properties.iteritems():
  276. is_strong = self._schema[key][2]
  277. if isinstance(value, XCObject):
  278. if is_strong:
  279. new_value = value.Copy()
  280. new_value.parent = that
  281. that._properties[key] = new_value
  282. else:
  283. that._properties[key] = value
  284. elif isinstance(value, str) or isinstance(value, unicode) or \
  285. isinstance(value, int):
  286. that._properties[key] = value
  287. elif isinstance(value, list):
  288. if is_strong:
  289. # If is_strong is True, each element is an XCObject, so it's safe to
  290. # call Copy.
  291. that._properties[key] = []
  292. for item in value:
  293. new_item = item.Copy()
  294. new_item.parent = that
  295. that._properties[key].append(new_item)
  296. else:
  297. that._properties[key] = value[:]
  298. elif isinstance(value, dict):
  299. # dicts are never strong.
  300. if is_strong:
  301. raise TypeError, 'Strong dict for key ' + key + ' in ' + \
  302. self.__class__.__name__
  303. else:
  304. that._properties[key] = value.copy()
  305. else:
  306. raise TypeError, 'Unexpected type ' + value.__class__.__name__ + \
  307. ' for key ' + key + ' in ' + self.__class__.__name__
  308. return that
  309. def Name(self):
  310. """Return the name corresponding to an object.
  311. Not all objects necessarily need to be nameable, and not all that do have
  312. a "name" property. Override as needed.
  313. """
  314. # If the schema indicates that "name" is required, try to access the
  315. # property even if it doesn't exist. This will result in a KeyError
  316. # being raised for the property that should be present, which seems more
  317. # appropriate than NotImplementedError in this case.
  318. if 'name' in self._properties or \
  319. ('name' in self._schema and self._schema['name'][3]):
  320. return self._properties['name']
  321. raise NotImplementedError, \
  322. self.__class__.__name__ + ' must implement Name'
  323. def Comment(self):
  324. """Return a comment string for the object.
  325. Most objects just use their name as the comment, but PBXProject uses
  326. different values.
  327. The returned comment is not escaped and does not have any comment marker
  328. strings applied to it.
  329. """
  330. return self.Name()
  331. def Hashables(self):
  332. hashables = [self.__class__.__name__]
  333. name = self.Name()
  334. if name != None:
  335. hashables.append(name)
  336. hashables.extend(self._hashables)
  337. return hashables
  338. def ComputeIDs(self, recursive=True, overwrite=True, hash=None):
  339. """Set "id" properties deterministically.
  340. An object's "id" property is set based on a hash of its class type and
  341. name, as well as the class type and name of all ancestor objects. As
  342. such, it is only advisable to call ComputeIDs once an entire project file
  343. tree is built.
  344. If recursive is True, recurse into all descendant objects and update their
  345. hashes.
  346. If overwrite is True, any existing value set in the "id" property will be
  347. replaced.
  348. """
  349. def _HashUpdate(hash, data):
  350. """Update hash with data's length and contents.
  351. If the hash were updated only with the value of data, it would be
  352. possible for clowns to induce collisions by manipulating the names of
  353. their objects. By adding the length, it's exceedingly less likely that
  354. ID collisions will be encountered, intentionally or not.
  355. """
  356. hash.update(struct.pack('>i', len(data)))
  357. hash.update(data)
  358. if hash is None:
  359. hash = _new_sha1()
  360. hashables = self.Hashables()
  361. assert len(hashables) > 0
  362. for hashable in hashables:
  363. _HashUpdate(hash, hashable)
  364. if recursive:
  365. for child in self.Children():
  366. child.ComputeIDs(recursive, overwrite, hash.copy())
  367. if overwrite or self.id is None:
  368. # Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is
  369. # is 160 bits. Instead of throwing out 64 bits of the digest, xor them
  370. # into the portion that gets used.
  371. assert hash.digest_size % 4 == 0
  372. digest_int_count = hash.digest_size / 4
  373. digest_ints = struct.unpack('>' + 'I' * digest_int_count, hash.digest())
  374. id_ints = [0, 0, 0]
  375. for index in xrange(0, digest_int_count):
  376. id_ints[index % 3] ^= digest_ints[index]
  377. self.id = '%08X%08X%08X' % tuple(id_ints)
  378. def EnsureNoIDCollisions(self):
  379. """Verifies that no two objects have the same ID. Checks all descendants.
  380. """
  381. ids = {}
  382. descendants = self.Descendants()
  383. for descendant in descendants:
  384. if descendant.id in ids:
  385. other = ids[descendant.id]
  386. raise KeyError, \
  387. 'Duplicate ID %s, objects "%s" and "%s" in "%s"' % \
  388. (descendant.id, str(descendant._properties),
  389. str(other._properties), self._properties['rootObject'].Name())
  390. ids[descendant.id] = descendant
  391. def Children(self):
  392. """Returns a list of all of this object's owned (strong) children."""
  393. children = []
  394. for property, attributes in self._schema.iteritems():
  395. (is_list, property_type, is_strong) = attributes[0:3]
  396. if is_strong and property in self._properties:
  397. if not is_list:
  398. children.append(self._properties[property])
  399. else:
  400. children.extend(self._properties[property])
  401. return children
  402. def Descendants(self):
  403. """Returns a list of all of this object's descendants, including this
  404. object.
  405. """
  406. children = self.Children()
  407. descendants = [self]
  408. for child in children:
  409. descendants.extend(child.Descendants())
  410. return descendants
  411. def PBXProjectAncestor(self):
  412. # The base case for recursion is defined at PBXProject.PBXProjectAncestor.
  413. if self.parent:
  414. return self.parent.PBXProjectAncestor()
  415. return None
  416. def _EncodeComment(self, comment):
  417. """Encodes a comment to be placed in the project file output, mimicing
  418. Xcode behavior.
  419. """
  420. # This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If
  421. # the string already contains a "*/", it is turned into "(*)/". This keeps
  422. # the file writer from outputting something that would be treated as the
  423. # end of a comment in the middle of something intended to be entirely a
  424. # comment.
  425. return '/* ' + comment.replace('*/', '(*)/') + ' */'
  426. def _EncodeTransform(self, match):
  427. # This function works closely with _EncodeString. It will only be called
  428. # by re.sub with match.group(0) containing a character matched by the
  429. # the _escaped expression.
  430. char = match.group(0)
  431. # Backslashes (\) and quotation marks (") are always replaced with a
  432. # backslash-escaped version of the same. Everything else gets its
  433. # replacement from the class' _encode_transforms array.
  434. if char == '\\':
  435. return '\\\\'
  436. if char == '"':
  437. return '\\"'
  438. return self._encode_transforms[ord(char)]
  439. def _EncodeString(self, value):
  440. """Encodes a string to be placed in the project file output, mimicing
  441. Xcode behavior.
  442. """
  443. # Use quotation marks when any character outside of the range A-Z, a-z, 0-9,
  444. # $ (dollar sign), . (period), and _ (underscore) is present. Also use
  445. # quotation marks to represent empty strings.
  446. #
  447. # Escape " (double-quote) and \ (backslash) by preceding them with a
  448. # backslash.
  449. #
  450. # Some characters below the printable ASCII range are encoded specially:
  451. # 7 ^G BEL is encoded as "\a"
  452. # 8 ^H BS is encoded as "\b"
  453. # 11 ^K VT is encoded as "\v"
  454. # 12 ^L NP is encoded as "\f"
  455. # 127 ^? DEL is passed through as-is without escaping
  456. # - In PBXFileReference and PBXBuildFile objects:
  457. # 9 ^I HT is passed through as-is without escaping
  458. # 10 ^J NL is passed through as-is without escaping
  459. # 13 ^M CR is passed through as-is without escaping
  460. # - In other objects:
  461. # 9 ^I HT is encoded as "\t"
  462. # 10 ^J NL is encoded as "\n"
  463. # 13 ^M CR is encoded as "\n" rendering it indistinguishable from
  464. # 10 ^J NL
  465. # All other nonprintable characters within the ASCII range (0 through 127
  466. # inclusive) are encoded as "\U001f" referring to the Unicode code point in
  467. # hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e".
  468. # Characters above the ASCII range are passed through to the output encoded
  469. # as UTF-8 without any escaping. These mappings are contained in the
  470. # class' _encode_transforms list.
  471. if _unquoted.search(value) and not _quoted.search(value):
  472. return value
  473. return '"' + _escaped.sub(self._EncodeTransform, value) + '"'
  474. def _XCPrint(self, file, tabs, line):
  475. file.write('\t' * tabs + line)
  476. def _XCPrintableValue(self, tabs, value, flatten_list=False):
  477. """Returns a representation of value that may be printed in a project file,
  478. mimicing Xcode's behavior.
  479. _XCPrintableValue can handle str and int values, XCObjects (which are
  480. made printable by returning their id property), and list and dict objects
  481. composed of any of the above types. When printing a list or dict, and
  482. _should_print_single_line is False, the tabs parameter is used to determine
  483. how much to indent the lines corresponding to the items in the list or
  484. dict.
  485. If flatten_list is True, single-element lists will be transformed into
  486. strings.
  487. """
  488. printable = ''
  489. comment = None
  490. if self._should_print_single_line:
  491. sep = ' '
  492. element_tabs = ''
  493. end_tabs = ''
  494. else:
  495. sep = '\n'
  496. element_tabs = '\t' * (tabs + 1)
  497. end_tabs = '\t' * tabs
  498. if isinstance(value, XCObject):
  499. printable += value.id
  500. comment = value.Comment()
  501. elif isinstance(value, str):
  502. printable += self._EncodeString(value)
  503. elif isinstance(value, unicode):
  504. printable += self._EncodeString(value.encode('utf-8'))
  505. elif isinstance(value, int):
  506. printable += str(value)
  507. elif isinstance(value, list):
  508. if flatten_list and len(value) <= 1:
  509. if len(value) == 0:
  510. printable += self._EncodeString('')
  511. else:
  512. printable += self._EncodeString(value[0])
  513. else:
  514. printable = '(' + sep
  515. for item in value:
  516. printable += element_tabs + \
  517. self._XCPrintableValue(tabs + 1, item, flatten_list) + \
  518. ',' + sep
  519. printable += end_tabs + ')'
  520. elif isinstance(value, dict):
  521. printable = '{' + sep
  522. for item_key, item_value in sorted(value.iteritems()):
  523. printable += element_tabs + \
  524. self._XCPrintableValue(tabs + 1, item_key, flatten_list) + ' = ' + \
  525. self._XCPrintableValue(tabs + 1, item_value, flatten_list) + ';' + \
  526. sep
  527. printable += end_tabs + '}'
  528. else:
  529. raise TypeError, "Can't make " + value.__class__.__name__ + ' printable'
  530. if comment != None:
  531. printable += ' ' + self._EncodeComment(comment)
  532. return printable
  533. def _XCKVPrint(self, file, tabs, key, value):
  534. """Prints a key and value, members of an XCObject's _properties dictionary,
  535. to file.
  536. tabs is an int identifying the indentation level. If the class'
  537. _should_print_single_line variable is True, tabs is ignored and the
  538. key-value pair will be followed by a space insead of a newline.
  539. """
  540. if self._should_print_single_line:
  541. printable = ''
  542. after_kv = ' '
  543. else:
  544. printable = '\t' * tabs
  545. after_kv = '\n'
  546. # Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy
  547. # objects without comments. Sometimes it prints them with comments, but
  548. # the majority of the time, it doesn't. To avoid unnecessary changes to
  549. # the project file after Xcode opens it, don't write comments for
  550. # remoteGlobalIDString. This is a sucky hack and it would certainly be
  551. # cleaner to extend the schema to indicate whether or not a comment should
  552. # be printed, but since this is the only case where the problem occurs and
  553. # Xcode itself can't seem to make up its mind, the hack will suffice.
  554. #
  555. # Also see PBXContainerItemProxy._schema['remoteGlobalIDString'].
  556. if key == 'remoteGlobalIDString' and isinstance(self,
  557. PBXContainerItemProxy):
  558. value_to_print = value.id
  559. else:
  560. value_to_print = value
  561. # PBXBuildFile's settings property is represented in the output as a dict,
  562. # but a hack here has it represented as a string. Arrange to strip off the
  563. # quotes so that it shows up in the output as expected.
  564. if key == 'settings' and isinstance(self, PBXBuildFile):
  565. strip_value_quotes = True
  566. else:
  567. strip_value_quotes = False
  568. # In another one-off, let's set flatten_list on buildSettings properties
  569. # of XCBuildConfiguration objects, because that's how Xcode treats them.
  570. if key == 'buildSettings' and isinstance(self, XCBuildConfiguration):
  571. flatten_list = True
  572. else:
  573. flatten_list = False
  574. try:
  575. printable_key = self._XCPrintableValue(tabs, key, flatten_list)
  576. printable_value = self._XCPrintableValue(tabs, value_to_print,
  577. flatten_list)
  578. if strip_value_quotes and len(printable_value) > 1 and \
  579. printable_value[0] == '"' and printable_value[-1] == '"':
  580. printable_value = printable_value[1:-1]
  581. printable += printable_key + ' = ' + printable_value + ';' + after_kv
  582. except TypeError, e:
  583. gyp.common.ExceptionAppend(e,
  584. 'while printing key "%s"' % key)
  585. raise
  586. self._XCPrint(file, 0, printable)
  587. def Print(self, file=sys.stdout):
  588. """Prints a reprentation of this object to file, adhering to Xcode output
  589. formatting.
  590. """
  591. self.VerifyHasRequiredProperties()
  592. if self._should_print_single_line:
  593. # When printing an object in a single line, Xcode doesn't put any space
  594. # between the beginning of a dictionary (or presumably a list) and the
  595. # first contained item, so you wind up with snippets like
  596. # ...CDEF = {isa = PBXFileReference; fileRef = 0123...
  597. # If it were me, I would have put a space in there after the opening
  598. # curly, but I guess this is just another one of those inconsistencies
  599. # between how Xcode prints PBXFileReference and PBXBuildFile objects as
  600. # compared to other objects. Mimic Xcode's behavior here by using an
  601. # empty string for sep.
  602. sep = ''
  603. end_tabs = 0
  604. else:
  605. sep = '\n'
  606. end_tabs = 2
  607. # Start the object. For example, '\t\tPBXProject = {\n'.
  608. self._XCPrint(file, 2, self._XCPrintableValue(2, self) + ' = {' + sep)
  609. # "isa" isn't in the _properties dictionary, it's an intrinsic property
  610. # of the class which the object belongs to. Xcode always outputs "isa"
  611. # as the first element of an object dictionary.
  612. self._XCKVPrint(file, 3, 'isa', self.__class__.__name__)
  613. # The remaining elements of an object dictionary are sorted alphabetically.
  614. for property, value in sorted(self._properties.iteritems()):
  615. self._XCKVPrint(file, 3, property, value)
  616. # End the object.
  617. self._XCPrint(file, end_tabs, '};\n')
  618. def UpdateProperties(self, properties, do_copy=False):
  619. """Merge the supplied properties into the _properties dictionary.
  620. The input properties must adhere to the class schema or a KeyError or
  621. TypeError exception will be raised. If adding an object of an XCObject
  622. subclass and the schema indicates a strong relationship, the object's
  623. parent will be set to this object.
  624. If do_copy is True, then lists, dicts, strong-owned XCObjects, and
  625. strong-owned XCObjects in lists will be copied instead of having their
  626. references added.
  627. """
  628. if properties is None:
  629. return
  630. for property, value in properties.iteritems():
  631. # Make sure the property is in the schema.
  632. if not property in self._schema:
  633. raise KeyError, property + ' not in ' + self.__class__.__name__
  634. # Make sure the property conforms to the schema.
  635. (is_list, property_type, is_strong) = self._schema[property][0:3]
  636. if is_list:
  637. if value.__class__ != list:
  638. raise TypeError, \
  639. property + ' of ' + self.__class__.__name__ + \
  640. ' must be list, not ' + value.__class__.__name__
  641. for item in value:
  642. if not isinstance(item, property_type) and \
  643. not (item.__class__ == unicode and property_type == str):
  644. # Accept unicode where str is specified. str is treated as
  645. # UTF-8-encoded.
  646. raise TypeError, \
  647. 'item of ' + property + ' of ' + self.__class__.__name__ + \
  648. ' must be ' + property_type.__name__ + ', not ' + \
  649. item.__class__.__name__
  650. elif not isinstance(value, property_type) and \
  651. not (value.__class__ == unicode and property_type == str):
  652. # Accept unicode where str is specified. str is treated as
  653. # UTF-8-encoded.
  654. raise TypeError, \
  655. property + ' of ' + self.__class__.__name__ + ' must be ' + \
  656. property_type.__name__ + ', not ' + value.__class__.__name__
  657. # Checks passed, perform the assignment.
  658. if do_copy:
  659. if isinstance(value, XCObject):
  660. if is_strong:
  661. self._properties[property] = value.Copy()
  662. else:
  663. self._properties[property] = value
  664. elif isinstance(value, str) or isinstance(value, unicode) or \
  665. isinstance(value, int):
  666. self._properties[property] = value
  667. elif isinstance(value, list):
  668. if is_strong:
  669. # If is_strong is True, each element is an XCObject, so it's safe
  670. # to call Copy.
  671. self._properties[property] = []
  672. for item in value:
  673. self._properties[property].append(item.Copy())
  674. else:
  675. self._properties[property] = value[:]
  676. elif isinstance(value, dict):
  677. self._properties[property] = value.copy()
  678. else:
  679. raise TypeError, "Don't know how to copy a " + \
  680. value.__class__.__name__ + ' object for ' + \
  681. property + ' in ' + self.__class__.__name__
  682. else:
  683. self._properties[property] = value
  684. # Set up the child's back-reference to this object. Don't use |value|
  685. # any more because it may not be right if do_copy is true.
  686. if is_strong:
  687. if not is_list:
  688. self._properties[property].parent = self
  689. else:
  690. for item in self._properties[property]:
  691. item.parent = self
  692. def HasProperty(self, key):
  693. return key in self._properties
  694. def GetProperty(self, key):
  695. return self._properties[key]
  696. def SetProperty(self, key, value):
  697. self.UpdateProperties({key: value})
  698. def DelProperty(self, key):
  699. if key in self._properties:
  700. del self._properties[key]
  701. def AppendProperty(self, key, value):
  702. # TODO(mark): Support ExtendProperty too (and make this call that)?
  703. # Schema validation.
  704. if not key in self._schema:
  705. raise KeyError, key + ' not in ' + self.__class__.__name__
  706. (is_list, property_type, is_strong) = self._schema[key][0:3]
  707. if not is_list:
  708. raise TypeError, key + ' of ' + self.__class__.__name__ + ' must be list'
  709. if not isinstance(value, property_type):
  710. raise TypeError, 'item of ' + key + ' of ' + self.__class__.__name__ + \
  711. ' must be ' + property_type.__name__ + ', not ' + \
  712. value.__class__.__name__
  713. # If the property doesn't exist yet, create a new empty list to receive the
  714. # item.
  715. if not key in self._properties:
  716. self._properties[key] = []
  717. # Set up the ownership link.
  718. if is_strong:
  719. value.parent = self
  720. # Store the item.
  721. self._properties[key].append(value)
  722. def VerifyHasRequiredProperties(self):
  723. """Ensure that all properties identified as required by the schema are
  724. set.
  725. """
  726. # TODO(mark): A stronger verification mechanism is needed. Some
  727. # subclasses need to perform validation beyond what the schema can enforce.
  728. for property, attributes in self._schema.iteritems():
  729. (is_list, property_type, is_strong, is_required) = attributes[0:4]
  730. if is_required and not property in self._properties:
  731. raise KeyError, self.__class__.__name__ + ' requires ' + property
  732. def _SetDefaultsFromSchema(self):
  733. """Assign object default values according to the schema. This will not
  734. overwrite properties that have already been set."""
  735. defaults = {}
  736. for property, attributes in self._schema.iteritems():
  737. (is_list, property_type, is_strong, is_required) = attributes[0:4]
  738. if is_required and len(attributes) >= 5 and \
  739. not property in self._properties:
  740. default = attributes[4]
  741. defaults[property] = default
  742. if len(defaults) > 0:
  743. # Use do_copy=True so that each new object gets its own copy of strong
  744. # objects, lists, and dicts.
  745. self.UpdateProperties(defaults, do_copy=True)
  746. class XCHierarchicalElement(XCObject):
  747. """Abstract base for PBXGroup and PBXFileReference. Not represented in a
  748. project file."""
  749. # TODO(mark): Do name and path belong here? Probably so.
  750. # If path is set and name is not, name may have a default value. Name will
  751. # be set to the basename of path, if the basename of path is different from
  752. # the full value of path. If path is already just a leaf name, name will
  753. # not be set.
  754. _schema = XCObject._schema.copy()
  755. _schema.update({
  756. 'comments': [0, str, 0, 0],
  757. 'fileEncoding': [0, str, 0, 0],
  758. 'includeInIndex': [0, int, 0, 0],
  759. 'indentWidth': [0, int, 0, 0],
  760. 'lineEnding': [0, int, 0, 0],
  761. 'sourceTree': [0, str, 0, 1, '<group>'],
  762. 'tabWidth': [0, int, 0, 0],
  763. 'usesTabs': [0, int, 0, 0],
  764. 'wrapsLines': [0, int, 0, 0],
  765. })
  766. def __init__(self, properties=None, id=None, parent=None):
  767. # super
  768. XCObject.__init__(self, properties, id, parent)
  769. if 'path' in self._properties and not 'name' in self._properties:
  770. path = self._properties['path']
  771. name = posixpath.basename(path)
  772. if name != '' and path != name:
  773. self.SetProperty('name', name)
  774. if 'path' in self._properties and \
  775. (not 'sourceTree' in self._properties or \
  776. self._properties['sourceTree'] == '<group>'):
  777. # If the pathname begins with an Xcode variable like "$(SDKROOT)/", take
  778. # the variable out and make the path be relative to that variable by
  779. # assigning the variable name as the sourceTree.
  780. (source_tree, path) = SourceTreeAndPathFromPath(self._properties['path'])
  781. if source_tree != None:
  782. self._properties['sourceTree'] = source_tree
  783. if path != None:
  784. self._properties['path'] = path
  785. if source_tree != None and path is None and \
  786. not 'name' in self._properties:
  787. # The path was of the form "$(SDKROOT)" with no path following it.
  788. # This object is now relative to that variable, so it has no path
  789. # attribute of its own. It does, however, keep a name.
  790. del self._properties['path']
  791. self._properties['name'] = source_tree
  792. def Name(self):
  793. if 'name' in self._properties:
  794. return self._properties['name']
  795. elif 'path' in self._properties:
  796. return self._properties['path']
  797. else:
  798. # This happens in the case of the root PBXGroup.
  799. return None
  800. def Hashables(self):
  801. """Custom hashables for XCHierarchicalElements.
  802. XCHierarchicalElements are special. Generally, their hashes shouldn't
  803. change if the paths don't change. The normal XCObject implementation of
  804. Hashables adds a hashable for each object, which means that if
  805. the hierarchical structure changes (possibly due to changes caused when
  806. TakeOverOnlyChild runs and encounters slight changes in the hierarchy),
  807. the hashes will change. For example, if a project file initially contains
  808. a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent
  809. a/b. If someone later adds a/f2 to the project file, a/b can no longer be
  810. collapsed, and f1 winds up with parent b and grandparent a. That would
  811. be sufficient to change f1's hash.
  812. To counteract this problem, hashables for all XCHierarchicalElements except
  813. for the main group (which has neither a name nor a path) are taken to be
  814. just the set of path components. Because hashables are inherited from
  815. parents, this provides assurance that a/b/f1 has the same set of hashables
  816. whether its parent is b or a/b.
  817. The main group is a special case. As it is permitted to have no name or
  818. path, it is permitted to use the standard XCObject hash mechanism. This
  819. is not considered a problem because there can be only one main group.
  820. """
  821. if self == self.PBXProjectAncestor()._properties['mainGroup']:
  822. # super
  823. return XCObject.Hashables(self)
  824. hashables = []
  825. # Put the name in first, ensuring that if TakeOverOnlyChild collapses
  826. # children into a top-level group like "Source", the name always goes
  827. # into the list of hashables without interfering with path components.
  828. if 'name' in self._properties:
  829. # Make it less likely for people to manipulate hashes by following the
  830. # pattern of always pushing an object type value onto the list first.
  831. hashables.append(self.__class__.__name__ + '.name')
  832. hashables.append(self._properties['name'])
  833. # NOTE: This still has the problem that if an absolute path is encountered,
  834. # including paths with a sourceTree, they'll still inherit their parents'
  835. # hashables, even though the paths aren't relative to their parents. This
  836. # is not expected to be much of a problem in practice.
  837. path = self.PathFromSourceTreeAndPath()
  838. if path != None:
  839. components = path.split(posixpath.sep)
  840. for component in components:
  841. hashables.append(self.__class__.__name__ + '.path')
  842. hashables.append(component)
  843. hashables.extend(self._hashables)
  844. return hashables
  845. def Compare(self, other):
  846. # Allow comparison of these types. PBXGroup has the highest sort rank;
  847. # PBXVariantGroup is treated as equal to PBXFileReference.
  848. valid_class_types = {
  849. PBXFileReference: 'file',
  850. PBXGroup: 'group',
  851. PBXVariantGroup: 'file',
  852. }
  853. self_type = valid_class_types[self.__class__]
  854. other_type = valid_class_types[other.__class__]
  855. if self_type == other_type:
  856. # If the two objects are of the same sort rank, compare their names.
  857. return cmp(self.Name(), other.Name())
  858. # Otherwise, sort groups before everything else.
  859. if self_type == 'group':
  860. return -1
  861. return 1
  862. def CompareRootGroup(self, other):
  863. # This function should be used only to compare direct children of the
  864. # containing PBXProject's mainGroup. These groups should appear in the
  865. # listed order.
  866. # TODO(mark): "Build" is used by gyp.generator.xcode, perhaps the
  867. # generator should have a way of influencing this list rather than having
  868. # to hardcode for the generator here.
  869. order = ['Source', 'Intermediates', 'Projects', 'Frameworks', 'Products',
  870. 'Build']
  871. # If the groups aren't in the listed order, do a name comparison.
  872. # Otherwise, groups in the listed order should come before those that
  873. # aren't.
  874. self_name = self.Name()
  875. other_name = other.Name()
  876. self_in = isinstance(self, PBXGroup) and self_name in order
  877. other_in = isinstance(self, PBXGroup) and other_name in order
  878. if not self_in and not other_in:
  879. return self.Compare(other)
  880. if self_name in order and not other_name in order:
  881. return -1
  882. if other_name in order and not self_name in order:
  883. return 1
  884. # If both groups are in the listed order, go by the defined order.
  885. self_index = order.index(self_name)
  886. other_index = order.index(other_name)
  887. if self_index < other_index:
  888. return -1
  889. if self_index > other_index:
  890. return 1
  891. return 0
  892. def PathFromSourceTreeAndPath(self):
  893. # Turn the object's sourceTree and path properties into a single flat
  894. # string of a form comparable to the path parameter. If there's a
  895. # sourceTree property other than "<group>", wrap it in $(...) for the
  896. # comparison.
  897. components = []
  898. if self._properties['sourceTree'] != '<group>':
  899. components.append('$(' + self._properties['sourceTree'] + ')')
  900. if 'path' in self._properties:
  901. components.append(self._properties['path'])
  902. if len(components) > 0:
  903. return posixpath.join(*components)
  904. return None
  905. def FullPath(self):
  906. # Returns a full path to self relative to the project file, or relative
  907. # to some other source tree. Start with self, and walk up the chain of
  908. # parents prepending their paths, if any, until no more parents are
  909. # available (project-relative path) or until a path relative to some
  910. # source tree is found.
  911. xche = self
  912. path = None
  913. while isinstance(xche, XCHierarchicalElement) and \
  914. (path is None or \
  915. (not path.startswith('/') and not path.startswith('$'))):
  916. this_path = xche.PathFromSourceTreeAndPath()
  917. if this_path != None and path != None:
  918. path = posixpath.join(this_path, path)
  919. elif this_path != None:
  920. path = this_path
  921. xche = xche.parent
  922. return path
  923. class PBXGroup(XCHierarchicalElement):
  924. """
  925. Attributes:
  926. _children_by_path: Maps pathnames of children of this PBXGroup to the
  927. actual child XCHierarchicalElement objects.
  928. _variant_children_by_name_and_path: Maps (name, path) tuples of
  929. PBXVariantGroup children to the actual child PBXVariantGroup objects.
  930. """
  931. _schema = XCHierarchicalElement._schema.copy()
  932. _schema.update({
  933. 'children': [1, XCHierarchicalElement, 1, 1, []],
  934. 'name': [0, str, 0, 0],
  935. 'path': [0, str, 0, 0],
  936. })
  937. def __init__(self, properties=None, id=None, parent=None):
  938. # super
  939. XCHierarchicalElement.__init__(self, properties, id, parent)
  940. self._children_by_path = {}
  941. self._variant_children_by_name_and_path = {}
  942. for child in self._properties.get('children', []):
  943. self._AddChildToDicts(child)
  944. def _AddChildToDicts(self, child):
  945. # Sets up this PBXGroup object's dicts to reference the child properly.
  946. child_path = child.PathFromSourceTreeAndPath()
  947. if child_path:
  948. if child_path in self._children_by_path:
  949. raise ValueError, 'Found multiple children with path ' + child_path
  950. self._children_by_path[child_path] = child
  951. if isinstance(child, PBXVariantGroup):
  952. child_name = child._properties.get('name', None)
  953. key = (child_name, child_path)
  954. if key in self._variant_children_by_name_and_path:
  955. raise ValueError, 'Found multiple PBXVariantGroup children with ' + \
  956. 'name ' + str(child_name) + ' and path ' + \
  957. str(child_path)
  958. self._variant_children_by_name_and_path[key] = child
  959. def AppendChild(self, child):
  960. # Callers should use this instead of calling
  961. # AppendProperty('children', child) directly because this function
  962. # maintains the group's dicts.
  963. self.AppendProperty('children', child)
  964. self._AddChildToDicts(child)
  965. def GetChildByName(self, name):
  966. # This is not currently optimized with a dict as GetChildByPath is because
  967. # it has few callers. Most callers probably want GetChildByPath. This
  968. # function is only useful to get children that have names but no paths,
  969. # which is rare. The children of the main group ("Source", "Products",
  970. # etc.) is pretty much the only case where this likely to come up.
  971. #
  972. # TODO(mark): Maybe this should raise an error if more than one child is
  973. # present with the same name.
  974. if not 'children' in self._properties:
  975. return None
  976. for child in self._properties['children']:
  977. if child.Name() == name:
  978. return child
  979. return None
  980. def GetChildByPath(self, path):
  981. if not path:
  982. return None
  983. if path in self._children_by_path:
  984. return self._children_by_path[path]
  985. return None
  986. def GetChildByRemoteObject(self, remote_object):
  987. # This method is a little bit esoteric. Given a remote_object, which
  988. # should be a PBXFileReference in another project file, this method will
  989. # return this group's PBXReferenceProxy object serving as a local proxy
  990. # for the remote PBXFileReference.
  991. #
  992. # This function might benefit from a dict optimization as GetChildByPath
  993. # for some workloads, but profiling shows that it's not currently a
  994. # problem.
  995. if not 'children' in self._properties:
  996. return None
  997. for child in self._properties['children']:
  998. if not isinstance(child, PBXReferenceProxy):
  999. continue
  1000. container_proxy = child._properties['remoteRef']
  1001. if container_proxy._properties['remoteGlobalIDString'] == remote_object:
  1002. return child
  1003. return None
  1004. def AddOrGetFileByPath(self, path, hierarchical):
  1005. """Returns an existing or new file reference corresponding to path.
  1006. If hierarchical is True, this method will create or use the necessary
  1007. hierarchical group structure corresponding to path. Otherwise, it will
  1008. look in and create an item in the current group only.
  1009. If an existing matching reference is found, it is returned, otherwise, a
  1010. new one will be created, added to the correct group, and returned.
  1011. If path identifies a directory by virtue of carrying a trailing slash,
  1012. this method returns a PBXFileReference of "folder" type. If path
  1013. identifies a variant, by virtue of it identifying a file inside a directory
  1014. with an ".lproj" extension, this method returns a PBXVariantGroup
  1015. containing the variant named by path, and possibly other variants. For
  1016. all other paths, a "normal" PBXFileReference will be returned.
  1017. """
  1018. # Adding or getting a directory? Directories end with a trailing slash.
  1019. is_dir = False
  1020. if path.endswith('/'):
  1021. is_dir = True
  1022. path = posixpath.normpath(path)
  1023. if is_dir:
  1024. path = path + '/'
  1025. # Adding or getting a variant? Variants are files inside directories
  1026. # with an ".lproj" extension. Xcode uses variants for localization. For
  1027. # a variant path/to/Language.lproj/MainMenu.nib, put a variant group named
  1028. # MainMenu.nib inside path/to, and give it a variant named Language. In
  1029. # this example, grandparent would be set to path/to and parent_root would
  1030. # be set to Language.
  1031. variant_name = None
  1032. parent = posixpath.dirname(path)
  1033. grandparent = posixpath.dirname(parent)
  1034. parent_basename = posixpath.basename(parent)
  1035. (parent_root, parent_ext) = posixpath.splitext(parent_basename)
  1036. if parent_ext == '.lproj':
  1037. variant_name = parent_root
  1038. if grandparent == '':
  1039. grandparent = None
  1040. # Putting a directory inside a variant group is not currently supported.
  1041. assert not is_dir or variant_name is None
  1042. path_split = path.split(posixpath.sep)
  1043. if len(path_split) == 1 or \
  1044. ((is_dir or variant_name != None) and len(path_split) == 2) or \
  1045. not hierarchical:
  1046. # The PBXFileReference or PBXVariantGroup will be added to or gotten from
  1047. # this PBXGroup, no recursion necessary.
  1048. if variant_name is None:
  1049. # Add or get a PBXFileReference.
  1050. file_ref = self.GetChildByPath(path)
  1051. if file_ref != None:
  1052. assert file_ref.__class__ == PBXFileReference
  1053. else:
  1054. file_ref = PBXFileReference({'path': path})
  1055. self.AppendChild(file_ref)
  1056. else:
  1057. # Add or get a PBXVariantGroup. The variant group name is the same
  1058. # as the basename (MainMenu.nib in the example above). grandparent
  1059. # specifies the path to the variant group itself, and path_split[-2:]
  1060. # is the path of the specific variant relative to its group.
  1061. variant_group_name = posixpath.basename(path)
  1062. variant_group_ref = self.AddOrGetVariantGroupByNameAndPath(
  1063. variant_group_name, grandparent)
  1064. variant_path = posixpath.sep.join(path_split[-2:])
  1065. variant_ref = variant_group_ref.GetChildByPath(variant_path)
  1066. if variant_ref != None:
  1067. assert variant_ref.__class__ == PBXFileReference
  1068. else:
  1069. variant_ref = PBXFileReference({'name': variant_name,
  1070. 'path': variant_path})
  1071. variant_group_ref.AppendChild(variant_ref)
  1072. # The caller is interested in the variant group, not the specific
  1073. # variant file.
  1074. file_ref = variant_group_ref
  1075. return file_ref
  1076. else:
  1077. # Hierarchical recursion. Add or get a PBXGroup corresponding to the
  1078. # outermost path component, and then recurse into it, chopping off that
  1079. # path component.
  1080. next_dir = path_split[0]
  1081. group_ref = self.GetChildByPath(next_dir)
  1082. if group_ref != None:
  1083. assert group_ref.__class__ == PBXGroup
  1084. else:
  1085. group_ref = PBXGroup({'path': next_dir})
  1086. self.AppendChild(group_ref)
  1087. return group_ref.AddOrGetFileByPath(posixpath.sep.join(path_split[1:]),
  1088. hierarchical)
  1089. def AddOrGetVariantGroupByNameAndPath(self, name, path):
  1090. """Returns an existing or new PBXVariantGroup for name and path.
  1091. If a PBXVariantGroup identified by the name and path arguments is already
  1092. present as a child of this object, it is returned. Otherwise, a new
  1093. PBXVariantGroup with the correct properties is created, added as a child,
  1094. and returned.
  1095. This method will generally be called by AddOrGetFileByPath, which knows
  1096. when to create a variant group based on the structure of the pathnames
  1097. passed to it.
  1098. """
  1099. key = (name, path)
  1100. if key in self._variant_children_by_name_and_path:
  1101. variant_group_ref = self._variant_children_by_name_and_path[key]
  1102. assert variant_group_ref.__class__ == PBXVariantGroup
  1103. return variant_group_ref
  1104. variant_group_properties = {'name': name}
  1105. if path != None:
  1106. variant_group_properties['path'] = path
  1107. variant_group_ref = PBXVariantGroup(variant_group_properties)
  1108. self.AppendChild(variant_group_ref)
  1109. return variant_group_ref
  1110. def TakeOverOnlyChild(self, recurse=False):
  1111. """If this PBXGroup has only one child and it's also a PBXGroup, take
  1112. it over by making all of its children this object's children.
  1113. This function will continue to take over only children when those children
  1114. are groups. If there are three PBXGroups representing a, b, and c, with
  1115. c inside b and b inside a, and a and b have no other children, this will
  1116. result in a taking over both b and c, forming a PBXGroup for a/b/c.
  1117. If recurse is True, this function will recurse into children and ask them
  1118. to collapse themselves by taking over only children as well. Assuming
  1119. an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
  1120. (d1, d2, and f are files, the rest are groups), recursion will result in
  1121. a group for a/b/c containing a group for d3/e.
  1122. """
  1123. # At this stage, check that child class types are PBXGroup exactly,
  1124. # instead of using isinstance. The only subclass of PBXGroup,
  1125. # PBXVariantGroup, should not participate in reparenting in the same way:
  1126. # reparenting by merging different object types would be wrong.
  1127. while len(self._properties['children']) == 1 and \
  1128. self._properties['children'][0].__class__ == PBXGroup:
  1129. # Loop to take over the innermost only-child group possible.
  1130. child = self._properties['children'][0]
  1131. # Assume the child's properties, including its children. Save a copy
  1132. # of this object's old properties, because they'll still be needed.
  1133. # This object retains its existing id and parent attributes.
  1134. old_properties = self._properties
  1135. self._properties = child._properties
  1136. self._children_by_path = child._children_by_path
  1137. if not 'sourceTree' in self._properties or \
  1138. self._properties['sourceTree'] == '<group>':
  1139. # The child was relative to its parent. Fix up the path. Note that
  1140. # children with a sourceTree other than "<group>" are not relative to
  1141. # their parents, so no path fix-up is needed in that case.
  1142. if 'path' in old_properties:
  1143. if 'path' in self._properties:
  1144. # Both the original parent and child have paths set.
  1145. self._properties['path'] = posixpath.join(old_properties['path'],
  1146. self._properties['path'])
  1147. else:
  1148. # Only the original parent has a path, use it.
  1149. self._properties['path'] = old_properties['path']
  1150. if 'sourceTree' in old_properties:
  1151. # The original parent had a sourceTree set, use it.
  1152. self._properties['sourceTree'] = old_properties['sourceTree']
  1153. # If the original parent had a name set, keep using it. If the original
  1154. # parent didn't have a name but the child did, let the child's name
  1155. # live on. If the name attribute seems unnecessary now, get rid of it.
  1156. if 'name' in old_properties and old_properties['name'] != None and \
  1157. old_properties['name'] != self.Name():
  1158. self._properties['name'] = old_properties['name']
  1159. if 'name' in self._properties and 'path' in self._properties and \
  1160. self._properties['name'] == self._properties['path']:
  1161. del self._properties['name']
  1162. # Notify all children of their new parent.
  1163. for child in self._properties['children']:
  1164. child.parent = self
  1165. # If asked to recurse, recurse.
  1166. if recurse:
  1167. for child in self._properties['children']:
  1168. if child.__class__ == PBXGroup:
  1169. child.TakeOverOnlyChild(recurse)
  1170. def SortGroup(self):
  1171. self._properties['children'] = \
  1172. sorted(self._properties['children'], cmp=lambda x,y: x.Compare(y))
  1173. # Recurse.
  1174. for child in self._properties['children']:
  1175. if isinstance(child, PBXGroup):
  1176. child.SortGroup()
  1177. class XCFileLikeElement(XCHierarchicalElement):
  1178. # Abstract base for objects that can be used as the fileRef property of
  1179. # PBXBuildFile.
  1180. def PathHashables(self):
  1181. # A PBXBuildFile that refers to this object will call this method to
  1182. # obtain additional hashables specific to this XCFileLikeElement. Don't
  1183. # just use this object's hashables, they're not specific and unique enough
  1184. # on their own (without access to the parent hashables.) Instead, provide
  1185. # hashables that identify this object by path by getting its hashables as
  1186. # well as the hashables of ancestor XCHierarchicalElement objects.
  1187. hashables = []
  1188. xche = self
  1189. while xche != None and isinstance(xche, XCHierarchicalElement):
  1190. xche_hashables = xche.Hashables()
  1191. for index in xrange(0, len(xche_hashables)):
  1192. hashables.insert(index, xche_hashables[index])
  1193. xche = xche.parent
  1194. return hashables
  1195. class XCContainerPortal(XCObject):
  1196. # Abstract base for objects that can be used as the containerPortal property
  1197. # of PBXContainerItemProxy.
  1198. pass
  1199. class XCRemoteObject(XCObject):
  1200. # Abstract base for objects that can be used as the remoteGlobalIDString
  1201. # property of PBXContainerItemProxy.
  1202. pass
  1203. class PBXFileReference(XCFileLikeElement, XCContainerPortal, XCRemoteObject):
  1204. _schema = XCFileLikeElement._schema.copy()
  1205. _schema.update({
  1206. 'explicitFileType': [0, str, 0, 0],
  1207. 'lastKnownFileType': [0, str, 0, 0],
  1208. 'name': [0, str, 0, 0],
  1209. 'path': [0, str, 0, 1],
  1210. })
  1211. # Weird output rules for PBXFileReference.
  1212. _should_print_single_line = True
  1213. # super
  1214. _encode_transforms = XCFileLikeElement._alternate_encode_transforms
  1215. def __init__(self, properties=None, id=None, parent=None):
  1216. # super
  1217. XCFileLikeElement.__init__(self, properties, id, parent)
  1218. if 'path' in self._properties and self._properties['path'].endswith('/'):
  1219. self._properties['path'] = self._properties['path'][:-1]
  1220. is_dir = True
  1221. else:
  1222. is_dir = False
  1223. if 'path' in self._properties and \
  1224. not 'lastKnownFileType' in self._properties and \
  1225. not 'explicitFileType' in self._properties:
  1226. # TODO(mark): This is the replacement for a replacement for a quick hack.
  1227. # It is no longer incredibly sucky, but this list needs to be extended.
  1228. extension_map = {
  1229. 'a': 'archive.ar',
  1230. 'app': 'wrapper.application',
  1231. 'bdic': 'file',
  1232. 'bundle': 'wrapper.cfbundle',
  1233. 'c': 'sourcecode.c.c',
  1234. 'cc': 'sourcecode.cpp.cpp',
  1235. 'cpp': 'sourcecode.cpp.cpp',
  1236. 'css': 'text.css',
  1237. 'cxx': 'sourcecode.cpp.cpp',
  1238. 'dylib': 'compiled.mach-o.dylib',
  1239. 'framework': 'wrapper.framework',
  1240. 'h': 'sourcecode.c.h',
  1241. 'hxx': 'sourcecode.cpp.h',
  1242. 'icns': 'image.icns',
  1243. 'java': 'sourcecode.java',
  1244. 'js': 'sourcecode.javascript',
  1245. 'm': 'sourcecode.c.objc',
  1246. 'mm': 'sourcecode.cpp.objcpp',
  1247. 'nib': 'wrapper.nib',
  1248. 'o': 'compiled.mach-o.objfile',
  1249. 'pdf': 'image.pdf',
  1250. 'pl': 'text.script.perl',
  1251. 'plist': 'text.plist.xml',
  1252. 'pm': 'text.script.perl',
  1253. 'png': 'image.png',
  1254. 'py': 'text.script.python',
  1255. 'r': 'sourcecode.rez',
  1256. 'rez': 'sourcecode.rez',
  1257. 's': 'sourcecode.asm',
  1258. 'strings': 'text.plist.strings',
  1259. 'ttf': 'file',
  1260. 'xcconfig': 'text.xcconfig',
  1261. 'xib': 'file.xib',
  1262. 'y': 'sourcecode.yacc',
  1263. }
  1264. if is_dir:
  1265. file_type = 'folder'
  1266. else:
  1267. basename = posixpath.basename(self._properties['path'])
  1268. (root, ext) = posixpath.splitext(basename)
  1269. # Check the map using a lowercase extension.
  1270. # TODO(mark): Maybe it should try with the original case first and fall
  1271. # back to lowercase, in case there are any instances where case
  1272. # matters. There currently aren't.
  1273. if ext != '':
  1274. ext = ext[1:].lower()
  1275. # TODO(mark): "text" is the default value, but "file" is appropriate
  1276. # for unrecognized files not containing text. Xcode seems to choose
  1277. # based on content.
  1278. file_type = extension_map.get(ext, 'text')
  1279. self._properties['lastKnownFileType'] = file_type
  1280. class PBXVariantGroup(PBXGroup, XCFileLikeElement):
  1281. """PBXVariantGroup is used by Xcode to represent localizations."""
  1282. # No additions to the schema relative to PBXGroup.
  1283. pass
  1284. # PBXReferenceProxy is also an XCFileLikeElement subclass. It is defined below
  1285. # because it uses PBXContainerItemProxy, defined below.
  1286. class XCBuildConfiguration(XCObject):
  1287. _schema = XCObject._schema.copy()
  1288. _schema.update({
  1289. 'baseConfigurationReference': [0, PBXFileReference, 0, 0],
  1290. 'buildSettings': [0, dict, 0, 1, {}],
  1291. 'name': [0, str, 0, 1],
  1292. })
  1293. def HasBuildSetting(self, key):
  1294. return key in self._properties['buildSettings']
  1295. def GetBuildSetting(self, key):
  1296. return self._properties['buildSettings'][key]
  1297. def SetBuildSetting(self, key, value):
  1298. # TODO(mark): If a list, copy?
  1299. self._properties['buildSettings'][key] = value
  1300. def AppendBuildSetting(self, key, value):
  1301. if not key in self._properties['buildSettings']:
  1302. self._properties['buildSettings'][key] = []
  1303. self._properties['buildSettings'][key].append(value)
  1304. def DelBuildSetting(self, key):
  1305. if key in self._properties['buildSettings']:
  1306. del self._properties['buildSettings'][key]
  1307. def SetBaseConfiguration(self, value):
  1308. self._properties['baseConfigurationReference'] = value
  1309. class XCConfigurationList(XCObject):
  1310. # _configs is the default list of configurations.
  1311. _configs = [ XCBuildConfiguration({'name': 'Debug'}),
  1312. XCBuildConfiguration({'name': 'Release'}) ]
  1313. _schema = XCObject._schema.copy()
  1314. _schema.update({
  1315. 'buildConfigurations': [1, XCBuildConfiguration, 1, 1, _configs],
  1316. 'defaultConfigurationIsVisible': [0, int, 0, 1, 1],
  1317. 'defaultConfigurationName': [0, str, 0, 1, 'Release'],
  1318. })
  1319. def Name(self):
  1320. return 'Build configuration list for ' + \
  1321. self.parent.__class__.__name__ + ' "' + self.parent.Name() + '"'
  1322. def ConfigurationNamed(self, name):
  1323. """Convenience accessor to obtain an XCBuildConfiguration by name."""
  1324. for configuration in self._properties['buildConfigurations']:
  1325. if configuration._properties['name'] == name:
  1326. return configuration
  1327. raise KeyError, name
  1328. def DefaultConfiguration(self):
  1329. """Convenience accessor to obtain the default XCBuildConfiguration."""
  1330. return self.ConfigurationNamed(self._properties['defaultConfigurationName'])
  1331. def HasBuildSetting(self, key):
  1332. """Determines the state of a build setting in all XCBuildConfiguration
  1333. child objects.
  1334. If all child objects have key in their build settings, and the value is the
  1335. same in all child objects, returns 1.
  1336. If no child objects have the key in their build settings, returns 0.
  1337. If some, but not all, child objects have the key in their build settings,
  1338. or if any children have different values for the key, returns -1.
  1339. """
  1340. has = None
  1341. value = None
  1342. for configuration in self._properties['buildConfigurations']:
  1343. configuration_has = configuration.HasBuildSetting(key)
  1344. if has is None:
  1345. has = configuration_has
  1346. elif has != configuration_has:
  1347. return -1
  1348. if configuration_has:
  1349. configuration_value = configuration.GetBuildSetting(key)
  1350. if value is None:
  1351. value = configuration_value
  1352. elif value != configuration_value:
  1353. return -1
  1354. if not has:
  1355. return 0
  1356. return 1
  1357. def GetBuildSetting(self, key):
  1358. """Gets the build setting for key.
  1359. All child XCConfiguration objects must have the same value set for the
  1360. setting, or a ValueError will be raised.
  1361. """
  1362. # TODO(mark): This is wrong for build settings that are lists. The list
  1363. # contents should be compared (and a list copy returned?)
  1364. value = None
  1365. for configuration in self._properties['buildConfigurations']:
  1366. configuration_value = configuration.GetBuildSetting(key)
  1367. if value is None:
  1368. value = configuration_value
  1369. else:
  1370. if value != configuration_value:
  1371. raise ValueError, 'Variant values for ' + key
  1372. return value
  1373. def SetBuildSetting(self, key, value):
  1374. """Sets the build setting for key to value in all child
  1375. XCBuildConfiguration objects.
  1376. """
  1377. for configuration in self._properties['buildConfigurations']:
  1378. configuration.SetBuildSetting(key, value)
  1379. def AppendBuildSetting(self, key, value):
  1380. """Appends value to the build setting for key, which is treated as a list,
  1381. in all child XCBuildConfiguration objects.
  1382. """
  1383. for configuration in self._properties['buildConfigurations']:
  1384. configuration.AppendBuildSetting(key, value)
  1385. def DelBuildSetting(self, key):
  1386. """Deletes the build setting key from all child XCBuildConfiguration
  1387. objects.
  1388. """
  1389. for configuration in self._properties['buildConfigurations']:
  1390. configuration.DelBuildSetting(key)
  1391. def SetBaseConfiguration(self, value):
  1392. """Sets the build configuration in all child XCBuildConfiguration objects.
  1393. """
  1394. for configuration in self._properties['buildConfigurations']:
  1395. configuration.SetBaseConfiguration(value)
  1396. class PBXBuildFile(XCObject):
  1397. _schema = XCObject._schema.copy()
  1398. _schema.update({
  1399. 'fileRef': [0, XCFileLikeElement, 0, 1],
  1400. 'settings': [0, str, 0, 0], # hack, it's a dict
  1401. })
  1402. # Weird output rules for PBXBuildFile.
  1403. _should_print_single_line = True
  1404. _encode_transforms = XCObject._alternate_encode_transforms
  1405. def Name(self):
  1406. # Example: "main.cc in Sources"
  1407. return self._properties['fileRef'].Name() + ' in ' + self.parent.Name()
  1408. def Hashables(self):
  1409. # super
  1410. hashables = XCObject.Hashables(self)
  1411. # It is not sufficient to just rely on Name() to get the
  1412. # XCFileLikeElement's name, because that is not a complete pathname.
  1413. # PathHashables returns hashables unique enough that no two
  1414. # PBXBuildFiles should wind up with the same set of hashables, unless
  1415. # someone adds the same file multiple times to the same target. That
  1416. # would be considered invalid anyway.
  1417. hashables.extend(self._properties['fileRef'].PathHashables())
  1418. return hashables
  1419. class XCBuildPhase(XCObject):
  1420. """Abstract base for build phase classes. Not represented in a project
  1421. file.
  1422. Attributes:
  1423. _files_by_path: A dict mapping each path of a child in the files list by
  1424. path (keys) to the corresponding PBXBuildFile children (values).
  1425. _files_by_xcfilelikeelement: A dict mapping each XCFileLikeElement (keys)
  1426. to the corresponding PBXBuildFile children (values).
  1427. """
  1428. # TODO(mark): Some build phase types, like PBXShellScriptBuildPhase, don't
  1429. # actually have a "files" list. XCBuildPhase should not have "files" but
  1430. # another abstract subclass of it should provide this, and concrete build
  1431. # phase types that do have "files" lists should be derived from that new
  1432. # abstract subclass. XCBuildPhase should only provide buildActionMask and
  1433. # runOnlyForDeploymentPostprocessing, and not files or the various
  1434. # file-related methods and attributes.
  1435. _schema = XCObject._schema.copy()
  1436. _schema.update({
  1437. 'buildActionMask': [0, int, 0, 1, 0x7fffffff],
  1438. 'files': [1, PBXBuildFile, 1, 1, []],
  1439. 'runOnlyForDeploymentPostprocessing': [0, int, 0, 1, 0],
  1440. })
  1441. def __init__(self, properties=None, id=None, parent=None):
  1442. # super
  1443. XCObject.__init__(self, properties, id, parent)
  1444. self._files_by_path = {}
  1445. self._files_by_xcfilelikeelement = {}
  1446. for pbxbuildfile in self._properties.get('files', []):
  1447. self._AddBuildFileToDicts(pbxbuildfile)
  1448. def FileGroup(self, path):
  1449. # Subclasses must override this by returning a two-element tuple. The
  1450. # first item in the tuple should be the PBXGroup to which "path" should be
  1451. # added, either as a child or deeper descendant. The second item should
  1452. # be a boolean indicating whether files should be added into hierarchical
  1453. # groups or one single flat group.
  1454. raise NotImplementedError, \
  1455. self.__class__.__name__ + ' must implement FileGroup'
  1456. def _AddPathToDict(self, pbxbuildfile, path):
  1457. """Adds path to the dict tracking paths belonging to this build phase.
  1458. If the path is already a member of this build phase, raises an exception.
  1459. """
  1460. if path in self._files_by_path:
  1461. raise ValueError, 'Found multiple build files with path ' + path
  1462. self._files_by_path[path] = pbxbuildfile
  1463. def _AddBuildFileToDicts(self, pbxbuildfile, path=None):
  1464. """Maintains the _files_by_path and _files_by_xcfilelikeelement dicts.
  1465. If path is specified, then it is the path that is being added to the
  1466. phase, and pbxbuildfile must contain either a PBXFileReference directly
  1467. referencing that path, or it must contain a PBXVariantGroup that itself
  1468. contains a PBXFileReference referencing the path.
  1469. If path is not specified, either the PBXFileReference's path or the paths
  1470. of all children of the PBXVariantGroup are taken as being added to the
  1471. phase.
  1472. If the path is already present in the phase, raises an exception.
  1473. If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile
  1474. are already present in the phase, referenced by a different PBXBuildFile
  1475. object, raises an exception. This does not raise an exception when
  1476. a PBXFileReference or PBXVariantGroup reappear and are referenced by the
  1477. same PBXBuildFile that has already introduced them, because in the case
  1478. of PBXVariantGroup objects, they may correspond to multiple paths that are
  1479. not all added simultaneously. When this situation occurs, the path needs
  1480. to be added to _files_by_path, but nothing needs to change in
  1481. _files_by_xcfilelikeelement, and the caller should have avoided adding
  1482. the PBXBuildFile if it is already present in the list of children.
  1483. """
  1484. xcfilelikeelement = pbxbuildfile._properties['fileRef']
  1485. paths = []
  1486. if path != None:
  1487. # It's best when the caller provides the path.
  1488. if isinstance(xcfilelikeelement, PBXVariantGroup):
  1489. paths.append(path)
  1490. else:
  1491. # If the caller didn't provide a path, there can be either multiple
  1492. # paths (PBXVariantGroup) or one.
  1493. if isinstance(xcfilelikeelement, PBXVariantGroup):
  1494. for variant in xcfilelikeelement._properties['children']:
  1495. paths.append(variant.FullPath())
  1496. else:
  1497. paths.append(xcfilelikeelement.FullPath())
  1498. # Add the paths first, because if something's going to raise, the
  1499. # messages provided by _AddPathToDict are more useful owing to its
  1500. # having access to a real pathname and not just an object's Name().
  1501. for a_path in paths:
  1502. self._AddPathToDict(pbxbuildfile, a_path)
  1503. # If another PBXBuildFile references this XCFileLikeElement, there's a
  1504. # problem.
  1505. if xcfilelikeelement in self._files_by_xcfilelikeelement and \
  1506. self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile:
  1507. raise ValueError, 'Found multiple build files for ' + \
  1508. xcfilelikeelement.Name()
  1509. self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile
  1510. def AppendBuildFile(self, pbxbuildfile, path=None):
  1511. # Callers should use this instead of calling
  1512. # AppendProperty('files', pbxbuildfile) directly because this function
  1513. # maintains the object's dicts. Better yet, callers can just call AddFile
  1514. # with a pathname and not worry about building their own PBXBuildFile
  1515. # objects.
  1516. self.AppendProperty('files', pbxbuildfile)
  1517. self._AddBuildFileToDicts(pbxbuildfile, path)
  1518. def AddFile(self, path, settings=None):
  1519. (file_group, hierarchical) = self.FileGroup(path)
  1520. file_ref = file_group.AddOrGetFileByPath(path, hierarchical)
  1521. if file_ref in self._files_by_xcfilelikeelement and \
  1522. isinstance(file_ref, PBXVariantGroup):
  1523. # There's already a PBXBuildFile in this phase corresponding to the
  1524. # PBXVariantGroup. path just provides a new variant that belongs to
  1525. # the group. Add the path to the dict.
  1526. pbxbuildfile = self._files_by_xcfilelikeelement[file_ref]
  1527. self._AddBuildFileToDicts(pbxbuildfile, path)
  1528. else:
  1529. # Add a new PBXBuildFile to get file_ref into the phase.
  1530. if settings is None:
  1531. pbxbuildfile = PBXBuildFile({'fileRef': file_ref})
  1532. else:
  1533. pbxbuildfile = PBXBuildFile({'fileRef': file_ref, 'settings': settings})
  1534. self.AppendBuildFile(pbxbuildfile, path)
  1535. class PBXHeadersBuildPhase(XCBuildPhase):
  1536. # No additions to the schema relative to XCBuildPhase.
  1537. def Name(self):
  1538. return 'Headers'
  1539. def FileGroup(self, path):
  1540. return self.PBXProjectAncestor().RootGroupForPath(path)
  1541. class PBXResourcesBuildPhase(XCBuildPhase):
  1542. # No additions to the schema relative to XCBuildPhase.
  1543. def Name(self):
  1544. return 'Resources'
  1545. def FileGroup(self, path):
  1546. return self.PBXProjectAncestor().RootGroupForPath(path)
  1547. class PBXSourcesBuildPhase(XCBuildPhase):
  1548. # No additions to the schema relative to XCBuildPhase.
  1549. def Name(self):
  1550. return 'Sources'
  1551. def FileGroup(self, path):
  1552. return self.PBXProjectAncestor().RootGroupForPath(path)
  1553. class PBXFrameworksBuildPhase(XCBuildPhase):
  1554. # No additions to the schema relative to XCBuildPhase.
  1555. def Name(self):
  1556. return 'Frameworks'
  1557. def FileGroup(self, path):
  1558. (root, ext) = posixpath.splitext(path)
  1559. if ext != '':
  1560. ext = ext[1:].lower()
  1561. if ext == 'o':
  1562. # .o files are added to Xcode Frameworks phases, but conceptually aren't
  1563. # frameworks, they're more like sources or intermediates. Redirect them
  1564. # to show up in one of those other groups.
  1565. return self.PBXProjectAncestor().RootGroupForPath(path)
  1566. else:
  1567. return (self.PBXProjectAncestor().FrameworksGroup(), False)
  1568. class PBXShellScriptBuildPhase(XCBuildPhase):
  1569. _schema = XCBuildPhase._schema.copy()
  1570. _schema.update({
  1571. 'inputPaths': [1, str, 0, 1, []],
  1572. 'name': [0, str, 0, 0],
  1573. 'outputPaths': [1, str, 0, 1, []],
  1574. 'shellPath': [0, str, 0, 1, '/bin/sh'],
  1575. 'shellScript': [0, str, 0, 1],
  1576. 'showEnvVarsInLog': [0, int, 0, 0],
  1577. })
  1578. def Name(self):
  1579. if 'name' in self._properties:
  1580. return self._properties['name']
  1581. return 'ShellScript'
  1582. class PBXCopyFilesBuildPhase(XCBuildPhase):
  1583. _schema = XCBuildPhase._schema.copy()
  1584. _schema.update({
  1585. 'dstPath': [0, str, 0, 1],
  1586. 'dstSubfolderSpec': [0, int, 0, 1],
  1587. 'name': [0, str, 0, 0],
  1588. })
  1589. # path_tree_re matches "$(DIR)/path" or just "$(DIR)". Match group 1 is
  1590. # "DIR", match group 3 is "path" or None.
  1591. path_tree_re = re.compile('^\\$\\((.*)\\)(/(.*)|)$')
  1592. # path_tree_to_subfolder maps names of Xcode variables to the associated
  1593. # dstSubfolderSpec property value used in a PBXCopyFilesBuildPhase object.
  1594. path_tree_to_subfolder = {
  1595. 'BUILT_PRODUCTS_DIR': 16, # Products Directory
  1596. # Other types that can be chosen via the Xcode UI.
  1597. # TODO(mark): Map Xcode variable names to these.
  1598. # : 1, # Wrapper
  1599. # : 6, # Executables: 6
  1600. # : 7, # Resources
  1601. # : 15, # Java Resources
  1602. # : 10, # Frameworks
  1603. # : 11, # Shared Frameworks
  1604. # : 12, # Shared Support
  1605. # : 13, # PlugIns
  1606. }
  1607. def Name(self):
  1608. if 'name' in self._properties:
  1609. return self._properties['name']
  1610. return 'CopyFiles'
  1611. def FileGroup(self, path):
  1612. return self.PBXProjectAncestor().RootGroupForPath(path)
  1613. def SetDestination(self, path):
  1614. """Set the dstSubfolderSpec and dstPath properties from path.
  1615. path may be specified in the same notation used for XCHierarchicalElements,
  1616. specifically, "$(DIR)/path".
  1617. """
  1618. path_tree_match = self.path_tree_re.search(path)
  1619. if path_tree_match:
  1620. # Everything else needs to be relative to an Xcode variable.
  1621. path_tree = path_tree_match.group(1)
  1622. relative_path = path_tree_match.group(3)
  1623. if path_tree in self.path_tree_to_subfolder:
  1624. subfolder = self.path_tree_to_subfolder[path_tree]
  1625. if relative_path is None:
  1626. relative_path = ''
  1627. else:
  1628. # The path starts with an unrecognized Xcode variable
  1629. # name like $(SRCROOT). Xcode will still handle this
  1630. # as an "absolute path" that starts with the variable.
  1631. subfolder = 0
  1632. relative_path = path
  1633. elif path.startswith('/'):
  1634. # Special case. Absolute paths are in dstSubfolderSpec 0.
  1635. subfolder = 0
  1636. relative_path = path[1:]
  1637. else:
  1638. raise ValueError, 'Can\'t use path %s in a %s' % \
  1639. (path, self.__class__.__name__)
  1640. self._properties['dstPath'] = relative_path
  1641. self._properties['dstSubfolderSpec'] = subfolder
  1642. class PBXBuildRule(XCObject):
  1643. _schema = XCObject._schema.copy()
  1644. _schema.update({
  1645. 'compilerSpec': [0, str, 0, 1],
  1646. 'filePatterns': [0, str, 0, 0],
  1647. 'fileType': [0, str, 0, 1],
  1648. 'isEditable': [0, int, 0, 1, 1],
  1649. 'outputFiles': [1, str, 0, 1, []],
  1650. 'script': [0, str, 0, 0],
  1651. })
  1652. def Name(self):
  1653. # Not very inspired, but it's what Xcode uses.
  1654. return self.__class__.__name__
  1655. def Hashables(self):
  1656. # super
  1657. hashables = XCObject.Hashables(self)
  1658. # Use the hashables of the weak objects that this object refers to.
  1659. hashables.append(self._properties['fileType'])
  1660. if 'filePatterns' in self._properties:
  1661. hashables.append(self._properties['filePatterns'])
  1662. return hashables
  1663. class PBXContainerItemProxy(XCObject):
  1664. # When referencing an item in this project file, containerPortal is the
  1665. # PBXProject root object of this project file. When referencing an item in
  1666. # another project file, containerPortal is a PBXFileReference identifying
  1667. # the other project file.
  1668. #
  1669. # When serving as a proxy to an XCTarget (in this project file or another),
  1670. # proxyType is 1. When serving as a proxy to a PBXFileReference (in another
  1671. # project file), proxyType is 2. Type 2 is used for references to the
  1672. # producs of the other project file's targets.
  1673. #
  1674. # Xcode is weird about remoteGlobalIDString. Usually, it's printed without
  1675. # a comment, indicating that it's tracked internally simply as a string, but
  1676. # sometimes it's printed with a comment (usually when the object is initially
  1677. # created), indicating that it's tracked as a project file object at least
  1678. # sometimes. This module always tracks it as an object, but contains a hack
  1679. # to prevent it from printing the comment in the project file output. See
  1680. # _XCKVPrint.
  1681. _schema = XCObject._schema.copy()
  1682. _schema.update({
  1683. 'containerPortal': [0, XCContainerPortal, 0, 1],
  1684. 'proxyType': [0, int, 0, 1],
  1685. 'remoteGlobalIDString': [0, XCRemoteObject, 0, 1],
  1686. 'remoteInfo': [0, str, 0, 1],
  1687. })
  1688. def __repr__(self):
  1689. props = self._properties
  1690. name = '%s.gyp:%s' % (props['containerPortal'].Name(), props['remoteInfo'])
  1691. return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self))
  1692. def Name(self):
  1693. # Admittedly not the best name, but it's what Xcode uses.
  1694. return self.__class__.__name__
  1695. def Hashables(self):
  1696. # super
  1697. hashables = XCObject.Hashables(self)
  1698. # Use the hashables of the weak objects that this object refers to.
  1699. hashables.extend(self._properties['containerPortal'].Hashables())
  1700. hashables.extend(self._properties['remoteGlobalIDString'].Hashables())
  1701. return hashables
  1702. class PBXTargetDependency(XCObject):
  1703. # The "target" property accepts an XCTarget object, and obviously not
  1704. # NoneType. But XCTarget is defined below, so it can't be put into the
  1705. # schema yet. The definition of PBXTargetDependency can't be moved below
  1706. # XCTarget because XCTarget's own schema references PBXTargetDependency.
  1707. # Python doesn't deal well with this circular relationship, and doesn't have
  1708. # a real way to do forward declarations. To work around, the type of
  1709. # the "target" property is reset below, after XCTarget is defined.
  1710. #
  1711. # At least one of "name" and "target" is required.
  1712. _schema = XCObject._schema.copy()
  1713. _schema.update({
  1714. 'name': [0, str, 0, 0],
  1715. 'target': [0, None.__class__, 0, 0],
  1716. 'targetProxy': [0, PBXContainerItemProxy, 1, 1],
  1717. })
  1718. def __repr__(self):
  1719. name = self._properties.get('name') or self._properties['target'].Name()
  1720. return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self))
  1721. def Name(self):
  1722. # Admittedly not the best name, but it's what Xcode uses.
  1723. return self.__class__.__name__
  1724. def Hashables(self):
  1725. # super
  1726. hashables = XCObject.Hashables(self)
  1727. # Use the hashables of the weak objects that this object refers to.
  1728. hashables.extend(self._properties['targetProxy'].Hashables())
  1729. return hashables
  1730. class PBXReferenceProxy(XCFileLikeElement):
  1731. _schema = XCFileLikeElement._schema.copy()
  1732. _schema.update({
  1733. 'fileType': [0, str, 0, 1],
  1734. 'path': [0, str, 0, 1],
  1735. 'remoteRef': [0, PBXContainerItemProxy, 1, 1],
  1736. })
  1737. class XCTarget(XCRemoteObject):
  1738. # An XCTarget is really just an XCObject, the XCRemoteObject thing is just
  1739. # to allow PBXProject to be used in the remoteGlobalIDString property of
  1740. # PBXContainerItemProxy.
  1741. #
  1742. # Setting a "name" property at instantiation may also affect "productName",
  1743. # which may in turn affect the "PRODUCT_NAME" build setting in children of
  1744. # "buildConfigurationList". See __init__ below.
  1745. _schema = XCRemoteObject._schema.copy()
  1746. _schema.update({
  1747. 'buildConfigurationList': [0, XCConfigurationList, 1, 1,
  1748. XCConfigurationList()],
  1749. 'buildPhases': [1, XCBuildPhase, 1, 1, []],
  1750. 'dependencies': [1, PBXTargetDependency, 1, 1, []],
  1751. 'name': [0, str, 0, 1],
  1752. 'productName': [0, str, 0, 1],
  1753. })
  1754. def __init__(self, properties=None, id=None, parent=None,
  1755. force_outdir=None, force_prefix=None, force_extension=None):
  1756. # super
  1757. XCRemoteObject.__init__(self, properties, id, parent)
  1758. # Set up additional defaults not expressed in the schema. If a "name"
  1759. # property was supplied, set "productName" if it is not present. Also set
  1760. # the "PRODUCT_NAME" build setting in each configuration, but only if
  1761. # the setting is not present in any build configuration.
  1762. if 'name' in self._properties:
  1763. if not 'productName' in self._properties:
  1764. self.SetProperty('productName', self._properties['name'])
  1765. if 'productName' in self._properties:
  1766. if 'buildConfigurationList' in self._properties:
  1767. configs = self._properties['buildConfigurationList']
  1768. if configs.HasBuildSetting('PRODUCT_NAME') == 0:
  1769. configs.SetBuildSetting('PRODUCT_NAME',
  1770. self._properties['productName'])
  1771. def AddDependency(self, other):
  1772. pbxproject = self.PBXProjectAncestor()
  1773. other_pbxproject = other.PBXProjectAncestor()
  1774. if pbxproject == other_pbxproject:
  1775. # Add a dependency to another target in the same project file.
  1776. container = PBXContainerItemProxy({'containerPortal': pbxproject,
  1777. 'proxyType': 1,
  1778. 'remoteGlobalIDString': other,
  1779. 'remoteInfo': other.Name()})
  1780. dependency = PBXTargetDependency({'target': other,
  1781. 'targetProxy': container})
  1782. self.AppendProperty('dependencies', dependency)
  1783. else:
  1784. # Add a dependency to a target in a different project file.
  1785. other_project_ref = \
  1786. pbxproject.AddOrGetProjectReference(other_pbxproject)[1]
  1787. container = PBXContainerItemProxy({
  1788. 'containerPortal': other_project_ref,
  1789. 'proxyType': 1,
  1790. 'remoteGlobalIDString': other,
  1791. 'remoteInfo': other.Name(),
  1792. })
  1793. dependency = PBXTargetDependency({'name': other.Name(),
  1794. 'targetProxy': container})
  1795. self.AppendProperty('dependencies', dependency)
  1796. # Proxy all of these through to the build configuration list.
  1797. def ConfigurationNamed(self, name):
  1798. return self._properties['buildConfigurationList'].ConfigurationNamed(name)
  1799. def DefaultConfiguration(self):
  1800. return self._properties['buildConfigurationList'].DefaultConfiguration()
  1801. def HasBuildSetting(self, key):
  1802. return self._properties['buildConfigurationList'].HasBuildSetting(key)
  1803. def GetBuildSetting(self, key):
  1804. return self._properties['buildConfigurationList'].GetBuildSetting(key)
  1805. def SetBuildSetting(self, key, value):
  1806. return self._properties['buildConfigurationList'].SetBuildSetting(key, \
  1807. value)
  1808. def AppendBuildSetting(self, key, value):
  1809. return self._properties['buildConfigurationList'].AppendBuildSetting(key, \
  1810. value)
  1811. def DelBuildSetting(self, key):
  1812. return self._properties['buildConfigurationList'].DelBuildSetting(key)
  1813. # Redefine the type of the "target" property. See PBXTargetDependency._schema
  1814. # above.
  1815. PBXTargetDependency._schema['target'][1] = XCTarget
  1816. class PBXNativeTarget(XCTarget):
  1817. # buildPhases is overridden in the schema to be able to set defaults.
  1818. #
  1819. # NOTE: Contrary to most objects, it is advisable to set parent when
  1820. # constructing PBXNativeTarget. A parent of an XCTarget must be a PBXProject
  1821. # object. A parent reference is required for a PBXNativeTarget during
  1822. # construction to be able to set up the target defaults for productReference,
  1823. # because a PBXBuildFile object must be created for the target and it must
  1824. # be added to the PBXProject's mainGroup hierarchy.
  1825. _schema = XCTarget._schema.copy()
  1826. _schema.update({
  1827. 'buildPhases': [1, XCBuildPhase, 1, 1,
  1828. [PBXSourcesBuildPhase(), PBXFrameworksBuildPhase()]],
  1829. 'buildRules': [1, PBXBuildRule, 1, 1, []],
  1830. 'productReference': [0, PBXFileReference, 0, 1],
  1831. 'productType': [0, str, 0, 1],
  1832. })
  1833. # Mapping from Xcode product-types to settings. The settings are:
  1834. # filetype : used for explicitFileType in the project file
  1835. # prefix : the prefix for the file name
  1836. # suffix : the suffix for the filen ame
  1837. _product_filetypes = {
  1838. 'com.apple.product-type.application': ['wrapper.application',
  1839. '', '.app'],
  1840. 'com.apple.product-type.bundle': ['wrapper.cfbundle',
  1841. '', '.bundle'],
  1842. 'com.apple.product-type.framework': ['wrapper.framework',
  1843. '', '.framework'],
  1844. 'com.apple.product-type.library.dynamic': ['compiled.mach-o.dylib',
  1845. 'lib', '.dylib'],
  1846. 'com.apple.product-type.library.static': ['archive.ar',
  1847. 'lib', '.a'],
  1848. 'com.apple.product-type.tool': ['compiled.mach-o.executable',
  1849. '', ''],
  1850. 'com.googlecode.gyp.xcode.bundle': ['compiled.mach-o.dylib',
  1851. '', '.so'],
  1852. }
  1853. def __init__(self, properties=None, id=None, parent=None,
  1854. force_outdir=None, force_prefix=None, force_extension=None):
  1855. # super
  1856. XCTarget.__init__(self, properties, id, parent)
  1857. if 'productName' in self._properties and \
  1858. 'productType' in self._properties and \
  1859. not 'productReference' in self._properties and \
  1860. self._properties['productType'] in self._product_filetypes:
  1861. products_group = None
  1862. pbxproject = self.PBXProjectAncestor()
  1863. if pbxproject != None:
  1864. products_group = pbxproject.ProductsGroup()
  1865. if products_group != None:
  1866. (filetype, prefix, suffix) = \
  1867. self._product_filetypes[self._properties['productType']]
  1868. # Xcode does not have a distinct type for loadable modules that are
  1869. # pure BSD targets (not in a bundle wrapper). GYP allows such modules
  1870. # to be specified by setting a target type to loadable_module without
  1871. # having mac_bundle set. These are mapped to the pseudo-product type
  1872. # com.googlecode.gyp.xcode.bundle.
  1873. #
  1874. # By picking up this special type and converting it to a dynamic
  1875. # library (com.apple.product-type.library.dynamic) with fix-ups,
  1876. # single-file loadable modules can be produced.
  1877. #
  1878. # MACH_O_TYPE is changed to mh_bundle to produce the proper file type
  1879. # (as opposed to mh_dylib). In order for linking to succeed,
  1880. # DYLIB_CURRENT_VERSION and DYLIB_COMPATIBILITY_VERSION must be
  1881. # cleared. They are meaningless for type mh_bundle.
  1882. #
  1883. # Finally, the .so extension is forcibly applied over the default
  1884. # (.dylib), unless another forced extension is already selected.
  1885. # .dylib is plainly wrong, and .bundle is used by loadable_modules in
  1886. # bundle wrappers (com.apple.product-type.bundle). .so seems an odd
  1887. # choice because it's used as the extension on many other systems that
  1888. # don't distinguish between linkable shared libraries and non-linkable
  1889. # loadable modules, but there's precedent: Python loadable modules on
  1890. # Mac OS X use an .so extension.
  1891. if self._properties['productType'] == 'com.googlecode.gyp.xcode.bundle':
  1892. self._properties['productType'] = \
  1893. 'com.apple.product-type.library.dynamic'
  1894. self.SetBuildSetting('MACH_O_TYPE', 'mh_bundle')
  1895. self.SetBuildSetting('DYLIB_CURRENT_VERSION', '')
  1896. self.SetBuildSetting('DYLIB_COMPATIBILITY_VERSION', '')
  1897. if force_extension is None:
  1898. force_extension = suffix[1:]
  1899. if force_extension is not None:
  1900. # If it's a wrapper (bundle), set WRAPPER_EXTENSION.
  1901. if filetype.startswith('wrapper.'):
  1902. self.SetBuildSetting('WRAPPER_EXTENSION', force_extension)
  1903. else:
  1904. # Extension override.
  1905. suffix = '.' + force_extension
  1906. self.SetBuildSetting('EXECUTABLE_EXTENSION', force_extension)
  1907. if filetype.startswith('compiled.mach-o.executable'):
  1908. product_name = self._properties['productName']
  1909. product_name += suffix
  1910. suffix = ''
  1911. self.SetProperty('productName', product_name)
  1912. self.SetBuildSetting('PRODUCT_NAME', product_name)
  1913. # Xcode handles most prefixes based on the target type, however there
  1914. # are exceptions. If a "BSD Dynamic Library" target is added in the
  1915. # Xcode UI, Xcode sets EXECUTABLE_PREFIX. This check duplicates that
  1916. # behavior.
  1917. if force_prefix is not None:
  1918. prefix = force_prefix
  1919. if filetype.startswith('wrapper.'):
  1920. self.SetBuildSetting('WRAPPER_PREFIX', prefix)
  1921. else:
  1922. self.SetBuildSetting('EXECUTABLE_PREFIX', prefix)
  1923. if force_outdir is not None:
  1924. self.SetBuildSetting('TARGET_BUILD_DIR', force_outdir)
  1925. # TODO(tvl): Remove the below hack.
  1926. # http://code.google.com/p/gyp/issues/detail?id=122
  1927. # Some targets include the prefix in the target_name. These targets
  1928. # really should just add a product_name setting that doesn't include
  1929. # the prefix. For example:
  1930. # target_name = 'libevent', product_name = 'event'
  1931. # This check cleans up for them.
  1932. product_name = self._properties['productName']
  1933. prefix_len = len(prefix)
  1934. if prefix_len and (product_name[:prefix_len] == prefix):
  1935. product_name = product_name[prefix_len:]
  1936. self.SetProperty('productName', product_name)
  1937. self.SetBuildSetting('PRODUCT_NAME', product_name)
  1938. ref_props = {
  1939. 'explicitFileType': filetype,
  1940. 'includeInIndex': 0,
  1941. 'path': prefix + product_name + suffix,
  1942. 'sourceTree': 'BUILT_PRODUCTS_DIR',
  1943. }
  1944. file_ref = PBXFileReference(ref_props)
  1945. products_group.AppendChild(file_ref)
  1946. self.SetProperty('productReference', file_ref)
  1947. def GetBuildPhaseByType(self, type):
  1948. if not 'buildPhases' in self._properties:
  1949. return None
  1950. the_phase = None
  1951. for phase in self._properties['buildPhases']:
  1952. if isinstance(phase, type):
  1953. # Some phases may be present in multiples in a well-formed project file,
  1954. # but phases like PBXSourcesBuildPhase may only be present singly, and
  1955. # this function is intended as an aid to GetBuildPhaseByType. Loop
  1956. # over the entire list of phases and assert if more than one of the
  1957. # desired type is found.
  1958. assert the_phase is None
  1959. the_phase = phase
  1960. return the_phase
  1961. def HeadersPhase(self):
  1962. headers_phase = self.GetBuildPhaseByType(PBXHeadersBuildPhase)
  1963. if headers_phase is None:
  1964. headers_phase = PBXHeadersBuildPhase()
  1965. # The headers phase should come before the resources, sources, and
  1966. # frameworks phases, if any.
  1967. insert_at = len(self._properties['buildPhases'])
  1968. for index in xrange(0, len(self._properties['buildPhases'])):
  1969. phase = self._properties['buildPhases'][index]
  1970. if isinstance(phase, PBXResourcesBuildPhase) or \
  1971. isinstance(phase, PBXSourcesBuildPhase) or \
  1972. isinstance(phase, PBXFrameworksBuildPhase):
  1973. insert_at = index
  1974. break
  1975. self._properties['buildPhases'].insert(insert_at, headers_phase)
  1976. headers_phase.parent = self
  1977. return headers_phase
  1978. def ResourcesPhase(self):
  1979. resources_phase = self.GetBuildPhaseByType(PBXResourcesBuildPhase)
  1980. if resources_phase is None:
  1981. resources_phase = PBXResourcesBuildPhase()
  1982. # The resources phase should come before the sources and frameworks
  1983. # phases, if any.
  1984. insert_at = len(self._properties['buildPhases'])
  1985. for index in xrange(0, len(self._properties['buildPhases'])):
  1986. phase = self._properties['buildPhases'][index]
  1987. if isinstance(phase, PBXSourcesBuildPhase) or \
  1988. isinstance(phase, PBXFrameworksBuildPhase):
  1989. insert_at = index
  1990. break
  1991. self._properties['buildPhases'].insert(insert_at, resources_phase)
  1992. resources_phase.parent = self
  1993. return resources_phase
  1994. def SourcesPhase(self):
  1995. sources_phase = self.GetBuildPhaseByType(PBXSourcesBuildPhase)
  1996. if sources_phase is None:
  1997. sources_phase = PBXSourcesBuildPhase()
  1998. self.AppendProperty('buildPhases', sources_phase)
  1999. return sources_phase
  2000. def FrameworksPhase(self):
  2001. frameworks_phase = self.GetBuildPhaseByType(PBXFrameworksBuildPhase)
  2002. if frameworks_phase is None:
  2003. frameworks_phase = PBXFrameworksBuildPhase()
  2004. self.AppendProperty('buildPhases', frameworks_phase)
  2005. return frameworks_phase
  2006. def AddDependency(self, other):
  2007. # super
  2008. XCTarget.AddDependency(self, other)
  2009. static_library_type = 'com.apple.product-type.library.static'
  2010. shared_library_type = 'com.apple.product-type.library.dynamic'
  2011. framework_type = 'com.apple.product-type.framework'
  2012. if isinstance(other, PBXNativeTarget) and \
  2013. 'productType' in self._properties and \
  2014. self._properties['productType'] != static_library_type and \
  2015. 'productType' in other._properties and \
  2016. (other._properties['productType'] == static_library_type or \
  2017. ((other._properties['productType'] == shared_library_type or \
  2018. other._properties['productType'] == framework_type) and \
  2019. ((not other.HasBuildSetting('MACH_O_TYPE')) or
  2020. other.GetBuildSetting('MACH_O_TYPE') != 'mh_bundle'))):
  2021. file_ref = other.GetProperty('productReference')
  2022. pbxproject = self.PBXProjectAncestor()
  2023. other_pbxproject = other.PBXProjectAncestor()
  2024. if pbxproject != other_pbxproject:
  2025. other_project_product_group = \
  2026. pbxproject.AddOrGetProjectReference(other_pbxproject)[0]
  2027. file_ref = other_project_product_group.GetChildByRemoteObject(file_ref)
  2028. self.FrameworksPhase().AppendProperty('files',
  2029. PBXBuildFile({'fileRef': file_ref}))
  2030. class PBXAggregateTarget(XCTarget):
  2031. pass
  2032. class PBXProject(XCContainerPortal):
  2033. # A PBXProject is really just an XCObject, the XCContainerPortal thing is
  2034. # just to allow PBXProject to be used in the containerPortal property of
  2035. # PBXContainerItemProxy.
  2036. """
  2037. Attributes:
  2038. path: "sample.xcodeproj". TODO(mark) Document me!
  2039. _other_pbxprojects: A dictionary, keyed by other PBXProject objects. Each
  2040. value is a reference to the dict in the
  2041. projectReferences list associated with the keyed
  2042. PBXProject.
  2043. """
  2044. _schema = XCContainerPortal._schema.copy()
  2045. _schema.update({
  2046. 'attributes': [0, dict, 0, 0],
  2047. 'buildConfigurationList': [0, XCConfigurationList, 1, 1,
  2048. XCConfigurationList()],
  2049. 'compatibilityVersion': [0, str, 0, 1, 'Xcode 3.2'],
  2050. 'hasScannedForEncodings': [0, int, 0, 1, 1],
  2051. 'mainGroup': [0, PBXGroup, 1, 1, PBXGroup()],
  2052. 'projectDirPath': [0, str, 0, 1, ''],
  2053. 'projectReferences': [1, dict, 0, 0],
  2054. 'projectRoot': [0, str, 0, 1, ''],
  2055. 'targets': [1, XCTarget, 1, 1, []],
  2056. })
  2057. def __init__(self, properties=None, id=None, parent=None, path=None):
  2058. self.path = path
  2059. self._other_pbxprojects = {}
  2060. # super
  2061. return XCContainerPortal.__init__(self, properties, id, parent)
  2062. def Name(self):
  2063. name = self.path
  2064. if name[-10:] == '.xcodeproj':
  2065. name = name[:-10]
  2066. return posixpath.basename(name)
  2067. def Path(self):
  2068. return self.path
  2069. def Comment(self):
  2070. return 'Project object'
  2071. def Children(self):
  2072. # super
  2073. children = XCContainerPortal.Children(self)
  2074. # Add children that the schema doesn't know about. Maybe there's a more
  2075. # elegant way around this, but this is the only case where we need to own
  2076. # objects in a dictionary (that is itself in a list), and three lines for
  2077. # a one-off isn't that big a deal.
  2078. if 'projectReferences' in self._properties:
  2079. for reference in self._properties['projectReferences']:
  2080. children.append(reference['ProductGroup'])
  2081. return children
  2082. def PBXProjectAncestor(self):
  2083. return self
  2084. def _GroupByName(self, name):
  2085. if not 'mainGroup' in self._properties:
  2086. self.SetProperty('mainGroup', PBXGroup())
  2087. main_group = self._properties['mainGroup']
  2088. group = main_group.GetChildByName(name)
  2089. if group is None:
  2090. group = PBXGroup({'name': name})
  2091. main_group.AppendChild(group)
  2092. return group
  2093. # SourceGroup and ProductsGroup are created by default in Xcode's own
  2094. # templates.
  2095. def SourceGroup(self):
  2096. return self._GroupByName('Source')
  2097. def ProductsGroup(self):
  2098. return self._GroupByName('Products')
  2099. # IntermediatesGroup is used to collect source-like files that are generated
  2100. # by rules or script phases and are placed in intermediate directories such
  2101. # as DerivedSources.
  2102. def IntermediatesGroup(self):
  2103. return self._GroupByName('Intermediates')
  2104. # FrameworksGroup and ProjectsGroup are top-level groups used to collect
  2105. # frameworks and projects.
  2106. def FrameworksGroup(self):
  2107. return self._GroupByName('Frameworks')
  2108. def ProjectsGroup(self):
  2109. return self._GroupByName('Projects')
  2110. def RootGroupForPath(self, path):
  2111. """Returns a PBXGroup child of this object to which path should be added.
  2112. This method is intended to choose between SourceGroup and
  2113. IntermediatesGroup on the basis of whether path is present in a source
  2114. directory or an intermediates directory. For the purposes of this
  2115. determination, any path located within a derived file directory such as
  2116. PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates
  2117. directory.
  2118. The returned value is a two-element tuple. The first element is the
  2119. PBXGroup, and the second element specifies whether that group should be
  2120. organized hierarchically (True) or as a single flat list (False).
  2121. """
  2122. # TODO(mark): make this a class variable and bind to self on call?
  2123. # Also, this list is nowhere near exhaustive.
  2124. # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by
  2125. # gyp.generator.xcode. There should probably be some way for that module
  2126. # to push the names in, rather than having to hard-code them here.
  2127. source_tree_groups = {
  2128. 'DERIVED_FILE_DIR': (self.IntermediatesGroup, True),
  2129. 'INTERMEDIATE_DIR': (self.IntermediatesGroup, True),
  2130. 'PROJECT_DERIVED_FILE_DIR': (self.IntermediatesGroup, True),
  2131. 'SHARED_INTERMEDIATE_DIR': (self.IntermediatesGroup, True),
  2132. }
  2133. (source_tree, path) = SourceTreeAndPathFromPath(path)
  2134. if source_tree != None and source_tree in source_tree_groups:
  2135. (group_func, hierarchical) = source_tree_groups[source_tree]
  2136. group = group_func()
  2137. return (group, hierarchical)
  2138. # TODO(mark): make additional choices based on file extension.
  2139. return (self.SourceGroup(), True)
  2140. def AddOrGetFileInRootGroup(self, path):
  2141. """Returns a PBXFileReference corresponding to path in the correct group
  2142. according to RootGroupForPath's heuristics.
  2143. If an existing PBXFileReference for path exists, it will be returned.
  2144. Otherwise, one will be created and returned.
  2145. """
  2146. (group, hierarchical) = self.RootGroupForPath(path)
  2147. return group.AddOrGetFileByPath(path, hierarchical)
  2148. def RootGroupsTakeOverOnlyChildren(self, recurse=False):
  2149. """Calls TakeOverOnlyChild for all groups in the main group."""
  2150. for group in self._properties['mainGroup']._properties['children']:
  2151. if isinstance(group, PBXGroup):
  2152. group.TakeOverOnlyChild(recurse)
  2153. def SortGroups(self):
  2154. # Sort the children of the mainGroup (like "Source" and "Products")
  2155. # according to their defined order.
  2156. self._properties['mainGroup']._properties['children'] = \
  2157. sorted(self._properties['mainGroup']._properties['children'],
  2158. cmp=lambda x,y: x.CompareRootGroup(y))
  2159. # Sort everything else by putting group before files, and going
  2160. # alphabetically by name within sections of groups and files. SortGroup
  2161. # is recursive.
  2162. for group in self._properties['mainGroup']._properties['children']:
  2163. if not isinstance(group, PBXGroup):
  2164. continue
  2165. if group.Name() == 'Products':
  2166. # The Products group is a special case. Instead of sorting
  2167. # alphabetically, sort things in the order of the targets that
  2168. # produce the products. To do this, just build up a new list of
  2169. # products based on the targets.
  2170. products = []
  2171. for target in self._properties['targets']:
  2172. if not isinstance(target, PBXNativeTarget):
  2173. continue
  2174. product = target._properties['productReference']
  2175. # Make sure that the product is already in the products group.
  2176. assert product in group._properties['children']
  2177. products.append(product)
  2178. # Make sure that this process doesn't miss anything that was already
  2179. # in the products group.
  2180. assert len(products) == len(group._properties['children'])
  2181. group._properties['children'] = products
  2182. else:
  2183. group.SortGroup()
  2184. def AddOrGetProjectReference(self, other_pbxproject):
  2185. """Add a reference to another project file (via PBXProject object) to this
  2186. one.
  2187. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in
  2188. this project file that contains a PBXReferenceProxy object for each
  2189. product of each PBXNativeTarget in the other project file. ProjectRef is
  2190. a PBXFileReference to the other project file.
  2191. If this project file already references the other project file, the
  2192. existing ProductGroup and ProjectRef are returned. The ProductGroup will
  2193. still be updated if necessary.
  2194. """
  2195. if not 'projectReferences' in self._properties:
  2196. self._properties['projectReferences'] = []
  2197. product_group = None
  2198. project_ref = None
  2199. if not other_pbxproject in self._other_pbxprojects:
  2200. # This project file isn't yet linked to the other one. Establish the
  2201. # link.
  2202. product_group = PBXGroup({'name': 'Products'})
  2203. # ProductGroup is strong.
  2204. product_group.parent = self
  2205. # There's nothing unique about this PBXGroup, and if left alone, it will
  2206. # wind up with the same set of hashables as all other PBXGroup objects
  2207. # owned by the projectReferences list. Add the hashables of the
  2208. # remote PBXProject that it's related to.
  2209. product_group._hashables.extend(other_pbxproject.Hashables())
  2210. # The other project reports its path as relative to the same directory
  2211. # that this project's path is relative to. The other project's path
  2212. # is not necessarily already relative to this project. Figure out the
  2213. # pathname that this project needs to use to refer to the other one.
  2214. this_path = posixpath.dirname(self.Path())
  2215. projectDirPath = self.GetProperty('projectDirPath')
  2216. if projectDirPath:
  2217. if posixpath.isabs(projectDirPath[0]):
  2218. this_path = projectDirPath
  2219. else:
  2220. this_path = posixpath.join(this_path, projectDirPath)
  2221. other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path)
  2222. # ProjectRef is weak (it's owned by the mainGroup hierarchy).
  2223. project_ref = PBXFileReference({
  2224. 'lastKnownFileType': 'wrapper.pb-project',
  2225. 'path': other_path,
  2226. 'sourceTree': 'SOURCE_ROOT',
  2227. })
  2228. self.ProjectsGroup().AppendChild(project_ref)
  2229. ref_dict = {'ProductGroup': product_group, 'ProjectRef': project_ref}
  2230. self._other_pbxprojects[other_pbxproject] = ref_dict
  2231. self.AppendProperty('projectReferences', ref_dict)
  2232. # Xcode seems to sort this list case-insensitively
  2233. self._properties['projectReferences'] = \
  2234. sorted(self._properties['projectReferences'], cmp=lambda x,y:
  2235. cmp(x['ProjectRef'].Name().lower(),
  2236. y['ProjectRef'].Name().lower()))
  2237. else:
  2238. # The link already exists. Pull out the relevnt data.
  2239. project_ref_dict = self._other_pbxprojects[other_pbxproject]
  2240. product_group = project_ref_dict['ProductGroup']
  2241. project_ref = project_ref_dict['ProjectRef']
  2242. self._SetUpProductReferences(other_pbxproject, product_group, project_ref)
  2243. return [product_group, project_ref]
  2244. def _SetUpProductReferences(self, other_pbxproject, product_group,
  2245. project_ref):
  2246. # TODO(mark): This only adds references to products in other_pbxproject
  2247. # when they don't exist in this pbxproject. Perhaps it should also
  2248. # remove references from this pbxproject that are no longer present in
  2249. # other_pbxproject. Perhaps it should update various properties if they
  2250. # change.
  2251. for target in other_pbxproject._properties['targets']:
  2252. if not isinstance(target, PBXNativeTarget):
  2253. continue
  2254. other_fileref = target._properties['productReference']
  2255. if product_group.GetChildByRemoteObject(other_fileref) is None:
  2256. # Xcode sets remoteInfo to the name of the target and not the name
  2257. # of its product, despite this proxy being a reference to the product.
  2258. container_item = PBXContainerItemProxy({
  2259. 'containerPortal': project_ref,
  2260. 'proxyType': 2,
  2261. 'remoteGlobalIDString': other_fileref,
  2262. 'remoteInfo': target.Name()
  2263. })
  2264. # TODO(mark): Does sourceTree get copied straight over from the other
  2265. # project? Can the other project ever have lastKnownFileType here
  2266. # instead of explicitFileType? (Use it if so?) Can path ever be
  2267. # unset? (I don't think so.) Can other_fileref have name set, and
  2268. # does it impact the PBXReferenceProxy if so? These are the questions
  2269. # that perhaps will be answered one day.
  2270. reference_proxy = PBXReferenceProxy({
  2271. 'fileType': other_fileref._properties['explicitFileType'],
  2272. 'path': other_fileref._properties['path'],
  2273. 'sourceTree': other_fileref._properties['sourceTree'],
  2274. 'remoteRef': container_item,
  2275. })
  2276. product_group.AppendChild(reference_proxy)
  2277. def SortRemoteProductReferences(self):
  2278. # For each remote project file, sort the associated ProductGroup in the
  2279. # same order that the targets are sorted in the remote project file. This
  2280. # is the sort order used by Xcode.
  2281. def CompareProducts(x, y, remote_products):
  2282. # x and y are PBXReferenceProxy objects. Go through their associated
  2283. # PBXContainerItem to get the remote PBXFileReference, which will be
  2284. # present in the remote_products list.
  2285. x_remote = x._properties['remoteRef']._properties['remoteGlobalIDString']
  2286. y_remote = y._properties['remoteRef']._properties['remoteGlobalIDString']
  2287. x_index = remote_products.index(x_remote)
  2288. y_index = remote_products.index(y_remote)
  2289. # Use the order of each remote PBXFileReference in remote_products to
  2290. # determine the sort order.
  2291. return cmp(x_index, y_index)
  2292. for other_pbxproject, ref_dict in self._other_pbxprojects.iteritems():
  2293. # Build up a list of products in the remote project file, ordered the
  2294. # same as the targets that produce them.
  2295. remote_products = []
  2296. for target in other_pbxproject._properties['targets']:
  2297. if not isinstance(target, PBXNativeTarget):
  2298. continue
  2299. remote_products.append(target._properties['productReference'])
  2300. # Sort the PBXReferenceProxy children according to the list of remote
  2301. # products.
  2302. product_group = ref_dict['ProductGroup']
  2303. product_group._properties['children'] = sorted(
  2304. product_group._properties['children'],
  2305. cmp=lambda x, y: CompareProducts(x, y, remote_products))
  2306. class XCProjectFile(XCObject):
  2307. _schema = XCObject._schema.copy()
  2308. _schema.update({
  2309. 'archiveVersion': [0, int, 0, 1, 1],
  2310. 'classes': [0, dict, 0, 1, {}],
  2311. 'objectVersion': [0, int, 0, 1, 45],
  2312. 'rootObject': [0, PBXProject, 1, 1],
  2313. })
  2314. def SetXcodeVersion(self, version):
  2315. version_to_object_version = {
  2316. '2.4': 45,
  2317. '3.0': 45,
  2318. '3.1': 45,
  2319. '3.2': 46,
  2320. }
  2321. if not version in version_to_object_version:
  2322. supported_str = ', '.join(sorted(version_to_object_version.keys()))
  2323. raise Exception(
  2324. 'Unsupported Xcode version %s (supported: %s)' %
  2325. ( version, supported_str ) )
  2326. compatibility_version = 'Xcode %s' % version
  2327. self._properties['rootObject'].SetProperty('compatibilityVersion',
  2328. compatibility_version)
  2329. self.SetProperty('objectVersion', version_to_object_version[version]);
  2330. def ComputeIDs(self, recursive=True, overwrite=True, hash=None):
  2331. # Although XCProjectFile is implemented here as an XCObject, it's not a
  2332. # proper object in the Xcode sense, and it certainly doesn't have its own
  2333. # ID. Pass through an attempt to update IDs to the real root object.
  2334. if recursive:
  2335. self._properties['rootObject'].ComputeIDs(recursive, overwrite, hash)
  2336. def Print(self, file=sys.stdout):
  2337. self.VerifyHasRequiredProperties()
  2338. # Add the special "objects" property, which will be caught and handled
  2339. # separately during printing. This structure allows a fairly standard
  2340. # loop do the normal printing.
  2341. self._properties['objects'] = {}
  2342. self._XCPrint(file, 0, '// !$*UTF8*$!\n')
  2343. if self._should_print_single_line:
  2344. self._XCPrint(file, 0, '{ ')
  2345. else:
  2346. self._XCPrint(file, 0, '{\n')
  2347. for property, value in sorted(self._properties.iteritems(),
  2348. cmp=lambda x, y: cmp(x, y)):
  2349. if property == 'objects':
  2350. self._PrintObjects(file)
  2351. else:
  2352. self._XCKVPrint(file, 1, property, value)
  2353. self._XCPrint(file, 0, '}\n')
  2354. del self._properties['objects']
  2355. def _PrintObjects(self, file):
  2356. if self._should_print_single_line:
  2357. self._XCPrint(file, 0, 'objects = {')
  2358. else:
  2359. self._XCPrint(file, 1, 'objects = {\n')
  2360. objects_by_class = {}
  2361. for object in self.Descendants():
  2362. if object == self:
  2363. continue
  2364. class_name = object.__class__.__name__
  2365. if not class_name in objects_by_class:
  2366. objects_by_class[class_name] = []
  2367. objects_by_class[class_name].append(object)
  2368. for class_name in sorted(objects_by_class):
  2369. self._XCPrint(file, 0, '\n')
  2370. self._XCPrint(file, 0, '/* Begin ' + class_name + ' section */\n')
  2371. for object in sorted(objects_by_class[class_name],
  2372. cmp=lambda x, y: cmp(x.id, y.id)):
  2373. object.Print(file)
  2374. self._XCPrint(file, 0, '/* End ' + class_name + ' section */\n')
  2375. if self._should_print_single_line:
  2376. self._XCPrint(file, 0, '}; ')
  2377. else:
  2378. self._XCPrint(file, 1, '};\n')