redsnow 0.0.8

Sign up to get free protection for your applications and to get access to all the features.
Files changed (174) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +34 -0
  3. data/.gitmodules +3 -0
  4. data/.travis.yml +20 -0
  5. data/CHANGELOG.md +4 -0
  6. data/Gemfile +4 -0
  7. data/LICENSE +21 -0
  8. data/README.md +62 -0
  9. data/Rakefile +36 -0
  10. data/Vagrantfile +20 -0
  11. data/ext/snowcrash/Makefile +64 -0
  12. data/ext/snowcrash/Vagrantfile +20 -0
  13. data/ext/snowcrash/bin/snowcrash +0 -0
  14. data/ext/snowcrash/common.gypi +163 -0
  15. data/ext/snowcrash/config.gypi +10 -0
  16. data/ext/snowcrash/config.mk +5 -0
  17. data/ext/snowcrash/configure +213 -0
  18. data/ext/snowcrash/provisioning.sh +15 -0
  19. data/ext/snowcrash/snowcrash.gyp +141 -0
  20. data/ext/snowcrash/src/ActionParser.h +503 -0
  21. data/ext/snowcrash/src/AssetParser.h +215 -0
  22. data/ext/snowcrash/src/BlockUtility.h +186 -0
  23. data/ext/snowcrash/src/Blueprint.h +283 -0
  24. data/ext/snowcrash/src/BlueprintParser.h +347 -0
  25. data/ext/snowcrash/src/BlueprintParserCore.h +190 -0
  26. data/ext/snowcrash/src/BlueprintSection.h +140 -0
  27. data/ext/snowcrash/src/BlueprintUtility.h +126 -0
  28. data/ext/snowcrash/src/CBlueprint.cc +600 -0
  29. data/ext/snowcrash/src/CBlueprint.h +354 -0
  30. data/ext/snowcrash/src/CSourceAnnotation.cc +140 -0
  31. data/ext/snowcrash/src/CSourceAnnotation.h +106 -0
  32. data/ext/snowcrash/src/CodeBlockUtility.h +189 -0
  33. data/ext/snowcrash/src/DescriptionSectionUtility.h +156 -0
  34. data/ext/snowcrash/src/HTTP.cc +46 -0
  35. data/ext/snowcrash/src/HTTP.h +105 -0
  36. data/ext/snowcrash/src/HeaderParser.h +289 -0
  37. data/ext/snowcrash/src/ListBlockUtility.h +273 -0
  38. data/ext/snowcrash/src/ListUtility.h +95 -0
  39. data/ext/snowcrash/src/MarkdownBlock.cc +176 -0
  40. data/ext/snowcrash/src/MarkdownBlock.h +93 -0
  41. data/ext/snowcrash/src/MarkdownParser.cc +266 -0
  42. data/ext/snowcrash/src/MarkdownParser.h +88 -0
  43. data/ext/snowcrash/src/ParameterDefinitonParser.h +570 -0
  44. data/ext/snowcrash/src/ParametersParser.h +252 -0
  45. data/ext/snowcrash/src/Parser.cc +71 -0
  46. data/ext/snowcrash/src/Parser.h +29 -0
  47. data/ext/snowcrash/src/ParserCore.cc +120 -0
  48. data/ext/snowcrash/src/ParserCore.h +82 -0
  49. data/ext/snowcrash/src/PayloadParser.h +672 -0
  50. data/ext/snowcrash/src/Platform.h +54 -0
  51. data/ext/snowcrash/src/RegexMatch.h +32 -0
  52. data/ext/snowcrash/src/ResourceGroupParser.h +195 -0
  53. data/ext/snowcrash/src/ResourceParser.h +584 -0
  54. data/ext/snowcrash/src/SectionUtility.h +142 -0
  55. data/ext/snowcrash/src/Serialize.cc +52 -0
  56. data/ext/snowcrash/src/Serialize.h +69 -0
  57. data/ext/snowcrash/src/SerializeJSON.cc +601 -0
  58. data/ext/snowcrash/src/SerializeJSON.h +21 -0
  59. data/ext/snowcrash/src/SerializeYAML.cc +336 -0
  60. data/ext/snowcrash/src/SerializeYAML.h +21 -0
  61. data/ext/snowcrash/src/SourceAnnotation.h +177 -0
  62. data/ext/snowcrash/src/StringUtility.h +109 -0
  63. data/ext/snowcrash/src/SymbolTable.h +83 -0
  64. data/ext/snowcrash/src/UriTemplateParser.cc +195 -0
  65. data/ext/snowcrash/src/UriTemplateParser.h +243 -0
  66. data/ext/snowcrash/src/Version.h +39 -0
  67. data/ext/snowcrash/src/csnowcrash.cc +23 -0
  68. data/ext/snowcrash/src/csnowcrash.h +38 -0
  69. data/ext/snowcrash/src/posix/RegexMatch.cc +99 -0
  70. data/ext/snowcrash/src/snowcrash.cc +18 -0
  71. data/ext/snowcrash/src/snowcrash.h +41 -0
  72. data/ext/snowcrash/src/snowcrash/snowcrash.cc +170 -0
  73. data/ext/snowcrash/src/win/RegexMatch.cc +78 -0
  74. data/ext/snowcrash/sundown/CONTRIBUTING.md +10 -0
  75. data/ext/snowcrash/sundown/Makefile +83 -0
  76. data/ext/snowcrash/sundown/Makefile.win +33 -0
  77. data/ext/snowcrash/sundown/examples/smartypants.c +72 -0
  78. data/ext/snowcrash/sundown/examples/sundown.c +80 -0
  79. data/ext/snowcrash/sundown/html/houdini.h +37 -0
  80. data/ext/snowcrash/sundown/html/houdini_href_e.c +108 -0
  81. data/ext/snowcrash/sundown/html/houdini_html_e.c +84 -0
  82. data/ext/snowcrash/sundown/html/html.c +647 -0
  83. data/ext/snowcrash/sundown/html/html.h +77 -0
  84. data/ext/snowcrash/sundown/html/html_smartypants.c +389 -0
  85. data/ext/snowcrash/sundown/html_block_names.txt +25 -0
  86. data/ext/snowcrash/sundown/src/autolink.c +297 -0
  87. data/ext/snowcrash/sundown/src/autolink.h +51 -0
  88. data/ext/snowcrash/sundown/src/buffer.c +225 -0
  89. data/ext/snowcrash/sundown/src/buffer.h +96 -0
  90. data/ext/snowcrash/sundown/src/html_blocks.h +206 -0
  91. data/ext/snowcrash/sundown/src/markdown.c +2701 -0
  92. data/ext/snowcrash/sundown/src/markdown.h +147 -0
  93. data/ext/snowcrash/sundown/src/src_map.c +200 -0
  94. data/ext/snowcrash/sundown/src/src_map.h +58 -0
  95. data/ext/snowcrash/sundown/src/stack.c +81 -0
  96. data/ext/snowcrash/sundown/src/stack.h +29 -0
  97. data/ext/snowcrash/sundown/sundown.def +20 -0
  98. data/ext/snowcrash/tools/gyp/AUTHORS +11 -0
  99. data/ext/snowcrash/tools/gyp/DEPS +24 -0
  100. data/ext/snowcrash/tools/gyp/OWNERS +1 -0
  101. data/ext/snowcrash/tools/gyp/PRESUBMIT.py +120 -0
  102. data/ext/snowcrash/tools/gyp/buildbot/buildbot_run.py +190 -0
  103. data/ext/snowcrash/tools/gyp/codereview.settings +10 -0
  104. data/ext/snowcrash/tools/gyp/data/win/large-pdb-shim.cc +12 -0
  105. data/ext/snowcrash/tools/gyp/gyp +8 -0
  106. data/ext/snowcrash/tools/gyp/gyp.bat +5 -0
  107. data/ext/snowcrash/tools/gyp/gyp_main.py +18 -0
  108. data/ext/snowcrash/tools/gyp/pylib/gyp/MSVSNew.py +340 -0
  109. data/ext/snowcrash/tools/gyp/pylib/gyp/MSVSProject.py +208 -0
  110. data/ext/snowcrash/tools/gyp/pylib/gyp/MSVSSettings.py +1063 -0
  111. data/ext/snowcrash/tools/gyp/pylib/gyp/MSVSToolFile.py +58 -0
  112. data/ext/snowcrash/tools/gyp/pylib/gyp/MSVSUserFile.py +147 -0
  113. data/ext/snowcrash/tools/gyp/pylib/gyp/MSVSUtil.py +267 -0
  114. data/ext/snowcrash/tools/gyp/pylib/gyp/MSVSVersion.py +409 -0
  115. data/ext/snowcrash/tools/gyp/pylib/gyp/__init__.py +537 -0
  116. data/ext/snowcrash/tools/gyp/pylib/gyp/__init__.pyc +0 -0
  117. data/ext/snowcrash/tools/gyp/pylib/gyp/common.py +521 -0
  118. data/ext/snowcrash/tools/gyp/pylib/gyp/common.pyc +0 -0
  119. data/ext/snowcrash/tools/gyp/pylib/gyp/easy_xml.py +157 -0
  120. data/ext/snowcrash/tools/gyp/pylib/gyp/flock_tool.py +49 -0
  121. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/__init__.py +0 -0
  122. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/__init__.pyc +0 -0
  123. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/android.py +1069 -0
  124. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/cmake.py +1143 -0
  125. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/dump_dependency_json.py +81 -0
  126. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/eclipse.py +335 -0
  127. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/gypd.py +87 -0
  128. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/gypsh.py +56 -0
  129. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/make.py +2181 -0
  130. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/make.pyc +0 -0
  131. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/msvs.py +3335 -0
  132. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/ninja.py +2156 -0
  133. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/xcode.py +1224 -0
  134. data/ext/snowcrash/tools/gyp/pylib/gyp/generator/xcode.pyc +0 -0
  135. data/ext/snowcrash/tools/gyp/pylib/gyp/input.py +2809 -0
  136. data/ext/snowcrash/tools/gyp/pylib/gyp/input.pyc +0 -0
  137. data/ext/snowcrash/tools/gyp/pylib/gyp/mac_tool.py +510 -0
  138. data/ext/snowcrash/tools/gyp/pylib/gyp/msvs_emulation.py +972 -0
  139. data/ext/snowcrash/tools/gyp/pylib/gyp/ninja_syntax.py +160 -0
  140. data/ext/snowcrash/tools/gyp/pylib/gyp/ordered_dict.py +289 -0
  141. data/ext/snowcrash/tools/gyp/pylib/gyp/win_tool.py +292 -0
  142. data/ext/snowcrash/tools/gyp/pylib/gyp/xcode_emulation.py +1440 -0
  143. data/ext/snowcrash/tools/gyp/pylib/gyp/xcode_emulation.pyc +0 -0
  144. data/ext/snowcrash/tools/gyp/pylib/gyp/xcodeproj_file.py +2889 -0
  145. data/ext/snowcrash/tools/gyp/pylib/gyp/xcodeproj_file.pyc +0 -0
  146. data/ext/snowcrash/tools/gyp/pylib/gyp/xml_fix.py +69 -0
  147. data/ext/snowcrash/tools/gyp/pylintrc +307 -0
  148. data/ext/snowcrash/tools/gyp/samples/samples +81 -0
  149. data/ext/snowcrash/tools/gyp/samples/samples.bat +5 -0
  150. data/ext/snowcrash/tools/gyp/setup.py +19 -0
  151. data/ext/snowcrash/tools/gyp/tools/Xcode/Specifications/gyp.pbfilespec +27 -0
  152. data/ext/snowcrash/tools/gyp/tools/Xcode/Specifications/gyp.xclangspec +226 -0
  153. data/ext/snowcrash/tools/gyp/tools/emacs/gyp.el +252 -0
  154. data/ext/snowcrash/tools/gyp/tools/graphviz.py +100 -0
  155. data/ext/snowcrash/tools/gyp/tools/pretty_gyp.py +155 -0
  156. data/ext/snowcrash/tools/gyp/tools/pretty_sln.py +168 -0
  157. data/ext/snowcrash/tools/gyp/tools/pretty_vcproj.py +329 -0
  158. data/ext/snowcrash/tools/homebrew/snowcrash.rb +11 -0
  159. data/ext/snowcrash/vcbuild.bat +184 -0
  160. data/lib/redsnow.rb +31 -0
  161. data/lib/redsnow/binding.rb +132 -0
  162. data/lib/redsnow/blueprint.rb +365 -0
  163. data/lib/redsnow/object.rb +18 -0
  164. data/lib/redsnow/parseresult.rb +107 -0
  165. data/lib/redsnow/version.rb +4 -0
  166. data/provisioning.sh +20 -0
  167. data/redsnow.gemspec +35 -0
  168. data/test/_helper.rb +15 -0
  169. data/test/fixtures/sample-api-ast.json +97 -0
  170. data/test/fixtures/sample-api.apib +20 -0
  171. data/test/redsnow_binding_test.rb +35 -0
  172. data/test/redsnow_parseresult_test.rb +50 -0
  173. data/test/redsnow_test.rb +285 -0
  174. metadata +358 -0
