1c457178aab9072ef4869795cfe08d31debe6efb6bb33e46d66c68158115ca62e3eda91251fe9569466a4f7228e71b49e2bff2d3122ccd3f3a2b525dfc41d9 132 KB

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