@@ -0,0 +1,1224 @@
1
+ # Copyright (c) 2012 Google Inc. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ import filecmp
6
+ import gyp.common
7
+ import gyp.xcodeproj_file
8
+ import errno
9
+ import os
10
+ import sys
11
+ import posixpath
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ import tempfile
16
+
17
+
18
+ # Project files generated by this module will use _intermediate_var as a
19
+ # custom Xcode setting whose value is a DerivedSources-like directory that's
20
+ # project-specific and configuration-specific. The normal choice,
21
+ # DERIVED_FILE_DIR, is target-specific, which is thought to be too restrictive
22
+ # as it is likely that multiple targets within a single project file will want
23
+ # to access the same set of generated files. The other option,
24
+ # PROJECT_DERIVED_FILE_DIR, is unsuitable because while it is project-specific,
25
+ # it is not configuration-specific. INTERMEDIATE_DIR is defined as
26
+ # $(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION).
27
+ _intermediate_var = 'INTERMEDIATE_DIR'
28
+
29
+ # SHARED_INTERMEDIATE_DIR is the same, except that it is shared among all
30
+ # targets that share the same BUILT_PRODUCTS_DIR.
31
+ _shared_intermediate_var = 'SHARED_INTERMEDIATE_DIR'
32
+
33
+ _library_search_paths_var = 'LIBRARY_SEARCH_PATHS'
34
+
35
+ generator_default_variables = {
36
+ 'EXECUTABLE_PREFIX': '',
37
+ 'EXECUTABLE_SUFFIX': '',
38
+ 'STATIC_LIB_PREFIX': 'lib',
39
+ 'SHARED_LIB_PREFIX': 'lib',
40
+ 'STATIC_LIB_SUFFIX': '.a',
41
+ 'SHARED_LIB_SUFFIX': '.dylib',
42
+ # INTERMEDIATE_DIR is a place for targets to build up intermediate products.
43
+ # It is specific to each build environment. It is only guaranteed to exist
44
+ # and be constant within the context of a project, corresponding to a single
45
+ # input file. Some build environments may allow their intermediate directory
46
+ # to be shared on a wider scale, but this is not guaranteed.
47
+ 'INTERMEDIATE_DIR': '$(%s)' % _intermediate_var,
48
+ 'OS': 'mac',
49
+ 'PRODUCT_DIR': '$(BUILT_PRODUCTS_DIR)',
50
+ 'LIB_DIR': '$(BUILT_PRODUCTS_DIR)',
51
+ 'RULE_INPUT_ROOT': '$(INPUT_FILE_BASE)',
52
+ 'RULE_INPUT_EXT': '$(INPUT_FILE_SUFFIX)',
53
+ 'RULE_INPUT_NAME': '$(INPUT_FILE_NAME)',
54
+ 'RULE_INPUT_PATH': '$(INPUT_FILE_PATH)',
55
+ 'RULE_INPUT_DIRNAME': '$(INPUT_FILE_DIRNAME)',
56
+ 'SHARED_INTERMEDIATE_DIR': '$(%s)' % _shared_intermediate_var,
57
+ 'CONFIGURATION_NAME': '$(CONFIGURATION)',
58
+ }
59
+
60
+ # The Xcode-specific sections that hold paths.
61
+ generator_additional_path_sections = [
62
+ 'mac_bundle_resources',
63
+ 'mac_framework_headers',
64
+ 'mac_framework_private_headers',
65
+ # 'mac_framework_dirs', input already handles _dirs endings.
66
+ ]
67
+
68
+ # The Xcode-specific keys that exist on targets and aren't moved down to
69
+ # configurations.
70
+ generator_additional_non_configuration_keys = [
71
+ 'mac_bundle',
72
+ 'mac_bundle_resources',
73
+ 'mac_framework_headers',
74
+ 'mac_framework_private_headers',
75
+ 'mac_xctest_bundle',
76
+ 'xcode_create_dependents_test_runner',
77
+ ]
78
+
79
+ # We want to let any rules apply to files that are resources also.
80
+ generator_extra_sources_for_rules = [
81
+ 'mac_bundle_resources',
82
+ 'mac_framework_headers',
83
+ 'mac_framework_private_headers',
84
+ ]
85
+
86
+ # Xcode's standard set of library directories, which don't need to be duplicated
87
+ # in LIBRARY_SEARCH_PATHS. This list is not exhaustive, but that's okay.
88
+ xcode_standard_library_dirs = frozenset([
89
+ '$(SDKROOT)/usr/lib',
90
+ '$(SDKROOT)/usr/local/lib',
91
+ ])
92
+
93
+ def CreateXCConfigurationList(configuration_names):
94
+ xccl = gyp.xcodeproj_file.XCConfigurationList({'buildConfigurations': []})
95
+ if len(configuration_names) == 0:
96
+ configuration_names = ['Default']
97
+ for configuration_name in configuration_names:
98
+ xcbc = gyp.xcodeproj_file.XCBuildConfiguration({
99
+ 'name': configuration_name})
100
+ xccl.AppendProperty('buildConfigurations', xcbc)
101
+ xccl.SetProperty('defaultConfigurationName', configuration_names[0])
102
+ return xccl
103
+
104
+
105
+ class XcodeProject(object):
106
+ def __init__(self, gyp_path, path, build_file_dict):
107
+ self.gyp_path = gyp_path
108
+ self.path = path
109
+ self.project = gyp.xcodeproj_file.PBXProject(path=path)
110
+ projectDirPath = gyp.common.RelativePath(
111
+ os.path.dirname(os.path.abspath(self.gyp_path)),
112
+ os.path.dirname(path) or '.')
113
+ self.project.SetProperty('projectDirPath', projectDirPath)
114
+ self.project_file = \
115
+ gyp.xcodeproj_file.XCProjectFile({'rootObject': self.project})
116
+ self.build_file_dict = build_file_dict
117
+
118
+ # TODO(mark): add destructor that cleans up self.path if created_dir is
119
+ # True and things didn't complete successfully. Or do something even
120
+ # better with "try"?
121
+ self.created_dir = False
122
+ try:
123
+ os.makedirs(self.path)
124
+ self.created_dir = True
125
+ except OSError, e:
126
+ if e.errno != errno.EEXIST:
127
+ raise
128
+
129
+ def Finalize1(self, xcode_targets, serialize_all_tests):
130
+ # Collect a list of all of the build configuration names used by the
131
+ # various targets in the file. It is very heavily advised to keep each
132
+ # target in an entire project (even across multiple project files) using
133
+ # the same set of configuration names.
134
+ configurations = []
135
+ for xct in self.project.GetProperty('targets'):
136
+ xccl = xct.GetProperty('buildConfigurationList')
137
+ xcbcs = xccl.GetProperty('buildConfigurations')
138
+ for xcbc in xcbcs:
139
+ name = xcbc.GetProperty('name')
140
+ if name not in configurations:
141
+ configurations.append(name)
142
+
143
+ # Replace the XCConfigurationList attached to the PBXProject object with
144
+ # a new one specifying all of the configuration names used by the various
145
+ # targets.
146
+ try:
147
+ xccl = CreateXCConfigurationList(configurations)
148
+ self.project.SetProperty('buildConfigurationList', xccl)
149
+ except:
150
+ sys.stderr.write("Problem with gyp file %s\n" % self.gyp_path)
151
+ raise
152
+
153
+ # The need for this setting is explained above where _intermediate_var is
154
+ # defined. The comments below about wanting to avoid project-wide build
155
+ # settings apply here too, but this needs to be set on a project-wide basis
156
+ # so that files relative to the _intermediate_var setting can be displayed
157
+ # properly in the Xcode UI.
158
+ #
159
+ # Note that for configuration-relative files such as anything relative to
160
+ # _intermediate_var, for the purposes of UI tree view display, Xcode will
161
+ # only resolve the configuration name once, when the project file is
162
+ # opened. If the active build configuration is changed, the project file
163
+ # must be closed and reopened if it is desired for the tree view to update.
164
+ # This is filed as Apple radar 6588391.
165
+ xccl.SetBuildSetting(_intermediate_var,
166
+ '$(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION)')
167
+ xccl.SetBuildSetting(_shared_intermediate_var,
168
+ '$(SYMROOT)/DerivedSources/$(CONFIGURATION)')
169
+
170
+ # Set user-specified project-wide build settings and config files. This
171
+ # is intended to be used very sparingly. Really, almost everything should
172
+ # go into target-specific build settings sections. The project-wide
173
+ # settings are only intended to be used in cases where Xcode attempts to
174
+ # resolve variable references in a project context as opposed to a target
175
+ # context, such as when resolving sourceTree references while building up
176
+ # the tree tree view for UI display.
177
+ # Any values set globally are applied to all configurations, then any
178
+ # per-configuration values are applied.
179
+ for xck, xcv in self.build_file_dict.get('xcode_settings', {}).iteritems():
180
+ xccl.SetBuildSetting(xck, xcv)
181
+ if 'xcode_config_file' in self.build_file_dict:
182
+ config_ref = self.project.AddOrGetFileInRootGroup(
183
+ self.build_file_dict['xcode_config_file'])
184
+ xccl.SetBaseConfiguration(config_ref)
185
+ build_file_configurations = self.build_file_dict.get('configurations', {})
186
+ if build_file_configurations:
187
+ for config_name in configurations:
188
+ build_file_configuration_named = \
189
+ build_file_configurations.get(config_name, {})
190
+ if build_file_configuration_named:
191
+ xcc = xccl.ConfigurationNamed(config_name)
192
+ for xck, xcv in build_file_configuration_named.get('xcode_settings',
193
+ {}).iteritems():
194
+ xcc.SetBuildSetting(xck, xcv)
195
+ if 'xcode_config_file' in build_file_configuration_named:
196
+ config_ref = self.project.AddOrGetFileInRootGroup(
197
+ build_file_configurations[config_name]['xcode_config_file'])
198
+ xcc.SetBaseConfiguration(config_ref)
199
+
200
+ # Sort the targets based on how they appeared in the input.
201
+ # TODO(mark): Like a lot of other things here, this assumes internal
202
+ # knowledge of PBXProject - in this case, of its "targets" property.
203
+
204
+ # ordinary_targets are ordinary targets that are already in the project
205
+ # file. run_test_targets are the targets that run unittests and should be
206
+ # used for the Run All Tests target. support_targets are the action/rule
207
+ # targets used by GYP file targets, just kept for the assert check.
208
+ ordinary_targets = []
209
+ run_test_targets = []
210
+ support_targets = []
211
+
212
+ # targets is full list of targets in the project.
213
+ targets = []
214
+
215
+ # does the it define it's own "all"?
216
+ has_custom_all = False
217
+
218
+ # targets_for_all is the list of ordinary_targets that should be listed
219
+ # in this project's "All" target. It includes each non_runtest_target
220
+ # that does not have suppress_wildcard set.
221
+ targets_for_all = []
222
+
223
+ for target in self.build_file_dict['targets']:
224
+ target_name = target['target_name']
225
+ toolset = target['toolset']
226
+ qualified_target = gyp.common.QualifiedTarget(self.gyp_path, target_name,
227
+ toolset)
228
+ xcode_target = xcode_targets[qualified_target]
229
+ # Make sure that the target being added to the sorted list is already in
230
+ # the unsorted list.
231
+ assert xcode_target in self.project._properties['targets']
232
+ targets.append(xcode_target)
233
+ ordinary_targets.append(xcode_target)
234
+ if xcode_target.support_target:
235
+ support_targets.append(xcode_target.support_target)
236
+ targets.append(xcode_target.support_target)
237
+
238
+ if not int(target.get('suppress_wildcard', False)):
239
+ targets_for_all.append(xcode_target)
240
+
241
+ if target_name.lower() == 'all':
242
+ has_custom_all = True;
243
+
244
+ # If this target has a 'run_as' attribute, add its target to the
245
+ # targets, and add it to the test targets.
246
+ if target.get('run_as'):
247
+ # Make a target to run something. It should have one
248
+ # dependency, the parent xcode target.
249
+ xccl = CreateXCConfigurationList(configurations)
250
+ run_target = gyp.xcodeproj_file.PBXAggregateTarget({
251
+ 'name': 'Run ' + target_name,
252
+ 'productName': xcode_target.GetProperty('productName'),
253
+ 'buildConfigurationList': xccl,
254
+ },
255
+ parent=self.project)
256
+ run_target.AddDependency(xcode_target)
257
+
258
+ command = target['run_as']
259
+ script = ''
260
+ if command.get('working_directory'):
261
+ script = script + 'cd "%s"\n' % \
262
+ gyp.xcodeproj_file.ConvertVariablesToShellSyntax(
263
+ command.get('working_directory'))
264
+
265
+ if command.get('environment'):
266
+ script = script + "\n".join(
267
+ ['export %s="%s"' %
268
+ (key, gyp.xcodeproj_file.ConvertVariablesToShellSyntax(val))
269
+ for (key, val) in command.get('environment').iteritems()]) + "\n"
270
+
271
+ # Some test end up using sockets, files on disk, etc. and can get
272
+ # confused if more then one test runs at a time. The generator
273
+ # flag 'xcode_serialize_all_test_runs' controls the forcing of all
274
+ # tests serially. It defaults to True. To get serial runs this
275
+ # little bit of python does the same as the linux flock utility to
276
+ # make sure only one runs at a time.
277
+ command_prefix = ''
278
+ if serialize_all_tests:
279
+ command_prefix = \
280
+ """python -c "import fcntl, subprocess, sys
281
+ file = open('$TMPDIR/GYP_serialize_test_runs', 'a')
282
+ fcntl.flock(file.fileno(), fcntl.LOCK_EX)
283
+ sys.exit(subprocess.call(sys.argv[1:]))" """
284
+
285
+ # If we were unable to exec for some reason, we want to exit
286
+ # with an error, and fixup variable references to be shell
287
+ # syntax instead of xcode syntax.
288
+ script = script + 'exec ' + command_prefix + '%s\nexit 1\n' % \
289
+ gyp.xcodeproj_file.ConvertVariablesToShellSyntax(
290
+ gyp.common.EncodePOSIXShellList(command.get('action')))
291
+
292
+ ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({
293
+ 'shellScript': script,
294
+ 'showEnvVarsInLog': 0,
295
+ })
296
+ run_target.AppendProperty('buildPhases', ssbp)
297
+
298
+ # Add the run target to the project file.
299
+ targets.append(run_target)
300
+ run_test_targets.append(run_target)
301
+ xcode_target.test_runner = run_target
302
+
303
+
304
+ # Make sure that the list of targets being replaced is the same length as
305
+ # the one replacing it, but allow for the added test runner targets.
306
+ assert len(self.project._properties['targets']) == \
307
+ len(ordinary_targets) + len(support_targets)
308
+
309
+ self.project._properties['targets'] = targets
310
+
311
+ # Get rid of unnecessary levels of depth in groups like the Source group.
312
+ self.project.RootGroupsTakeOverOnlyChildren(True)
313
+
314
+ # Sort the groups nicely. Do this after sorting the targets, because the
315
+ # Products group is sorted based on the order of the targets.
316
+ self.project.SortGroups()
317
+
318
+ # Create an "All" target if there's more than one target in this project
319
+ # file and the project didn't define its own "All" target. Put a generated
320
+ # "All" target first so that people opening up the project for the first
321
+ # time will build everything by default.
322
+ if len(targets_for_all) > 1 and not has_custom_all:
323
+ xccl = CreateXCConfigurationList(configurations)
324
+ all_target = gyp.xcodeproj_file.PBXAggregateTarget(
325
+ {
326
+ 'buildConfigurationList': xccl,
327
+ 'name': 'All',
328
+ },
329
+ parent=self.project)
330
+
331
+ for target in targets_for_all:
332
+ all_target.AddDependency(target)
333
+
334
+ # TODO(mark): This is evil because it relies on internal knowledge of
335
+ # PBXProject._properties. It's important to get the "All" target first,
336
+ # though.
337
+ self.project._properties['targets'].insert(0, all_target)
338
+
339
+ # The same, but for run_test_targets.
340
+ if len(run_test_targets) > 1:
341
+ xccl = CreateXCConfigurationList(configurations)
342
+ run_all_tests_target = gyp.xcodeproj_file.PBXAggregateTarget(
343
+ {
344
+ 'buildConfigurationList': xccl,
345
+ 'name': 'Run All Tests',
346
+ },
347
+ parent=self.project)
348
+ for run_test_target in run_test_targets:
349
+ run_all_tests_target.AddDependency(run_test_target)
350
+
351
+ # Insert after the "All" target, which must exist if there is more than
352
+ # one run_test_target.
353
+ self.project._properties['targets'].insert(1, run_all_tests_target)
354
+
355
+ def Finalize2(self, xcode_targets, xcode_target_to_target_dict):
356
+ # Finalize2 needs to happen in a separate step because the process of
357
+ # updating references to other projects depends on the ordering of targets
358
+ # within remote project files. Finalize1 is responsible for sorting duty,
359
+ # and once all project files are sorted, Finalize2 can come in and update
360
+ # these references.
361
+
362
+ # To support making a "test runner" target that will run all the tests
363
+ # that are direct dependents of any given target, we look for
364
+ # xcode_create_dependents_test_runner being set on an Aggregate target,
365
+ # and generate a second target that will run the tests runners found under
366
+ # the marked target.
367
+ for bf_tgt in self.build_file_dict['targets']:
368
+ if int(bf_tgt.get('xcode_create_dependents_test_runner', 0)):
369
+ tgt_name = bf_tgt['target_name']
370
+ toolset = bf_tgt['toolset']
371
+ qualified_target = gyp.common.QualifiedTarget(self.gyp_path,
372
+ tgt_name, toolset)
373
+ xcode_target = xcode_targets[qualified_target]
374
+ if isinstance(xcode_target, gyp.xcodeproj_file.PBXAggregateTarget):
375
+ # Collect all the run test targets.
376
+ all_run_tests = []
377
+ pbxtds = xcode_target.GetProperty('dependencies')
378
+ for pbxtd in pbxtds:
379
+ pbxcip = pbxtd.GetProperty('targetProxy')
380
+ dependency_xct = pbxcip.GetProperty('remoteGlobalIDString')
381
+ if hasattr(dependency_xct, 'test_runner'):
382
+ all_run_tests.append(dependency_xct.test_runner)
383
+
384
+ # Directly depend on all the runners as they depend on the target
385
+ # that builds them.
386
+ if len(all_run_tests) > 0:
387
+ run_all_target = gyp.xcodeproj_file.PBXAggregateTarget({
388
+ 'name': 'Run %s Tests' % tgt_name,
389
+ 'productName': tgt_name,
390
+ },
391
+ parent=self.project)
392
+ for run_test_target in all_run_tests:
393
+ run_all_target.AddDependency(run_test_target)
394
+
395
+ # Insert the test runner after the related target.
396
+ idx = self.project._properties['targets'].index(xcode_target)
397
+ self.project._properties['targets'].insert(idx + 1, run_all_target)
398
+
399
+ # Update all references to other projects, to make sure that the lists of
400
+ # remote products are complete. Otherwise, Xcode will fill them in when
401
+ # it opens the project file, which will result in unnecessary diffs.
402
+ # TODO(mark): This is evil because it relies on internal knowledge of
403
+ # PBXProject._other_pbxprojects.
404
+ for other_pbxproject in self.project._other_pbxprojects.keys():
405
+ self.project.AddOrGetProjectReference(other_pbxproject)
406
+
407
+ self.project.SortRemoteProductReferences()
408
+
409
+ # Give everything an ID.
410
+ self.project_file.ComputeIDs()
411
+
412
+ # Make sure that no two objects in the project file have the same ID. If
413
+ # multiple objects wind up with the same ID, upon loading the file, Xcode
414
+ # will only recognize one object (the last one in the file?) and the
415
+ # results are unpredictable.
416
+ self.project_file.EnsureNoIDCollisions()
417
+
418
+ def Write(self):
419
+ # Write the project file to a temporary location first. Xcode watches for
420
+ # changes to the project file and presents a UI sheet offering to reload
421
+ # the project when it does change. However, in some cases, especially when
422
+ # multiple projects are open or when Xcode is busy, things don't work so
423
+ # seamlessly. Sometimes, Xcode is able to detect that a project file has
424
+ # changed but can't unload it because something else is referencing it.
425
+ # To mitigate this problem, and to avoid even having Xcode present the UI
426
+ # sheet when an open project is rewritten for inconsequential changes, the
427
+ # project file is written to a temporary file in the xcodeproj directory
428
+ # first. The new temporary file is then compared to the existing project
429
+ # file, if any. If they differ, the new file replaces the old; otherwise,
430
+ # the new project file is simply deleted. Xcode properly detects a file
431
+ # being renamed over an open project file as a change and so it remains
432
+ # able to present the "project file changed" sheet under this system.
433
+ # Writing to a temporary file first also avoids the possible problem of
434
+ # Xcode rereading an incomplete project file.
435
+ (output_fd, new_pbxproj_path) = \
436
+ tempfile.mkstemp(suffix='.tmp', prefix='project.pbxproj.gyp.',
437
+ dir=self.path)
438
+
439
+ try:
440
+ output_file = os.fdopen(output_fd, 'wb')
441
+
442
+ self.project_file.Print(output_file)
443
+ output_file.close()
444
+
445
+ pbxproj_path = os.path.join(self.path, 'project.pbxproj')
446
+
447
+ same = False
448
+ try:
449
+ same = filecmp.cmp(pbxproj_path, new_pbxproj_path, False)
450
+ except OSError, e:
451
+ if e.errno != errno.ENOENT:
452
+ raise
453
+
454
+ if same:
455
+ # The new file is identical to the old one, just get rid of the new
456
+ # one.
457
+ os.unlink(new_pbxproj_path)
458
+ else:
459
+ # The new file is different from the old one, or there is no old one.
460
+ # Rename the new file to the permanent name.
461
+ #
462
+ # tempfile.mkstemp uses an overly restrictive mode, resulting in a
463
+ # file that can only be read by the owner, regardless of the umask.
464
+ # There's no reason to not respect the umask here, which means that
465
+ # an extra hoop is required to fetch it and reset the new file's mode.
466
+ #
467
+ # No way to get the umask without setting a new one? Set a safe one
468
+ # and then set it back to the old value.
469
+ umask = os.umask(077)
470
+ os.umask(umask)
471
+
472
+ os.chmod(new_pbxproj_path, 0666 & ~umask)
473
+ os.rename(new_pbxproj_path, pbxproj_path)
474
+
475
+ except Exception:
476
+ # Don't leave turds behind. In fact, if this code was responsible for
477
+ # creating the xcodeproj directory, get rid of that too.
478
+ os.unlink(new_pbxproj_path)
479
+ if self.created_dir:
480
+ shutil.rmtree(self.path, True)
481
+ raise
482
+
483
+
484
+ def AddSourceToTarget(source, type, pbxp, xct):
485
+ # TODO(mark): Perhaps source_extensions and library_extensions can be made a
486
+ # little bit fancier.
487
+ source_extensions = ['c', 'cc', 'cpp', 'cxx', 'm', 'mm', 's']
488
+
489
+ # .o is conceptually more of a "source" than a "library," but Xcode thinks
490
+ # of "sources" as things to compile and "libraries" (or "frameworks") as
491
+ # things to link with. Adding an object file to an Xcode target's frameworks
492
+ # phase works properly.
493
+ library_extensions = ['a', 'dylib', 'framework', 'o']
494
+
495
+ basename = posixpath.basename(source)
496
+ (root, ext) = posixpath.splitext(basename)
497
+ if ext:
498
+ ext = ext[1:].lower()
499
+
500
+ if ext in source_extensions and type != 'none':
501
+ xct.SourcesPhase().AddFile(source)
502
+ elif ext in library_extensions and type != 'none':
503
+ xct.FrameworksPhase().AddFile(source)
504
+ else:
505
+ # Files that aren't added to a sources or frameworks build phase can still
506
+ # go into the project file, just not as part of a build phase.
507
+ pbxp.AddOrGetFileInRootGroup(source)
508
+
509
+
510
+ def AddResourceToTarget(resource, pbxp, xct):
511
+ # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call
512
+ # where it's used.
513
+ xct.ResourcesPhase().AddFile(resource)
514
+
515
+
516
+ def AddHeaderToTarget(header, pbxp, xct, is_public):
517
+ # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call
518
+ # where it's used.
519
+ settings = '{ATTRIBUTES = (%s, ); }' % ('Private', 'Public')[is_public]
520
+ xct.HeadersPhase().AddFile(header, settings)
521
+
522
+
523
+ _xcode_variable_re = re.compile('(\$\((.*?)\))')
524
+ def ExpandXcodeVariables(string, expansions):
525
+ """Expands Xcode-style $(VARIABLES) in string per the expansions dict.
526
+
527
+ In some rare cases, it is appropriate to expand Xcode variables when a
528
+ project file is generated. For any substring $(VAR) in string, if VAR is a
529
+ key in the expansions dict, $(VAR) will be replaced with expansions[VAR].
530
+ Any $(VAR) substring in string for which VAR is not a key in the expansions
531
+ dict will remain in the returned string.
532
+ """
533
+
534
+ matches = _xcode_variable_re.findall(string)
535
+ if matches == None:
536
+ return string
537
+
538
+ matches.reverse()
539
+ for match in matches:
540
+ (to_replace, variable) = match
541
+ if not variable in expansions:
542
+ continue
543
+
544
+ replacement = expansions[variable]
545
+ string = re.sub(re.escape(to_replace), replacement, string)
546
+
547
+ return string
548
+
549
+
550
+ _xcode_define_re = re.compile(r'([\\\"\' ])')
551
+ def EscapeXcodeDefine(s):
552
+ """We must escape the defines that we give to XCode so that it knows not to
553
+ split on spaces and to respect backslash and quote literals. However, we
554
+ must not quote the define, or Xcode will incorrectly intepret variables
555
+ especially $(inherited)."""
556
+ return re.sub(_xcode_define_re, r'\\\1', s)
557
+
558
+
559
+ def PerformBuild(data, configurations, params):
560
+ options = params['options']
561
+
562
+ for build_file, build_file_dict in data.iteritems():
563
+ (build_file_root, build_file_ext) = os.path.splitext(build_file)
564
+ if build_file_ext != '.gyp':
565
+ continue
566
+ xcodeproj_path = build_file_root + options.suffix + '.xcodeproj'
567
+ if options.generator_output:
568
+ xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path)
569
+
570
+ for config in configurations:
571
+ arguments = ['xcodebuild', '-project', xcodeproj_path]
572
+ arguments += ['-configuration', config]
573
+ print "Building [%s]: %s" % (config, arguments)
574
+ subprocess.check_call(arguments)
575
+
576
+
577
+ def GenerateOutput(target_list, target_dicts, data, params):
578
+ options = params['options']
579
+ generator_flags = params.get('generator_flags', {})
580
+ parallel_builds = generator_flags.get('xcode_parallel_builds', True)
581
+ serialize_all_tests = \
582
+ generator_flags.get('xcode_serialize_all_test_runs', True)
583
+ project_version = generator_flags.get('xcode_project_version', None)
584
+ skip_excluded_files = \
585
+ not generator_flags.get('xcode_list_excluded_files', True)
586
+ xcode_projects = {}
587
+ for build_file, build_file_dict in data.iteritems():
588
+ (build_file_root, build_file_ext) = os.path.splitext(build_file)
589
+ if build_file_ext != '.gyp':
590
+ continue
591
+ xcodeproj_path = build_file_root + options.suffix + '.xcodeproj'
592
+ if options.generator_output:
593
+ xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path)
594
+ xcp = XcodeProject(build_file, xcodeproj_path, build_file_dict)
595
+ xcode_projects[build_file] = xcp
596
+ pbxp = xcp.project
597
+
598
+ if parallel_builds:
599
+ pbxp.SetProperty('attributes',
600
+ {'BuildIndependentTargetsInParallel': 'YES'})
601
+ if project_version:
602
+ xcp.project_file.SetXcodeVersion(project_version)
603
+
604
+ # Add gyp/gypi files to project
605
+ if not generator_flags.get('standalone'):
606
+ main_group = pbxp.GetProperty('mainGroup')
607
+ build_group = gyp.xcodeproj_file.PBXGroup({'name': 'Build'})
608
+ main_group.AppendChild(build_group)
609
+ for included_file in build_file_dict['included_files']:
610
+ build_group.AddOrGetFileByPath(included_file, False)
611
+
612
+ xcode_targets = {}
613
+ xcode_target_to_target_dict = {}
614
+ for qualified_target in target_list:
615
+ [build_file, target_name, toolset] = \
616
+ gyp.common.ParseQualifiedTarget(qualified_target)
617
+
618
+ spec = target_dicts[qualified_target]
619
+ if spec['toolset'] != 'target':
620
+ raise Exception(
621
+ 'Multiple toolsets not supported in xcode build (target %s)' %
622
+ qualified_target)
623
+ configuration_names = [spec['default_configuration']]
624
+ for configuration_name in sorted(spec['configurations'].keys()):
625
+ if configuration_name not in configuration_names:
626
+ configuration_names.append(configuration_name)
627
+ xcp = xcode_projects[build_file]
628
+ pbxp = xcp.project
629
+
630
+ # Set up the configurations for the target according to the list of names
631
+ # supplied.
632
+ xccl = CreateXCConfigurationList(configuration_names)
633
+
634
+ # Create an XCTarget subclass object for the target. The type with
635
+ # "+bundle" appended will be used if the target has "mac_bundle" set.
636
+ # loadable_modules not in a mac_bundle are mapped to
637
+ # com.googlecode.gyp.xcode.bundle, a pseudo-type that xcode.py interprets
638
+ # to create a single-file mh_bundle.
639
+ _types = {
640
+ 'executable': 'com.apple.product-type.tool',
641
+ 'loadable_module': 'com.googlecode.gyp.xcode.bundle',
642
+ 'shared_library': 'com.apple.product-type.library.dynamic',
643
+ 'static_library': 'com.apple.product-type.library.static',
644
+ 'executable+bundle': 'com.apple.product-type.application',
645
+ 'loadable_module+bundle': 'com.apple.product-type.bundle',
646
+ 'loadable_module+xctest': 'com.apple.product-type.bundle.unit-test',
647
+ 'shared_library+bundle': 'com.apple.product-type.framework',
648
+ }
649
+
650
+ target_properties = {
651
+ 'buildConfigurationList': xccl,
652
+ 'name': target_name,
653
+ }
654
+
655
+ type = spec['type']
656
+ is_xctest = int(spec.get('mac_xctest_bundle', 0))
657
+ is_bundle = int(spec.get('mac_bundle', 0)) or is_xctest
658
+ if type != 'none':
659
+ type_bundle_key = type
660
+ if is_xctest:
661
+ type_bundle_key += '+xctest'
662
+ assert type == 'loadable_module', (
663
+ 'mac_xctest_bundle targets must have type loadable_module '
664
+ '(target %s)' % target_name)
665
+ elif is_bundle:
666
+ type_bundle_key += '+bundle'
667
+
668
+ xctarget_type = gyp.xcodeproj_file.PBXNativeTarget
669
+ try:
670
+ target_properties['productType'] = _types[type_bundle_key]
671
+ except KeyError, e:
672
+ gyp.common.ExceptionAppend(e, "-- unknown product type while "
673
+ "writing target %s" % target_name)
674
+ raise
675
+ else:
676
+ xctarget_type = gyp.xcodeproj_file.PBXAggregateTarget
677
+ assert not is_bundle, (
678
+ 'mac_bundle targets cannot have type none (target "%s")' %
679
+ target_name)
680
+ assert not is_xctest, (
681
+ 'mac_xctest_bundle targets cannot have type none (target "%s")' %
682
+ target_name)
683
+
684
+ target_product_name = spec.get('product_name')
685
+ if target_product_name is not None:
686
+ target_properties['productName'] = target_product_name
687
+
688
+ xct = xctarget_type(target_properties, parent=pbxp,
689
+ force_outdir=spec.get('product_dir'),
690
+ force_prefix=spec.get('product_prefix'),
691
+ force_extension=spec.get('product_extension'))
692
+ pbxp.AppendProperty('targets', xct)
693
+ xcode_targets[qualified_target] = xct
694
+ xcode_target_to_target_dict[xct] = spec
695
+
696
+ spec_actions = spec.get('actions', [])
697
+ spec_rules = spec.get('rules', [])
698
+
699
+ # Xcode has some "issues" with checking dependencies for the "Compile
700
+ # sources" step with any source files/headers generated by actions/rules.
701
+ # To work around this, if a target is building anything directly (not
702
+ # type "none"), then a second target is used to run the GYP actions/rules
703
+ # and is made a dependency of this target. This way the work is done
704
+ # before the dependency checks for what should be recompiled.
705
+ support_xct = None
706
+ if type != 'none' and (spec_actions or spec_rules):
707
+ support_xccl = CreateXCConfigurationList(configuration_names);
708
+ support_target_properties = {
709
+ 'buildConfigurationList': support_xccl,
710
+ 'name': target_name + ' Support',
711
+ }
712
+ if target_product_name:
713
+ support_target_properties['productName'] = \
714
+ target_product_name + ' Support'
715
+ support_xct = \
716
+ gyp.xcodeproj_file.PBXAggregateTarget(support_target_properties,
717
+ parent=pbxp)
718
+ pbxp.AppendProperty('targets', support_xct)
719
+ xct.AddDependency(support_xct)
720
+ # Hang the support target off the main target so it can be tested/found
721
+ # by the generator during Finalize.
722
+ xct.support_target = support_xct
723
+
724
+ prebuild_index = 0
725
+
726
+ # Add custom shell script phases for "actions" sections.
727
+ for action in spec_actions:
728
+ # There's no need to write anything into the script to ensure that the
729
+ # output directories already exist, because Xcode will look at the
730
+ # declared outputs and automatically ensure that they exist for us.
731
+
732
+ # Do we have a message to print when this action runs?
733
+ message = action.get('message')
734
+ if message:
735
+ message = 'echo note: ' + gyp.common.EncodePOSIXShellArgument(message)
736
+ else:
737
+ message = ''
738
+
739
+ # Turn the list into a string that can be passed to a shell.
740
+ action_string = gyp.common.EncodePOSIXShellList(action['action'])
741
+
742
+ # Convert Xcode-type variable references to sh-compatible environment
743
+ # variable references.
744
+ message_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(message)
745
+ action_string_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(
746
+ action_string)
747
+
748
+ script = ''
749
+ # Include the optional message
750
+ if message_sh:
751
+ script += message_sh + '\n'
752
+ # Be sure the script runs in exec, and that if exec fails, the script
753
+ # exits signalling an error.
754
+ script += 'exec ' + action_string_sh + '\nexit 1\n'
755
+ ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({
756
+ 'inputPaths': action['inputs'],
757
+ 'name': 'Action "' + action['action_name'] + '"',
758
+ 'outputPaths': action['outputs'],
759
+ 'shellScript': script,
760
+ 'showEnvVarsInLog': 0,
761
+ })
762
+
763
+ if support_xct:
764
+ support_xct.AppendProperty('buildPhases', ssbp)
765
+ else:
766
+ # TODO(mark): this assumes too much knowledge of the internals of
767
+ # xcodeproj_file; some of these smarts should move into xcodeproj_file
768
+ # itself.
769
+ xct._properties['buildPhases'].insert(prebuild_index, ssbp)
770
+ prebuild_index = prebuild_index + 1
771
+
772
+ # TODO(mark): Should verify that at most one of these is specified.
773
+ if int(action.get('process_outputs_as_sources', False)):
774
+ for output in action['outputs']:
775
+ AddSourceToTarget(output, type, pbxp, xct)
776
+
777
+ if int(action.get('process_outputs_as_mac_bundle_resources', False)):
778
+ for output in action['outputs']:
779
+ AddResourceToTarget(output, pbxp, xct)
780
+
781
+ # tgt_mac_bundle_resources holds the list of bundle resources so
782
+ # the rule processing can check against it.
783
+ if is_bundle:
784
+ tgt_mac_bundle_resources = spec.get('mac_bundle_resources', [])
785
+ else:
786
+ tgt_mac_bundle_resources = []
787
+
788
+ # Add custom shell script phases driving "make" for "rules" sections.
789
+ #
790
+ # Xcode's built-in rule support is almost powerful enough to use directly,
791
+ # but there are a few significant deficiencies that render them unusable.
792
+ # There are workarounds for some of its inadequacies, but in aggregate,
793
+ # the workarounds added complexity to the generator, and some workarounds
794
+ # actually require input files to be crafted more carefully than I'd like.
795
+ # Consequently, until Xcode rules are made more capable, "rules" input
796
+ # sections will be handled in Xcode output by shell script build phases
797
+ # performed prior to the compilation phase.
798
+ #
799
+ # The following problems with Xcode rules were found. The numbers are
800
+ # Apple radar IDs. I hope that these shortcomings are addressed, I really
801
+ # liked having the rules handled directly in Xcode during the period that
802
+ # I was prototyping this.
803
+ #
804
+ # 6588600 Xcode compiles custom script rule outputs too soon, compilation
805
+ # fails. This occurs when rule outputs from distinct inputs are
806
+ # interdependent. The only workaround is to put rules and their
807
+ # inputs in a separate target from the one that compiles the rule
808
+ # outputs. This requires input file cooperation and it means that
809
+ # process_outputs_as_sources is unusable.
810
+ # 6584932 Need to declare that custom rule outputs should be excluded from
811
+ # compilation. A possible workaround is to lie to Xcode about a
812
+ # rule's output, giving it a dummy file it doesn't know how to
813
+ # compile. The rule action script would need to touch the dummy.
814
+ # 6584839 I need a way to declare additional inputs to a custom rule.
815
+ # A possible workaround is a shell script phase prior to
816
+ # compilation that touches a rule's primary input files if any
817
+ # would-be additional inputs are newer than the output. Modifying
818
+ # the source tree - even just modification times - feels dirty.
819
+ # 6564240 Xcode "custom script" build rules always dump all environment
820
+ # variables. This is a low-prioroty problem and is not a
821
+ # show-stopper.
822
+ rules_by_ext = {}
823
+ for rule in spec_rules:
824
+ rules_by_ext[rule['extension']] = rule
825
+
826
+ # First, some definitions:
827
+ #
828
+ # A "rule source" is a file that was listed in a target's "sources"
829
+ # list and will have a rule applied to it on the basis of matching the
830
+ # rule's "extensions" attribute. Rule sources are direct inputs to
831
+ # rules.
832
+ #
833
+ # Rule definitions may specify additional inputs in their "inputs"
834
+ # attribute. These additional inputs are used for dependency tracking
835
+ # purposes.
836
+ #
837
+ # A "concrete output" is a rule output with input-dependent variables
838
+ # resolved. For example, given a rule with:
839
+ # 'extension': 'ext', 'outputs': ['$(INPUT_FILE_BASE).cc'],
840
+ # if the target's "sources" list contained "one.ext" and "two.ext",
841
+ # the "concrete output" for rule input "two.ext" would be "two.cc". If
842
+ # a rule specifies multiple outputs, each input file that the rule is
843
+ # applied to will have the same number of concrete outputs.
844
+ #
845
+ # If any concrete outputs are outdated or missing relative to their
846
+ # corresponding rule_source or to any specified additional input, the
847
+ # rule action must be performed to generate the concrete outputs.
848
+
849
+ # concrete_outputs_by_rule_source will have an item at the same index
850
+ # as the rule['rule_sources'] that it corresponds to. Each item is a
851
+ # list of all of the concrete outputs for the rule_source.
852
+ concrete_outputs_by_rule_source = []
853
+
854
+ # concrete_outputs_all is a flat list of all concrete outputs that this
855
+ # rule is able to produce, given the known set of input files
856
+ # (rule_sources) that apply to it.
857
+ concrete_outputs_all = []
858
+
859
+ # messages & actions are keyed by the same indices as rule['rule_sources']
860
+ # and concrete_outputs_by_rule_source. They contain the message and
861
+ # action to perform after resolving input-dependent variables. The
862
+ # message is optional, in which case None is stored for each rule source.
863
+ messages = []
864
+ actions = []
865
+
866
+ for rule_source in rule.get('rule_sources', []):
867
+ rule_source_dirname, rule_source_basename = \
868
+ posixpath.split(rule_source)
869
+ (rule_source_root, rule_source_ext) = \
870
+ posixpath.splitext(rule_source_basename)
871
+
872
+ # These are the same variable names that Xcode uses for its own native
873
+ # rule support. Because Xcode's rule engine is not being used, they
874
+ # need to be expanded as they are written to the makefile.
875
+ rule_input_dict = {
876
+ 'INPUT_FILE_BASE': rule_source_root,
877
+ 'INPUT_FILE_SUFFIX': rule_source_ext,
878
+ 'INPUT_FILE_NAME': rule_source_basename,
879
+ 'INPUT_FILE_PATH': rule_source,
880
+ 'INPUT_FILE_DIRNAME': rule_source_dirname,
881
+ }
882
+
883
+ concrete_outputs_for_this_rule_source = []
884
+ for output in rule.get('outputs', []):
885
+ # Fortunately, Xcode and make both use $(VAR) format for their
886
+ # variables, so the expansion is the only transformation necessary.
887
+ # Any remaning $(VAR)-type variables in the string can be given
888
+ # directly to make, which will pick up the correct settings from
889
+ # what Xcode puts into the environment.
890
+ concrete_output = ExpandXcodeVariables(output, rule_input_dict)
891
+ concrete_outputs_for_this_rule_source.append(concrete_output)
892
+
893
+ # Add all concrete outputs to the project.
894
+ pbxp.AddOrGetFileInRootGroup(concrete_output)
895
+
896
+ concrete_outputs_by_rule_source.append( \
897
+ concrete_outputs_for_this_rule_source)
898
+ concrete_outputs_all.extend(concrete_outputs_for_this_rule_source)
899
+
900
+ # TODO(mark): Should verify that at most one of these is specified.
901
+ if int(rule.get('process_outputs_as_sources', False)):
902
+ for output in concrete_outputs_for_this_rule_source:
903
+ AddSourceToTarget(output, type, pbxp, xct)
904
+
905
+ # If the file came from the mac_bundle_resources list or if the rule
906
+ # is marked to process outputs as bundle resource, do so.
907
+ was_mac_bundle_resource = rule_source in tgt_mac_bundle_resources
908
+ if was_mac_bundle_resource or \
909
+ int(rule.get('process_outputs_as_mac_bundle_resources', False)):
910
+ for output in concrete_outputs_for_this_rule_source:
911
+ AddResourceToTarget(output, pbxp, xct)
912
+
913
+ # Do we have a message to print when this rule runs?
914
+ message = rule.get('message')
915
+ if message:
916
+ message = gyp.common.EncodePOSIXShellArgument(message)
917
+ message = ExpandXcodeVariables(message, rule_input_dict)
918
+ messages.append(message)
919
+
920
+ # Turn the list into a string that can be passed to a shell.
921
+ action_string = gyp.common.EncodePOSIXShellList(rule['action'])
922
+
923
+ action = ExpandXcodeVariables(action_string, rule_input_dict)
924
+ actions.append(action)
925
+
926
+ if len(concrete_outputs_all) > 0:
927
+ # TODO(mark): There's a possibilty for collision here. Consider
928
+ # target "t" rule "A_r" and target "t_A" rule "r".
929
+ makefile_name = '%s.make' % re.sub(
930
+ '[^a-zA-Z0-9_]', '_' , '%s_%s' % (target_name, rule['rule_name']))
931
+ makefile_path = os.path.join(xcode_projects[build_file].path,
932
+ makefile_name)
933
+ # TODO(mark): try/close? Write to a temporary file and swap it only
934
+ # if it's got changes?
935
+ makefile = open(makefile_path, 'wb')
936
+
937
+ # make will build the first target in the makefile by default. By
938
+ # convention, it's called "all". List all (or at least one)
939
+ # concrete output for each rule source as a prerequisite of the "all"
940
+ # target.
941
+ makefile.write('all: \\\n')
942
+ for concrete_output_index in \
943
+ xrange(0, len(concrete_outputs_by_rule_source)):
944
+ # Only list the first (index [0]) concrete output of each input
945
+ # in the "all" target. Otherwise, a parallel make (-j > 1) would
946
+ # attempt to process each input multiple times simultaneously.
947
+ # Otherwise, "all" could just contain the entire list of
948
+ # concrete_outputs_all.
949
+ concrete_output = \
950
+ concrete_outputs_by_rule_source[concrete_output_index][0]
951
+ if concrete_output_index == len(concrete_outputs_by_rule_source) - 1:
952
+ eol = ''
953
+ else:
954
+ eol = ' \\'
955
+ makefile.write(' %s%s\n' % (concrete_output, eol))
956
+
957
+ for (rule_source, concrete_outputs, message, action) in \
958
+ zip(rule['rule_sources'], concrete_outputs_by_rule_source,
959
+ messages, actions):
960
+ makefile.write('\n')
961
+
962
+ # Add a rule that declares it can build each concrete output of a
963
+ # rule source. Collect the names of the directories that are
964
+ # required.
965
+ concrete_output_dirs = []
966
+ for concrete_output_index in xrange(0, len(concrete_outputs)):
967
+ concrete_output = concrete_outputs[concrete_output_index]
968
+ if concrete_output_index == 0:
969
+ bol = ''
970
+ else:
971
+ bol = ' '
972
+ makefile.write('%s%s \\\n' % (bol, concrete_output))
973
+
974
+ concrete_output_dir = posixpath.dirname(concrete_output)
975
+ if (concrete_output_dir and
976
+ concrete_output_dir not in concrete_output_dirs):
977
+ concrete_output_dirs.append(concrete_output_dir)
978
+
979
+ makefile.write(' : \\\n')
980
+
981
+ # The prerequisites for this rule are the rule source itself and
982
+ # the set of additional rule inputs, if any.
983
+ prerequisites = [rule_source]
984
+ prerequisites.extend(rule.get('inputs', []))
985
+ for prerequisite_index in xrange(0, len(prerequisites)):
986
+ prerequisite = prerequisites[prerequisite_index]
987
+ if prerequisite_index == len(prerequisites) - 1:
988
+ eol = ''
989
+ else:
990
+ eol = ' \\'
991
+ makefile.write(' %s%s\n' % (prerequisite, eol))
992
+
993
+ # Make sure that output directories exist before executing the rule
994
+ # action.
995
+ if len(concrete_output_dirs) > 0:
996
+ makefile.write('\t@mkdir -p "%s"\n' %
997
+ '" "'.join(concrete_output_dirs))
998
+
999
+ # The rule message and action have already had the necessary variable
1000
+ # substitutions performed.
1001
+ if message:
1002
+ # Mark it with note: so Xcode picks it up in build output.
1003
+ makefile.write('\t@echo note: %s\n' % message)
1004
+ makefile.write('\t%s\n' % action)
1005
+
1006
+ makefile.close()
1007
+
1008
+ # It might be nice to ensure that needed output directories exist
1009
+ # here rather than in each target in the Makefile, but that wouldn't
1010
+ # work if there ever was a concrete output that had an input-dependent
1011
+ # variable anywhere other than in the leaf position.
1012
+
1013
+ # Don't declare any inputPaths or outputPaths. If they're present,
1014
+ # Xcode will provide a slight optimization by only running the script
1015
+ # phase if any output is missing or outdated relative to any input.
1016
+ # Unfortunately, it will also assume that all outputs are touched by
1017
+ # the script, and if the outputs serve as files in a compilation
1018
+ # phase, they will be unconditionally rebuilt. Since make might not
1019
+ # rebuild everything that could be declared here as an output, this
1020
+ # extra compilation activity is unnecessary. With inputPaths and
1021
+ # outputPaths not supplied, make will always be called, but it knows
1022
+ # enough to not do anything when everything is up-to-date.
1023
+
1024
+ # To help speed things up, pass -j COUNT to make so it does some work
1025
+ # in parallel. Don't use ncpus because Xcode will build ncpus targets
1026
+ # in parallel and if each target happens to have a rules step, there
1027
+ # would be ncpus^2 things going. With a machine that has 2 quad-core
1028
+ # Xeons, a build can quickly run out of processes based on
1029
+ # scheduling/other tasks, and randomly failing builds are no good.
1030
+ script = \
1031
+ """JOB_COUNT="$(/usr/sbin/sysctl -n hw.ncpu)"
1032
+ if [ "${JOB_COUNT}" -gt 4 ]; then
1033
+ JOB_COUNT=4
1034
+ fi
1035
+ exec xcrun make -f "${PROJECT_FILE_PATH}/%s" -j "${JOB_COUNT}"
1036
+ exit 1
1037
+ """ % makefile_name
1038
+ ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({
1039
+ 'name': 'Rule "' + rule['rule_name'] + '"',
1040
+ 'shellScript': script,
1041
+ 'showEnvVarsInLog': 0,
1042
+ })
1043
+
1044
+ if support_xct:
1045
+ support_xct.AppendProperty('buildPhases', ssbp)
1046
+ else:
1047
+ # TODO(mark): this assumes too much knowledge of the internals of
1048
+ # xcodeproj_file; some of these smarts should move into xcodeproj_file
1049
+ # itself.
1050
+ xct._properties['buildPhases'].insert(prebuild_index, ssbp)
1051
+ prebuild_index = prebuild_index + 1
1052
+
1053
+ # Extra rule inputs also go into the project file. Concrete outputs were
1054
+ # already added when they were computed.
1055
+ groups = ['inputs', 'inputs_excluded']
1056
+ if skip_excluded_files:
1057
+ groups = [x for x in groups if not x.endswith('_excluded')]
1058
+ for group in groups:
1059
+ for item in rule.get(group, []):
1060
+ pbxp.AddOrGetFileInRootGroup(item)
1061
+
1062
+ # Add "sources".
1063
+ for source in spec.get('sources', []):
1064
+ (source_root, source_extension) = posixpath.splitext(source)
1065
+ if source_extension[1:] not in rules_by_ext:
1066
+ # AddSourceToTarget will add the file to a root group if it's not
1067
+ # already there.
1068
+ AddSourceToTarget(source, type, pbxp, xct)
1069
+ else:
1070
+ pbxp.AddOrGetFileInRootGroup(source)
1071
+
1072
+ # Add "mac_bundle_resources" and "mac_framework_private_headers" if
1073
+ # it's a bundle of any type.
1074
+ if is_bundle:
1075
+ for resource in tgt_mac_bundle_resources:
1076
+ (resource_root, resource_extension) = posixpath.splitext(resource)
1077
+ if resource_extension[1:] not in rules_by_ext:
1078
+ AddResourceToTarget(resource, pbxp, xct)
1079
+ else:
1080
+ pbxp.AddOrGetFileInRootGroup(resource)
1081
+
1082
+ for header in spec.get('mac_framework_private_headers', []):
1083
+ AddHeaderToTarget(header, pbxp, xct, False)
1084
+
1085
+ # Add "mac_framework_headers". These can be valid for both frameworks
1086
+ # and static libraries.
1087
+ if is_bundle or type == 'static_library':
1088
+ for header in spec.get('mac_framework_headers', []):
1089
+ AddHeaderToTarget(header, pbxp, xct, True)
1090
+
1091
+ # Add "copies".
1092
+ pbxcp_dict = {}
1093
+ for copy_group in spec.get('copies', []):
1094
+ dest = copy_group['destination']
1095
+ if dest[0] not in ('/', '$'):
1096
+ # Relative paths are relative to $(SRCROOT).
1097
+ dest = '$(SRCROOT)/' + dest
1098
+
1099
+ # Coalesce multiple "copies" sections in the same target with the same
1100
+ # "destination" property into the same PBXCopyFilesBuildPhase, otherwise
1101
+ # they'll wind up with ID collisions.
1102
+ pbxcp = pbxcp_dict.get(dest, None)
1103
+ if pbxcp is None:
1104
+ pbxcp = gyp.xcodeproj_file.PBXCopyFilesBuildPhase({
1105
+ 'name': 'Copy to ' + copy_group['destination']
1106
+ },
1107
+ parent=xct)
1108
+ pbxcp.SetDestination(dest)
1109
+
1110
+ # TODO(mark): The usual comment about this knowing too much about
1111
+ # gyp.xcodeproj_file internals applies.
1112
+ xct._properties['buildPhases'].insert(prebuild_index, pbxcp)
1113
+
1114
+ pbxcp_dict[dest] = pbxcp
1115
+
1116
+ for file in copy_group['files']:
1117
+ pbxcp.AddFile(file)
1118
+
1119
+ # Excluded files can also go into the project file.
1120
+ if not skip_excluded_files:
1121
+ for key in ['sources', 'mac_bundle_resources', 'mac_framework_headers',
1122
+ 'mac_framework_private_headers']:
1123
+ excluded_key = key + '_excluded'
1124
+ for item in spec.get(excluded_key, []):
1125
+ pbxp.AddOrGetFileInRootGroup(item)
1126
+
1127
+ # So can "inputs" and "outputs" sections of "actions" groups.
1128
+ groups = ['inputs', 'inputs_excluded', 'outputs', 'outputs_excluded']
1129
+ if skip_excluded_files:
1130
+ groups = [x for x in groups if not x.endswith('_excluded')]
1131
+ for action in spec.get('actions', []):
1132
+ for group in groups:
1133
+ for item in action.get(group, []):
1134
+ # Exclude anything in BUILT_PRODUCTS_DIR. They're products, not
1135
+ # sources.
1136
+ if not item.startswith('$(BUILT_PRODUCTS_DIR)/'):
1137
+ pbxp.AddOrGetFileInRootGroup(item)
1138
+
1139
+ for postbuild in spec.get('postbuilds', []):
1140
+ action_string_sh = gyp.common.EncodePOSIXShellList(postbuild['action'])
1141
+ script = 'exec ' + action_string_sh + '\nexit 1\n'
1142
+
1143
+ # Make the postbuild step depend on the output of ld or ar from this
1144
+ # target. Apparently putting the script step after the link step isn't
1145
+ # sufficient to ensure proper ordering in all cases. With an input
1146
+ # declared but no outputs, the script step should run every time, as
1147
+ # desired.
1148
+ ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({
1149
+ 'inputPaths': ['$(BUILT_PRODUCTS_DIR)/$(EXECUTABLE_PATH)'],
1150
+ 'name': 'Postbuild "' + postbuild['postbuild_name'] + '"',
1151
+ 'shellScript': script,
1152
+ 'showEnvVarsInLog': 0,
1153
+ })
1154
+ xct.AppendProperty('buildPhases', ssbp)
1155
+
1156
+ # Add dependencies before libraries, because adding a dependency may imply
1157
+ # adding a library. It's preferable to keep dependencies listed first
1158
+ # during a link phase so that they can override symbols that would
1159
+ # otherwise be provided by libraries, which will usually include system
1160
+ # libraries. On some systems, ld is finicky and even requires the
1161
+ # libraries to be ordered in such a way that unresolved symbols in
1162
+ # earlier-listed libraries may only be resolved by later-listed libraries.
1163
+ # The Mac linker doesn't work that way, but other platforms do, and so
1164
+ # their linker invocations need to be constructed in this way. There's
1165
+ # no compelling reason for Xcode's linker invocations to differ.
1166
+
1167
+ if 'dependencies' in spec:
1168
+ for dependency in spec['dependencies']:
1169
+ xct.AddDependency(xcode_targets[dependency])
1170
+ # The support project also gets the dependencies (in case they are
1171
+ # needed for the actions/rules to work).
1172
+ if support_xct:
1173
+ support_xct.AddDependency(xcode_targets[dependency])
1174
+
1175
+ if 'libraries' in spec:
1176
+ for library in spec['libraries']:
1177
+ xct.FrameworksPhase().AddFile(library)
1178
+ # Add the library's directory to LIBRARY_SEARCH_PATHS if necessary.
1179
+ # I wish Xcode handled this automatically.
1180
+ library_dir = posixpath.dirname(library)
1181
+ if library_dir not in xcode_standard_library_dirs and (
1182
+ not xct.HasBuildSetting(_library_search_paths_var) or
1183
+ library_dir not in xct.GetBuildSetting(_library_search_paths_var)):
1184
+ xct.AppendBuildSetting(_library_search_paths_var, library_dir)
1185
+
1186
+ for configuration_name in configuration_names:
1187
+ configuration = spec['configurations'][configuration_name]
1188
+ xcbc = xct.ConfigurationNamed(configuration_name)
1189
+ for include_dir in configuration.get('mac_framework_dirs', []):
1190
+ xcbc.AppendBuildSetting('FRAMEWORK_SEARCH_PATHS', include_dir)
1191
+ for include_dir in configuration.get('include_dirs', []):
1192
+ xcbc.AppendBuildSetting('HEADER_SEARCH_PATHS', include_dir)
1193
+ for library_dir in configuration.get('library_dirs', []):
1194
+ if library_dir not in xcode_standard_library_dirs and (
1195
+ not xcbc.HasBuildSetting(_library_search_paths_var) or
1196
+ library_dir not in xcbc.GetBuildSetting(_library_search_paths_var)):
1197
+ xcbc.AppendBuildSetting(_library_search_paths_var, library_dir)
1198
+
1199
+ if 'defines' in configuration:
1200
+ for define in configuration['defines']:
1201
+ set_define = EscapeXcodeDefine(define)
1202
+ xcbc.AppendBuildSetting('GCC_PREPROCESSOR_DEFINITIONS', set_define)
1203
+ if 'xcode_settings' in configuration:
1204
+ for xck, xcv in configuration['xcode_settings'].iteritems():
1205
+ xcbc.SetBuildSetting(xck, xcv)
1206
+ if 'xcode_config_file' in configuration:
1207
+ config_ref = pbxp.AddOrGetFileInRootGroup(
1208
+ configuration['xcode_config_file'])
1209
+ xcbc.SetBaseConfiguration(config_ref)
1210
+
1211
+ build_files = []
1212
+ for build_file, build_file_dict in data.iteritems():
1213
+ if build_file.endswith('.gyp'):
1214
+ build_files.append(build_file)
1215
+
1216
+ for build_file in build_files:
1217
+ xcode_projects[build_file].Finalize1(xcode_targets, serialize_all_tests)
1218
+
1219
+ for build_file in build_files:
1220
+ xcode_projects[build_file].Finalize2(xcode_targets,
1221
+ xcode_target_to_target_dict)
1222
+
1223
+ for build_file in build_files:
1224
+ xcode_projects[build_file].Write()