casbin-async-django-orm-adapter 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. async_casbin_adapter/__init__.py +0 -0
  2. async_casbin_adapter/adapter.py +100 -0
  3. async_casbin_adapter/apps.py +24 -0
  4. async_casbin_adapter/enforcer.py +81 -0
  5. async_casbin_adapter/migrations/0001_initial.py +37 -0
  6. async_casbin_adapter/migrations/__init__.py +0 -0
  7. async_casbin_adapter/models.py +48 -0
  8. async_casbin_adapter/utils.py +25 -0
  9. casbin_async_django_orm_adapter-1.0.0.dist-info/METADATA +116 -0
  10. casbin_async_django_orm_adapter-1.0.0.dist-info/RECORD +74 -0
  11. casbin_async_django_orm_adapter-1.0.0.dist-info/WHEEL +5 -0
  12. casbin_async_django_orm_adapter-1.0.0.dist-info/licenses/LICENSE +201 -0
  13. casbin_async_django_orm_adapter-1.0.0.dist-info/top_level.txt +3 -0
  14. node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  15. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +365 -0
  16. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  17. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1272 -0
  18. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  19. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  20. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +152 -0
  21. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +270 -0
  22. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  23. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +704 -0
  24. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py +709 -0
  25. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +173 -0
  26. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +169 -0
  27. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +113 -0
  28. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  29. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  30. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +805 -0
  31. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1172 -0
  32. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1319 -0
  33. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +128 -0
  34. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +104 -0
  35. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +462 -0
  36. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  37. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +56 -0
  38. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2745 -0
  39. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3976 -0
  40. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  41. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2965 -0
  42. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +67 -0
  43. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1391 -0
  44. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +26 -0
  45. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py +3112 -0
  46. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +99 -0
  47. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +767 -0
  48. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1260 -0
  49. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  50. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  51. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +373 -0
  52. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1939 -0
  53. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation_test.py +54 -0
  54. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +303 -0
  55. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3196 -0
  56. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  57. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/__init__.py +15 -0
  58. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_elffile.py +108 -0
  59. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_manylinux.py +252 -0
  60. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_musllinux.py +83 -0
  61. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_parser.py +359 -0
  62. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_structures.py +61 -0
  63. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_tokenizer.py +192 -0
  64. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/markers.py +252 -0
  65. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/metadata.py +825 -0
  66. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/py.typed +0 -0
  67. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/requirements.py +90 -0
  68. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/specifiers.py +1030 -0
  69. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/tags.py +553 -0
  70. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/utils.py +172 -0
  71. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/version.py +563 -0
  72. node_modules/npm/node_modules/node-gyp/gyp/test_gyp.py +261 -0
  73. node_modules/semantic-release-pypi/dist/py/set_version.py +32 -0
  74. node_modules/semantic-release-pypi/dist/py/verify_setup.py +24 -0
@@ -0,0 +1,3112 @@
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
+
6
+ import ast
7
+ import multiprocessing
8
+ import os.path
9
+ import re
10
+ import shlex
11
+ import signal
12
+ import subprocess
13
+ import sys
14
+ import threading
15
+ import traceback
16
+
17
+ from packaging.version import Version
18
+
19
+ import gyp.common
20
+ import gyp.simple_copy
21
+ from gyp.common import GypError, OrderedSet
22
+
23
+ # A list of types that are treated as linkable.
24
+ linkable_types = [
25
+ "executable",
26
+ "shared_library",
27
+ "loadable_module",
28
+ "mac_kernel_extension",
29
+ "windows_driver",
30
+ ]
31
+
32
+ # A list of sections that contain links to other targets.
33
+ dependency_sections = ["dependencies", "export_dependent_settings"]
34
+
35
+ # base_path_sections is a list of sections defined by GYP that contain
36
+ # pathnames. The generators can provide more keys, the two lists are merged
37
+ # into path_sections, but you should call IsPathSection instead of using either
38
+ # list directly.
39
+ base_path_sections = [
40
+ "destination",
41
+ "files",
42
+ "include_dirs",
43
+ "inputs",
44
+ "libraries",
45
+ "outputs",
46
+ "sources",
47
+ ]
48
+ path_sections = set()
49
+
50
+ # These per-process dictionaries are used to cache build file data when loading
51
+ # in parallel mode.
52
+ per_process_data = {}
53
+ per_process_aux_data = {}
54
+
55
+
56
+ def IsPathSection(section):
57
+ # If section ends in one of the '=+?!' characters, it's applied to a section
58
+ # without the trailing characters. '/' is notably absent from this list,
59
+ # because there's no way for a regular expression to be treated as a path.
60
+ while section and section[-1:] in "=+?!":
61
+ section = section[:-1]
62
+
63
+ if section in path_sections:
64
+ return True
65
+
66
+ # Sections matching the regexp '_(dir|file|path)s?$' are also
67
+ # considered PathSections. Using manual string matching since that
68
+ # is much faster than the regexp and this can be called hundreds of
69
+ # thousands of times so micro performance matters.
70
+ if "_" in section:
71
+ tail = section[-6:]
72
+ if tail[-1] == "s":
73
+ tail = tail[:-1]
74
+ if tail[-5:] in ("_file", "_path"):
75
+ return True
76
+ return tail[-4:] == "_dir"
77
+
78
+ return False
79
+
80
+
81
+ # base_non_configuration_keys is a list of key names that belong in the target
82
+ # itself and should not be propagated into its configurations. It is merged
83
+ # with a list that can come from the generator to
84
+ # create non_configuration_keys.
85
+ base_non_configuration_keys = [
86
+ # Sections that must exist inside targets and not configurations.
87
+ "actions",
88
+ "configurations",
89
+ "copies",
90
+ "default_configuration",
91
+ "dependencies",
92
+ "dependencies_original",
93
+ "libraries",
94
+ "postbuilds",
95
+ "product_dir",
96
+ "product_extension",
97
+ "product_name",
98
+ "product_prefix",
99
+ "rules",
100
+ "run_as",
101
+ "sources",
102
+ "standalone_static_library",
103
+ "suppress_wildcard",
104
+ "target_name",
105
+ "toolset",
106
+ "toolsets",
107
+ "type",
108
+ # Sections that can be found inside targets or configurations, but that
109
+ # should not be propagated from targets into their configurations.
110
+ "variables",
111
+ ]
112
+ non_configuration_keys = []
113
+
114
+ # Keys that do not belong inside a configuration dictionary.
115
+ invalid_configuration_keys = [
116
+ "actions",
117
+ "all_dependent_settings",
118
+ "configurations",
119
+ "dependencies",
120
+ "direct_dependent_settings",
121
+ "libraries",
122
+ "link_settings",
123
+ "sources",
124
+ "standalone_static_library",
125
+ "target_name",
126
+ "type",
127
+ ]
128
+
129
+ # Controls whether or not the generator supports multiple toolsets.
130
+ multiple_toolsets = False
131
+
132
+ # Paths for converting filelist paths to output paths: {
133
+ # toplevel,
134
+ # qualified_output_dir,
135
+ # }
136
+ generator_filelist_paths = None
137
+
138
+
139
+ def GetIncludedBuildFiles(build_file_path, aux_data, included=None):
140
+ """Return a list of all build files included into build_file_path.
141
+
142
+ The returned list will contain build_file_path as well as all other files
143
+ that it included, either directly or indirectly. Note that the list may
144
+ contain files that were included into a conditional section that evaluated
145
+ to false and was not merged into build_file_path's dict.
146
+
147
+ aux_data is a dict containing a key for each build file or included build
148
+ file. Those keys provide access to dicts whose "included" keys contain
149
+ lists of all other files included by the build file.
150
+
151
+ included should be left at its default None value by external callers. It
152
+ is used for recursion.
153
+
154
+ The returned list will not contain any duplicate entries. Each build file
155
+ in the list will be relative to the current directory.
156
+ """
157
+
158
+ if included is None:
159
+ included = []
160
+
161
+ if build_file_path in included:
162
+ return included
163
+
164
+ included.append(build_file_path)
165
+
166
+ for included_build_file in aux_data[build_file_path].get("included", []):
167
+ GetIncludedBuildFiles(included_build_file, aux_data, included)
168
+
169
+ return included
170
+
171
+
172
+ def CheckedEval(file_contents):
173
+ """Return the eval of a gyp file.
174
+ The gyp file is restricted to dictionaries and lists only, and
175
+ repeated keys are not allowed.
176
+ Note that this is slower than eval() is.
177
+ """
178
+
179
+ syntax_tree = ast.parse(file_contents)
180
+ assert isinstance(syntax_tree, ast.Module)
181
+ c1 = syntax_tree.body
182
+ assert len(c1) == 1
183
+ c2 = c1[0]
184
+ assert isinstance(c2, ast.Expr)
185
+ return CheckNode(c2.value, [])
186
+
187
+
188
+ def CheckNode(node, keypath):
189
+ if isinstance(node, ast.Dict):
190
+ dict = {}
191
+ for key, value in zip(node.keys, node.values):
192
+ assert isinstance(key, ast.Str)
193
+ key = key.s
194
+ if key in dict:
195
+ raise GypError(
196
+ "Key '"
197
+ + key
198
+ + "' repeated at level "
199
+ + repr(len(keypath) + 1)
200
+ + " with key path '"
201
+ + ".".join(keypath)
202
+ + "'"
203
+ )
204
+ kp = list(keypath) # Make a copy of the list for descending this node.
205
+ kp.append(key)
206
+ dict[key] = CheckNode(value, kp)
207
+ return dict
208
+ elif isinstance(node, ast.List):
209
+ children = []
210
+ for index, child in enumerate(node.elts):
211
+ kp = list(keypath) # Copy list.
212
+ kp.append(repr(index))
213
+ children.append(CheckNode(child, kp))
214
+ return children
215
+ elif isinstance(node, ast.Str):
216
+ return node.s
217
+ else:
218
+ raise TypeError(
219
+ "Unknown AST node at key path '" + ".".join(keypath) + "': " + repr(node)
220
+ )
221
+
222
+
223
+ def LoadOneBuildFile(build_file_path, data, aux_data, includes, is_target, check):
224
+ if build_file_path in data:
225
+ return data[build_file_path]
226
+
227
+ if os.path.exists(build_file_path):
228
+ build_file_contents = open(build_file_path, encoding="utf-8").read()
229
+ else:
230
+ raise GypError(f"{build_file_path} not found (cwd: {os.getcwd()})")
231
+
232
+ build_file_data = None
233
+ try:
234
+ if check:
235
+ build_file_data = CheckedEval(build_file_contents)
236
+ else:
237
+ build_file_data = eval(build_file_contents, {"__builtins__": {}}, None)
238
+ except SyntaxError as e:
239
+ e.filename = build_file_path
240
+ raise
241
+ except Exception as e:
242
+ gyp.common.ExceptionAppend(e, "while reading " + build_file_path)
243
+ raise
244
+
245
+ if not isinstance(build_file_data, dict):
246
+ raise GypError("%s does not evaluate to a dictionary." % build_file_path)
247
+
248
+ data[build_file_path] = build_file_data
249
+ aux_data[build_file_path] = {}
250
+
251
+ # Scan for includes and merge them in.
252
+ if "skip_includes" not in build_file_data or not build_file_data["skip_includes"]:
253
+ try:
254
+ if is_target:
255
+ LoadBuildFileIncludesIntoDict(
256
+ build_file_data, build_file_path, data, aux_data, includes, check
257
+ )
258
+ else:
259
+ LoadBuildFileIncludesIntoDict(
260
+ build_file_data, build_file_path, data, aux_data, None, check
261
+ )
262
+ except Exception as e:
263
+ gyp.common.ExceptionAppend(
264
+ e, "while reading includes of " + build_file_path
265
+ )
266
+ raise
267
+
268
+ return build_file_data
269
+
270
+
271
+ def LoadBuildFileIncludesIntoDict(
272
+ subdict, subdict_path, data, aux_data, includes, check
273
+ ):
274
+ includes_list = []
275
+ if includes is not None:
276
+ includes_list.extend(includes)
277
+ if "includes" in subdict:
278
+ for include in subdict["includes"]:
279
+ # "include" is specified relative to subdict_path, so compute the real
280
+ # path to include by appending the provided "include" to the directory
281
+ # in which subdict_path resides.
282
+ relative_include = os.path.normpath(
283
+ os.path.join(os.path.dirname(subdict_path), include)
284
+ )
285
+ includes_list.append(relative_include)
286
+ # Unhook the includes list, it's no longer needed.
287
+ del subdict["includes"]
288
+
289
+ # Merge in the included files.
290
+ for include in includes_list:
291
+ if "included" not in aux_data[subdict_path]:
292
+ aux_data[subdict_path]["included"] = []
293
+ aux_data[subdict_path]["included"].append(include)
294
+
295
+ gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'", include)
296
+
297
+ MergeDicts(
298
+ subdict,
299
+ LoadOneBuildFile(include, data, aux_data, None, False, check),
300
+ subdict_path,
301
+ include,
302
+ )
303
+
304
+ # Recurse into subdictionaries.
305
+ for k, v in subdict.items():
306
+ if isinstance(v, dict):
307
+ LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, None, check)
308
+ elif isinstance(v, list):
309
+ LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, check)
310
+
311
+
312
+ # This recurses into lists so that it can look for dicts.
313
+ def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, check):
314
+ for item in sublist:
315
+ if isinstance(item, dict):
316
+ LoadBuildFileIncludesIntoDict(
317
+ item, sublist_path, data, aux_data, None, check
318
+ )
319
+ elif isinstance(item, list):
320
+ LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, check)
321
+
322
+
323
+ # Processes toolsets in all the targets. This recurses into condition entries
324
+ # since they can contain toolsets as well.
325
+ def ProcessToolsetsInDict(data):
326
+ if "targets" in data:
327
+ target_list = data["targets"]
328
+ new_target_list = []
329
+ for target in target_list:
330
+ # If this target already has an explicit 'toolset', and no 'toolsets'
331
+ # list, don't modify it further.
332
+ if "toolset" in target and "toolsets" not in target:
333
+ new_target_list.append(target)
334
+ continue
335
+ if multiple_toolsets:
336
+ toolsets = target.get("toolsets", ["target"])
337
+ else:
338
+ toolsets = ["target"]
339
+ # Make sure this 'toolsets' definition is only processed once.
340
+ if "toolsets" in target:
341
+ del target["toolsets"]
342
+ if len(toolsets) > 0:
343
+ # Optimization: only do copies if more than one toolset is specified.
344
+ for build in toolsets[1:]:
345
+ new_target = gyp.simple_copy.deepcopy(target)
346
+ new_target["toolset"] = build
347
+ new_target_list.append(new_target)
348
+ target["toolset"] = toolsets[0]
349
+ new_target_list.append(target)
350
+ data["targets"] = new_target_list
351
+ if "conditions" in data:
352
+ for condition in data["conditions"]:
353
+ if isinstance(condition, list):
354
+ for condition_dict in condition[1:]:
355
+ if isinstance(condition_dict, dict):
356
+ ProcessToolsetsInDict(condition_dict)
357
+
358
+
359
+ # TODO(mark): I don't love this name. It just means that it's going to load
360
+ # a build file that contains targets and is expected to provide a targets dict
361
+ # that contains the targets...
362
+ def LoadTargetBuildFile(
363
+ build_file_path,
364
+ data,
365
+ aux_data,
366
+ variables,
367
+ includes,
368
+ depth,
369
+ check,
370
+ load_dependencies,
371
+ ):
372
+ # If depth is set, predefine the DEPTH variable to be a relative path from
373
+ # this build file's directory to the directory identified by depth.
374
+ if depth:
375
+ # TODO(dglazkov) The backslash/forward-slash replacement at the end is a
376
+ # temporary measure. This should really be addressed by keeping all paths
377
+ # in POSIX until actual project generation.
378
+ d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path))
379
+ if d == "":
380
+ variables["DEPTH"] = "."
381
+ else:
382
+ variables["DEPTH"] = d.replace("\\", "/")
383
+
384
+ # The 'target_build_files' key is only set when loading target build files in
385
+ # the non-parallel code path, where LoadTargetBuildFile is called
386
+ # recursively. In the parallel code path, we don't need to check whether the
387
+ # |build_file_path| has already been loaded, because the 'scheduled' set in
388
+ # ParallelState guarantees that we never load the same |build_file_path|
389
+ # twice.
390
+ if "target_build_files" in data:
391
+ if build_file_path in data["target_build_files"]:
392
+ # Already loaded.
393
+ return False
394
+ data["target_build_files"].add(build_file_path)
395
+
396
+ gyp.DebugOutput(
397
+ gyp.DEBUG_INCLUDES, "Loading Target Build File '%s'", build_file_path
398
+ )
399
+
400
+ build_file_data = LoadOneBuildFile(
401
+ build_file_path, data, aux_data, includes, True, check
402
+ )
403
+
404
+ # Store DEPTH for later use in generators.
405
+ build_file_data["_DEPTH"] = depth
406
+
407
+ # Set up the included_files key indicating which .gyp files contributed to
408
+ # this target dict.
409
+ if "included_files" in build_file_data:
410
+ raise GypError(build_file_path + " must not contain included_files key")
411
+
412
+ included = GetIncludedBuildFiles(build_file_path, aux_data)
413
+ build_file_data["included_files"] = []
414
+ for included_file in included:
415
+ # included_file is relative to the current directory, but it needs to
416
+ # be made relative to build_file_path's directory.
417
+ included_relative = gyp.common.RelativePath(
418
+ included_file, os.path.dirname(build_file_path)
419
+ )
420
+ build_file_data["included_files"].append(included_relative)
421
+
422
+ # Do a first round of toolsets expansion so that conditions can be defined
423
+ # per toolset.
424
+ ProcessToolsetsInDict(build_file_data)
425
+
426
+ # Apply "pre"/"early" variable expansions and condition evaluations.
427
+ ProcessVariablesAndConditionsInDict(
428
+ build_file_data, PHASE_EARLY, variables, build_file_path
429
+ )
430
+
431
+ # Since some toolsets might have been defined conditionally, perform
432
+ # a second round of toolsets expansion now.
433
+ ProcessToolsetsInDict(build_file_data)
434
+
435
+ # Look at each project's target_defaults dict, and merge settings into
436
+ # targets.
437
+ if "target_defaults" in build_file_data:
438
+ if "targets" not in build_file_data:
439
+ raise GypError("Unable to find targets in build file %s" % build_file_path)
440
+
441
+ index = 0
442
+ while index < len(build_file_data["targets"]):
443
+ # This procedure needs to give the impression that target_defaults is
444
+ # used as defaults, and the individual targets inherit from that.
445
+ # The individual targets need to be merged into the defaults. Make
446
+ # a deep copy of the defaults for each target, merge the target dict
447
+ # as found in the input file into that copy, and then hook up the
448
+ # copy with the target-specific data merged into it as the replacement
449
+ # target dict.
450
+ old_target_dict = build_file_data["targets"][index]
451
+ new_target_dict = gyp.simple_copy.deepcopy(
452
+ build_file_data["target_defaults"]
453
+ )
454
+ MergeDicts(
455
+ new_target_dict, old_target_dict, build_file_path, build_file_path
456
+ )
457
+ build_file_data["targets"][index] = new_target_dict
458
+ index += 1
459
+
460
+ # No longer needed.
461
+ del build_file_data["target_defaults"]
462
+
463
+ # Look for dependencies. This means that dependency resolution occurs
464
+ # after "pre" conditionals and variable expansion, but before "post" -
465
+ # in other words, you can't put a "dependencies" section inside a "post"
466
+ # conditional within a target.
467
+
468
+ dependencies = []
469
+ if "targets" in build_file_data:
470
+ for target_dict in build_file_data["targets"]:
471
+ if "dependencies" not in target_dict:
472
+ continue
473
+ for dependency in target_dict["dependencies"]:
474
+ dependencies.append(
475
+ gyp.common.ResolveTarget(build_file_path, dependency, None)[0]
476
+ )
477
+
478
+ if load_dependencies:
479
+ for dependency in dependencies:
480
+ try:
481
+ LoadTargetBuildFile(
482
+ dependency,
483
+ data,
484
+ aux_data,
485
+ variables,
486
+ includes,
487
+ depth,
488
+ check,
489
+ load_dependencies,
490
+ )
491
+ except Exception as e:
492
+ gyp.common.ExceptionAppend(
493
+ e, "while loading dependencies of %s" % build_file_path
494
+ )
495
+ raise
496
+ else:
497
+ return (build_file_path, dependencies)
498
+
499
+
500
+ def CallLoadTargetBuildFile(
501
+ global_flags,
502
+ build_file_path,
503
+ variables,
504
+ includes,
505
+ depth,
506
+ check,
507
+ generator_input_info,
508
+ ):
509
+ """Wrapper around LoadTargetBuildFile for parallel processing.
510
+
511
+ This wrapper is used when LoadTargetBuildFile is executed in
512
+ a worker process.
513
+ """
514
+
515
+ try:
516
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
517
+
518
+ # Apply globals so that the worker process behaves the same.
519
+ for key, value in global_flags.items():
520
+ globals()[key] = value
521
+
522
+ SetGeneratorGlobals(generator_input_info)
523
+ result = LoadTargetBuildFile(
524
+ build_file_path,
525
+ per_process_data,
526
+ per_process_aux_data,
527
+ variables,
528
+ includes,
529
+ depth,
530
+ check,
531
+ False,
532
+ )
533
+ if not result:
534
+ return result
535
+
536
+ (build_file_path, dependencies) = result
537
+
538
+ # We can safely pop the build_file_data from per_process_data because it
539
+ # will never be referenced by this process again, so we don't need to keep
540
+ # it in the cache.
541
+ build_file_data = per_process_data.pop(build_file_path)
542
+
543
+ # This gets serialized and sent back to the main process via a pipe.
544
+ # It's handled in LoadTargetBuildFileCallback.
545
+ return (build_file_path, build_file_data, dependencies)
546
+ except GypError as e:
547
+ sys.stderr.write("gyp: %s\n" % e)
548
+ return None
549
+ except Exception as e:
550
+ print("Exception:", e, file=sys.stderr)
551
+ print(traceback.format_exc(), file=sys.stderr)
552
+ return None
553
+
554
+
555
+ class ParallelProcessingError(Exception):
556
+ pass
557
+
558
+
559
+ class ParallelState:
560
+ """Class to keep track of state when processing input files in parallel.
561
+
562
+ If build files are loaded in parallel, use this to keep track of
563
+ state during farming out and processing parallel jobs. It's stored
564
+ in a global so that the callback function can have access to it.
565
+ """
566
+
567
+ def __init__(self):
568
+ # The multiprocessing pool.
569
+ self.pool = None
570
+ # The condition variable used to protect this object and notify
571
+ # the main loop when there might be more data to process.
572
+ self.condition = None
573
+ # The "data" dict that was passed to LoadTargetBuildFileParallel
574
+ self.data = None
575
+ # The number of parallel calls outstanding; decremented when a response
576
+ # was received.
577
+ self.pending = 0
578
+ # The set of all build files that have been scheduled, so we don't
579
+ # schedule the same one twice.
580
+ self.scheduled = set()
581
+ # A list of dependency build file paths that haven't been scheduled yet.
582
+ self.dependencies = []
583
+ # Flag to indicate if there was an error in a child process.
584
+ self.error = False
585
+
586
+ def LoadTargetBuildFileCallback(self, result):
587
+ """Handle the results of running LoadTargetBuildFile in another process.
588
+ """
589
+ self.condition.acquire()
590
+ if not result:
591
+ self.error = True
592
+ self.condition.notify()
593
+ self.condition.release()
594
+ return
595
+ (build_file_path0, build_file_data0, dependencies0) = result
596
+ self.data[build_file_path0] = build_file_data0
597
+ self.data["target_build_files"].add(build_file_path0)
598
+ for new_dependency in dependencies0:
599
+ if new_dependency not in self.scheduled:
600
+ self.scheduled.add(new_dependency)
601
+ self.dependencies.append(new_dependency)
602
+ self.pending -= 1
603
+ self.condition.notify()
604
+ self.condition.release()
605
+
606
+
607
+ def LoadTargetBuildFilesParallel(
608
+ build_files, data, variables, includes, depth, check, generator_input_info
609
+ ):
610
+ parallel_state = ParallelState()
611
+ parallel_state.condition = threading.Condition()
612
+ # Make copies of the build_files argument that we can modify while working.
613
+ parallel_state.dependencies = list(build_files)
614
+ parallel_state.scheduled = set(build_files)
615
+ parallel_state.pending = 0
616
+ parallel_state.data = data
617
+
618
+ try:
619
+ parallel_state.condition.acquire()
620
+ while parallel_state.dependencies or parallel_state.pending:
621
+ if parallel_state.error:
622
+ break
623
+ if not parallel_state.dependencies:
624
+ parallel_state.condition.wait()
625
+ continue
626
+
627
+ dependency = parallel_state.dependencies.pop()
628
+
629
+ parallel_state.pending += 1
630
+ global_flags = {
631
+ "path_sections": globals()["path_sections"],
632
+ "non_configuration_keys": globals()["non_configuration_keys"],
633
+ "multiple_toolsets": globals()["multiple_toolsets"],
634
+ }
635
+
636
+ if not parallel_state.pool:
637
+ parallel_state.pool = multiprocessing.Pool(multiprocessing.cpu_count())
638
+ parallel_state.pool.apply_async(
639
+ CallLoadTargetBuildFile,
640
+ args=(
641
+ global_flags,
642
+ dependency,
643
+ variables,
644
+ includes,
645
+ depth,
646
+ check,
647
+ generator_input_info,
648
+ ),
649
+ callback=parallel_state.LoadTargetBuildFileCallback,
650
+ )
651
+ except KeyboardInterrupt as e:
652
+ parallel_state.pool.terminate()
653
+ raise e
654
+
655
+ parallel_state.condition.release()
656
+
657
+ parallel_state.pool.close()
658
+ parallel_state.pool.join()
659
+ parallel_state.pool = None
660
+
661
+ if parallel_state.error:
662
+ sys.exit(1)
663
+
664
+
665
+ # Look for the bracket that matches the first bracket seen in a
666
+ # string, and return the start and end as a tuple. For example, if
667
+ # the input is something like "<(foo <(bar)) blah", then it would
668
+ # return (1, 13), indicating the entire string except for the leading
669
+ # "<" and trailing " blah".
670
+ LBRACKETS = set("{[(")
671
+ BRACKETS = {"}": "{", "]": "[", ")": "("}
672
+
673
+
674
+ def FindEnclosingBracketGroup(input_str):
675
+ stack = []
676
+ start = -1
677
+ for index, char in enumerate(input_str):
678
+ if char in LBRACKETS:
679
+ stack.append(char)
680
+ if start == -1:
681
+ start = index
682
+ elif char in BRACKETS:
683
+ if not stack:
684
+ return (-1, -1)
685
+ if stack.pop() != BRACKETS[char]:
686
+ return (-1, -1)
687
+ if not stack:
688
+ return (start, index + 1)
689
+ return (-1, -1)
690
+
691
+
692
+ def IsStrCanonicalInt(string):
693
+ """Returns True if |string| is in its canonical integer form.
694
+
695
+ The canonical form is such that str(int(string)) == string.
696
+ """
697
+ if isinstance(string, str):
698
+ # This function is called a lot so for maximum performance, avoid
699
+ # involving regexps which would otherwise make the code much
700
+ # shorter. Regexps would need twice the time of this function.
701
+ if string:
702
+ if string == "0":
703
+ return True
704
+ if string[0] == "-":
705
+ string = string[1:]
706
+ if not string:
707
+ return False
708
+ if "1" <= string[0] <= "9":
709
+ return string.isdigit()
710
+
711
+ return False
712
+
713
+
714
+ # This matches things like "<(asdf)", "<!(cmd)", "<!@(cmd)", "<|(list)",
715
+ # "<!interpreter(arguments)", "<([list])", and even "<([)" and "<(<())".
716
+ # In the last case, the inner "<()" is captured in match['content'].
717
+ early_variable_re = re.compile(
718
+ r"(?P<replace>(?P<type><(?:(?:!?@?)|\|)?)"
719
+ r"(?P<command_string>[-a-zA-Z0-9_.]+)?"
720
+ r"\((?P<is_array>\s*\[?)"
721
+ r"(?P<content>.*?)(\]?)\))"
722
+ )
723
+
724
+ # This matches the same as early_variable_re, but with '>' instead of '<'.
725
+ late_variable_re = re.compile(
726
+ r"(?P<replace>(?P<type>>(?:(?:!?@?)|\|)?)"
727
+ r"(?P<command_string>[-a-zA-Z0-9_.]+)?"
728
+ r"\((?P<is_array>\s*\[?)"
729
+ r"(?P<content>.*?)(\]?)\))"
730
+ )
731
+
732
+ # This matches the same as early_variable_re, but with '^' instead of '<'.
733
+ latelate_variable_re = re.compile(
734
+ r"(?P<replace>(?P<type>[\^](?:(?:!?@?)|\|)?)"
735
+ r"(?P<command_string>[-a-zA-Z0-9_.]+)?"
736
+ r"\((?P<is_array>\s*\[?)"
737
+ r"(?P<content>.*?)(\]?)\))"
738
+ )
739
+
740
+ # Global cache of results from running commands so they don't have to be run
741
+ # more then once.
742
+ cached_command_results = {}
743
+
744
+
745
+ def FixupPlatformCommand(cmd):
746
+ if sys.platform == "win32":
747
+ if isinstance(cmd, list):
748
+ cmd = [re.sub("^cat ", "type ", cmd[0])] + cmd[1:]
749
+ else:
750
+ cmd = re.sub("^cat ", "type ", cmd)
751
+ return cmd
752
+
753
+
754
+ PHASE_EARLY = 0
755
+ PHASE_LATE = 1
756
+ PHASE_LATELATE = 2
757
+
758
+
759
+ def ExpandVariables(input, phase, variables, build_file):
760
+ # Look for the pattern that gets expanded into variables
761
+ if phase == PHASE_EARLY:
762
+ variable_re = early_variable_re
763
+ expansion_symbol = "<"
764
+ elif phase == PHASE_LATE:
765
+ variable_re = late_variable_re
766
+ expansion_symbol = ">"
767
+ elif phase == PHASE_LATELATE:
768
+ variable_re = latelate_variable_re
769
+ expansion_symbol = "^"
770
+ else:
771
+ assert False
772
+
773
+ input_str = str(input)
774
+ if IsStrCanonicalInt(input_str):
775
+ return int(input_str)
776
+
777
+ # Do a quick scan to determine if an expensive regex search is warranted.
778
+ if expansion_symbol not in input_str:
779
+ return input_str
780
+
781
+ # Get the entire list of matches as a list of MatchObject instances.
782
+ # (using findall here would return strings instead of MatchObjects).
783
+ matches = list(variable_re.finditer(input_str))
784
+ if not matches:
785
+ return input_str
786
+
787
+ output = input_str
788
+ # Reverse the list of matches so that replacements are done right-to-left.
789
+ # That ensures that earlier replacements won't mess up the string in a
790
+ # way that causes later calls to find the earlier substituted text instead
791
+ # of what's intended for replacement.
792
+ matches.reverse()
793
+ for match_group in matches:
794
+ match = match_group.groupdict()
795
+ gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %r", match)
796
+ # match['replace'] is the substring to look for, match['type']
797
+ # is the character code for the replacement type (< > <! >! <| >| <@
798
+ # >@ <!@ >!@), match['is_array'] contains a '[' for command
799
+ # arrays, and match['content'] is the name of the variable (< >)
800
+ # or command to run (<! >!). match['command_string'] is an optional
801
+ # command string. Currently, only 'pymod_do_main' is supported.
802
+
803
+ # run_command is true if a ! variant is used.
804
+ run_command = "!" in match["type"]
805
+ command_string = match["command_string"]
806
+
807
+ # file_list is true if a | variant is used.
808
+ file_list = "|" in match["type"]
809
+
810
+ # Capture these now so we can adjust them later.
811
+ replace_start = match_group.start("replace")
812
+ replace_end = match_group.end("replace")
813
+
814
+ # Find the ending paren, and re-evaluate the contained string.
815
+ (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:])
816
+
817
+ # Adjust the replacement range to match the entire command
818
+ # found by FindEnclosingBracketGroup (since the variable_re
819
+ # probably doesn't match the entire command if it contained
820
+ # nested variables).
821
+ replace_end = replace_start + c_end
822
+
823
+ # Find the "real" replacement, matching the appropriate closing
824
+ # paren, and adjust the replacement start and end.
825
+ replacement = input_str[replace_start:replace_end]
826
+
827
+ # Figure out what the contents of the variable parens are.
828
+ contents_start = replace_start + c_start + 1
829
+ contents_end = replace_end - 1
830
+ contents = input_str[contents_start:contents_end]
831
+
832
+ # Do filter substitution now for <|().
833
+ # Admittedly, this is different than the evaluation order in other
834
+ # contexts. However, since filtration has no chance to run on <|(),
835
+ # this seems like the only obvious way to give them access to filters.
836
+ if file_list:
837
+ processed_variables = gyp.simple_copy.deepcopy(variables)
838
+ ProcessListFiltersInDict(contents, processed_variables)
839
+ # Recurse to expand variables in the contents
840
+ contents = ExpandVariables(contents, phase, processed_variables, build_file)
841
+ else:
842
+ # Recurse to expand variables in the contents
843
+ contents = ExpandVariables(contents, phase, variables, build_file)
844
+
845
+ # Strip off leading/trailing whitespace so that variable matches are
846
+ # simpler below (and because they are rarely needed).
847
+ contents = contents.strip()
848
+
849
+ # expand_to_list is true if an @ variant is used. In that case,
850
+ # the expansion should result in a list. Note that the caller
851
+ # is to be expecting a list in return, and not all callers do
852
+ # because not all are working in list context. Also, for list
853
+ # expansions, there can be no other text besides the variable
854
+ # expansion in the input string.
855
+ expand_to_list = "@" in match["type"] and input_str == replacement
856
+
857
+ if run_command or file_list:
858
+ # Find the build file's directory, so commands can be run or file lists
859
+ # generated relative to it.
860
+ build_file_dir = os.path.dirname(build_file)
861
+ if build_file_dir == "" and not file_list:
862
+ # If build_file is just a leaf filename indicating a file in the
863
+ # current directory, build_file_dir might be an empty string. Set
864
+ # it to None to signal to subprocess.Popen that it should run the
865
+ # command in the current directory.
866
+ build_file_dir = None
867
+
868
+ # Support <|(listfile.txt ...) which generates a file
869
+ # containing items from a gyp list, generated at gyp time.
870
+ # This works around actions/rules which have more inputs than will
871
+ # fit on the command line.
872
+ if file_list:
873
+ contents_list = (contents if isinstance(contents, list)
874
+ else contents.split(" "))
875
+ replacement = contents_list[0]
876
+ if os.path.isabs(replacement):
877
+ raise GypError('| cannot handle absolute paths, got "%s"' % replacement)
878
+
879
+ if not generator_filelist_paths:
880
+ path = os.path.join(build_file_dir, replacement)
881
+ else:
882
+ if os.path.isabs(build_file_dir):
883
+ toplevel = generator_filelist_paths["toplevel"]
884
+ rel_build_file_dir = gyp.common.RelativePath(
885
+ build_file_dir, toplevel
886
+ )
887
+ else:
888
+ rel_build_file_dir = build_file_dir
889
+ qualified_out_dir = generator_filelist_paths["qualified_out_dir"]
890
+ path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement)
891
+ gyp.common.EnsureDirExists(path)
892
+
893
+ replacement = gyp.common.RelativePath(path, build_file_dir)
894
+ f = gyp.common.WriteOnDiff(path)
895
+ for i in contents_list[1:]:
896
+ f.write("%s\n" % i)
897
+ f.close()
898
+
899
+ elif run_command:
900
+ use_shell = True
901
+ if match["is_array"]:
902
+ contents = eval(contents)
903
+ use_shell = False
904
+
905
+ # Check for a cached value to avoid executing commands, or generating
906
+ # file lists more than once. The cache key contains the command to be
907
+ # run as well as the directory to run it from, to account for commands
908
+ # that depend on their current directory.
909
+ # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory,
910
+ # someone could author a set of GYP files where each time the command
911
+ # is invoked it produces different output by design. When the need
912
+ # arises, the syntax should be extended to support no caching off a
913
+ # command's output so it is run every time.
914
+ cache_key = (str(contents), build_file_dir)
915
+ cached_value = cached_command_results.get(cache_key, None)
916
+ if cached_value is None:
917
+ gyp.DebugOutput(
918
+ gyp.DEBUG_VARIABLES,
919
+ "Executing command '%s' in directory '%s'",
920
+ contents,
921
+ build_file_dir,
922
+ )
923
+
924
+ replacement = ""
925
+
926
+ if command_string == "pymod_do_main":
927
+ # <!pymod_do_main(modulename param eters) loads |modulename| as a
928
+ # python module and then calls that module's DoMain() function,
929
+ # passing ["param", "eters"] as a single list argument. For modules
930
+ # that don't load quickly, this can be faster than
931
+ # <!(python modulename param eters). Do this in |build_file_dir|.
932
+ oldwd = os.getcwd() # Python doesn't like os.open('.'): no fchdir.
933
+ if build_file_dir: # build_file_dir may be None (see above).
934
+ os.chdir(build_file_dir)
935
+ sys.path.append(os.getcwd())
936
+ try:
937
+
938
+ parsed_contents = shlex.split(contents)
939
+ try:
940
+ py_module = __import__(parsed_contents[0])
941
+ except ImportError as e:
942
+ raise GypError(
943
+ "Error importing pymod_do_main"
944
+ "module (%s): %s" % (parsed_contents[0], e)
945
+ )
946
+ replacement = str(
947
+ py_module.DoMain(parsed_contents[1:])
948
+ ).rstrip()
949
+ finally:
950
+ sys.path.pop()
951
+ os.chdir(oldwd)
952
+ assert replacement is not None
953
+ elif command_string:
954
+ raise GypError(
955
+ "Unknown command string '%s' in '%s'."
956
+ % (command_string, contents)
957
+ )
958
+ else:
959
+ # Fix up command with platform specific workarounds.
960
+ contents = FixupPlatformCommand(contents)
961
+ try:
962
+ # stderr will be printed no matter what
963
+ result = subprocess.run(
964
+ contents,
965
+ stdout=subprocess.PIPE,
966
+ shell=use_shell,
967
+ cwd=build_file_dir,
968
+ check=False
969
+ )
970
+ except Exception as e:
971
+ raise GypError(
972
+ "%s while executing command '%s' in %s"
973
+ % (e, contents, build_file)
974
+ )
975
+
976
+ if result.returncode > 0:
977
+ raise GypError(
978
+ "Call to '%s' returned exit status %d while in %s."
979
+ % (contents, result.returncode, build_file)
980
+ )
981
+ replacement = result.stdout.decode("utf-8").rstrip()
982
+
983
+ cached_command_results[cache_key] = replacement
984
+ else:
985
+ gyp.DebugOutput(
986
+ gyp.DEBUG_VARIABLES,
987
+ "Had cache value for command '%s' in directory '%s'",
988
+ contents,
989
+ build_file_dir,
990
+ )
991
+ replacement = cached_value
992
+
993
+ elif contents not in variables:
994
+ if contents[-1] in ["!", "/"]:
995
+ # In order to allow cross-compiles (nacl) to happen more naturally,
996
+ # we will allow references to >(sources/) etc. to resolve to
997
+ # and empty list if undefined. This allows actions to:
998
+ # 'action!': [
999
+ # '>@(_sources!)',
1000
+ # ],
1001
+ # 'action/': [
1002
+ # '>@(_sources/)',
1003
+ # ],
1004
+ replacement = []
1005
+ else:
1006
+ raise GypError(
1007
+ "Undefined variable " + contents + " in " + build_file
1008
+ )
1009
+ else:
1010
+ replacement = variables[contents]
1011
+
1012
+ if isinstance(replacement, bytes) and not isinstance(replacement, str):
1013
+ replacement = replacement.decode("utf-8") # done on Python 3 only
1014
+ if isinstance(replacement, list):
1015
+ for item in replacement:
1016
+ if isinstance(item, bytes) and not isinstance(item, str):
1017
+ item = item.decode("utf-8") # done on Python 3 only
1018
+ if not contents[-1] == "/" and type(item) not in (str, int):
1019
+ raise GypError(
1020
+ "Variable "
1021
+ + contents
1022
+ + " must expand to a string or list of strings; "
1023
+ + "list contains a "
1024
+ + item.__class__.__name__
1025
+ )
1026
+ # Run through the list and handle variable expansions in it. Since
1027
+ # the list is guaranteed not to contain dicts, this won't do anything
1028
+ # with conditions sections.
1029
+ ProcessVariablesAndConditionsInList(
1030
+ replacement, phase, variables, build_file
1031
+ )
1032
+ elif type(replacement) not in (str, int):
1033
+ raise GypError(
1034
+ "Variable "
1035
+ + contents
1036
+ + " must expand to a string or list of strings; "
1037
+ + "found a "
1038
+ + replacement.__class__.__name__
1039
+ )
1040
+
1041
+ if expand_to_list:
1042
+ # Expanding in list context. It's guaranteed that there's only one
1043
+ # replacement to do in |input_str| and that it's this replacement. See
1044
+ # above.
1045
+ if isinstance(replacement, list):
1046
+ # If it's already a list, make a copy.
1047
+ output = replacement[:]
1048
+ else:
1049
+ # Split it the same way sh would split arguments.
1050
+ output = shlex.split(str(replacement))
1051
+ else:
1052
+ # Expanding in string context.
1053
+ encoded_replacement = ""
1054
+ if isinstance(replacement, list):
1055
+ # When expanding a list into string context, turn the list items
1056
+ # into a string in a way that will work with a subprocess call.
1057
+ #
1058
+ # TODO(mark): This isn't completely correct. This should
1059
+ # call a generator-provided function that observes the
1060
+ # proper list-to-argument quoting rules on a specific
1061
+ # platform instead of just calling the POSIX encoding
1062
+ # routine.
1063
+ encoded_replacement = gyp.common.EncodePOSIXShellList(replacement)
1064
+ else:
1065
+ encoded_replacement = replacement
1066
+
1067
+ output = (
1068
+ output[:replace_start] + str(encoded_replacement) + output[replace_end:]
1069
+ )
1070
+ # Prepare for the next match iteration.
1071
+ input_str = output
1072
+
1073
+ if output == input:
1074
+ gyp.DebugOutput(
1075
+ gyp.DEBUG_VARIABLES,
1076
+ "Found only identity matches on %r, avoiding infinite recursion.",
1077
+ output,
1078
+ )
1079
+ else:
1080
+ # Look for more matches now that we've replaced some, to deal with
1081
+ # expanding local variables (variables defined in the same
1082
+ # variables block as this one).
1083
+ gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %r, recursing.", output)
1084
+ if isinstance(output, list):
1085
+ if output and isinstance(output[0], list):
1086
+ # Leave output alone if it's a list of lists.
1087
+ # We don't want such lists to be stringified.
1088
+ pass
1089
+ else:
1090
+ new_output = []
1091
+ for item in output:
1092
+ new_output.append(
1093
+ ExpandVariables(item, phase, variables, build_file)
1094
+ )
1095
+ output = new_output
1096
+ else:
1097
+ output = ExpandVariables(output, phase, variables, build_file)
1098
+
1099
+ # Convert all strings that are canonically-represented integers into integers.
1100
+ if isinstance(output, list):
1101
+ for index, outstr in enumerate(output):
1102
+ if IsStrCanonicalInt(outstr):
1103
+ output[index] = int(outstr)
1104
+ elif IsStrCanonicalInt(output):
1105
+ output = int(output)
1106
+
1107
+ return output
1108
+
1109
+
1110
+ # The same condition is often evaluated over and over again so it
1111
+ # makes sense to cache as much as possible between evaluations.
1112
+ cached_conditions_asts = {}
1113
+
1114
+
1115
+ def EvalCondition(condition, conditions_key, phase, variables, build_file):
1116
+ """Returns the dict that should be used or None if the result was
1117
+ that nothing should be used."""
1118
+ if not isinstance(condition, list):
1119
+ raise GypError(conditions_key + " must be a list")
1120
+ if len(condition) < 2:
1121
+ # It's possible that condition[0] won't work in which case this
1122
+ # attempt will raise its own IndexError. That's probably fine.
1123
+ raise GypError(
1124
+ conditions_key
1125
+ + " "
1126
+ + condition[0]
1127
+ + " must be at least length 2, not "
1128
+ + str(len(condition))
1129
+ )
1130
+
1131
+ i = 0
1132
+ result = None
1133
+ while i < len(condition):
1134
+ cond_expr = condition[i]
1135
+ true_dict = condition[i + 1]
1136
+ if not isinstance(true_dict, dict):
1137
+ raise GypError(
1138
+ f"{conditions_key} {cond_expr} must be followed by a dictionary, "
1139
+ f"not {type(true_dict)}"
1140
+ )
1141
+ if len(condition) > i + 2 and isinstance(condition[i + 2], dict):
1142
+ false_dict = condition[i + 2]
1143
+ i = i + 3
1144
+ if i != len(condition):
1145
+ raise GypError(
1146
+ f"{conditions_key} {cond_expr} has "
1147
+ f"{len(condition) - i} unexpected trailing items"
1148
+ )
1149
+ else:
1150
+ false_dict = None
1151
+ i = i + 2
1152
+ if result is None:
1153
+ result = EvalSingleCondition(
1154
+ cond_expr, true_dict, false_dict, phase, variables, build_file
1155
+ )
1156
+
1157
+ return result
1158
+
1159
+
1160
+ def EvalSingleCondition(cond_expr, true_dict, false_dict, phase, variables, build_file):
1161
+ """Returns true_dict if cond_expr evaluates to true, and false_dict
1162
+ otherwise."""
1163
+ # Do expansions on the condition itself. Since the condition can naturally
1164
+ # contain variable references without needing to resort to GYP expansion
1165
+ # syntax, this is of dubious value for variables, but someone might want to
1166
+ # use a command expansion directly inside a condition.
1167
+ cond_expr_expanded = ExpandVariables(cond_expr, phase, variables, build_file)
1168
+ if type(cond_expr_expanded) not in (str, int):
1169
+ raise ValueError(
1170
+ "Variable expansion in this context permits str and int "
1171
+ + "only, found "
1172
+ + cond_expr_expanded.__class__.__name__
1173
+ )
1174
+
1175
+ try:
1176
+ if cond_expr_expanded in cached_conditions_asts:
1177
+ ast_code = cached_conditions_asts[cond_expr_expanded]
1178
+ else:
1179
+ ast_code = compile(cond_expr_expanded, "<string>", "eval")
1180
+ cached_conditions_asts[cond_expr_expanded] = ast_code
1181
+ env = {"__builtins__": {}, "v": Version}
1182
+ if eval(ast_code, env, variables):
1183
+ return true_dict
1184
+ return false_dict
1185
+ except SyntaxError as e:
1186
+ syntax_error = SyntaxError(
1187
+ "%s while evaluating condition '%s' in %s "
1188
+ "at character %d." % (str(e.args[0]), e.text, build_file, e.offset),
1189
+ e.filename,
1190
+ e.lineno,
1191
+ e.offset,
1192
+ e.text,
1193
+ )
1194
+ raise syntax_error
1195
+ except NameError as e:
1196
+ gyp.common.ExceptionAppend(
1197
+ e,
1198
+ f"while evaluating condition '{cond_expr_expanded}' in {build_file}",
1199
+ )
1200
+ raise GypError(e)
1201
+
1202
+
1203
+ def ProcessConditionsInDict(the_dict, phase, variables, build_file):
1204
+ # Process a 'conditions' or 'target_conditions' section in the_dict,
1205
+ # depending on phase.
1206
+ # early -> conditions
1207
+ # late -> target_conditions
1208
+ # latelate -> no conditions
1209
+ #
1210
+ # Each item in a conditions list consists of cond_expr, a string expression
1211
+ # evaluated as the condition, and true_dict, a dict that will be merged into
1212
+ # the_dict if cond_expr evaluates to true. Optionally, a third item,
1213
+ # false_dict, may be present. false_dict is merged into the_dict if
1214
+ # cond_expr evaluates to false.
1215
+ #
1216
+ # Any dict merged into the_dict will be recursively processed for nested
1217
+ # conditionals and other expansions, also according to phase, immediately
1218
+ # prior to being merged.
1219
+
1220
+ if phase == PHASE_EARLY:
1221
+ conditions_key = "conditions"
1222
+ elif phase == PHASE_LATE:
1223
+ conditions_key = "target_conditions"
1224
+ elif phase == PHASE_LATELATE:
1225
+ return
1226
+ else:
1227
+ assert False
1228
+
1229
+ if conditions_key not in the_dict:
1230
+ return
1231
+
1232
+ conditions_list = the_dict[conditions_key]
1233
+ # Unhook the conditions list, it's no longer needed.
1234
+ del the_dict[conditions_key]
1235
+
1236
+ for condition in conditions_list:
1237
+ merge_dict = EvalCondition(
1238
+ condition, conditions_key, phase, variables, build_file
1239
+ )
1240
+
1241
+ if merge_dict is not None:
1242
+ # Expand variables and nested conditionals in the merge_dict before
1243
+ # merging it.
1244
+ ProcessVariablesAndConditionsInDict(
1245
+ merge_dict, phase, variables, build_file
1246
+ )
1247
+
1248
+ MergeDicts(the_dict, merge_dict, build_file, build_file)
1249
+
1250
+
1251
+ def LoadAutomaticVariablesFromDict(variables, the_dict):
1252
+ # Any keys with plain string values in the_dict become automatic variables.
1253
+ # The variable name is the key name with a "_" character prepended.
1254
+ for key, value in the_dict.items():
1255
+ if type(value) in (str, int, list):
1256
+ variables["_" + key] = value
1257
+
1258
+
1259
+ def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key):
1260
+ # Any keys in the_dict's "variables" dict, if it has one, becomes a
1261
+ # variable. The variable name is the key name in the "variables" dict.
1262
+ # Variables that end with the % character are set only if they are unset in
1263
+ # the variables dict. the_dict_key is the name of the key that accesses
1264
+ # the_dict in the_dict's parent dict. If the_dict's parent is not a dict
1265
+ # (it could be a list or it could be parentless because it is a root dict),
1266
+ # the_dict_key will be None.
1267
+ for key, value in the_dict.get("variables", {}).items():
1268
+ if type(value) not in (str, int, list):
1269
+ continue
1270
+
1271
+ if key.endswith("%"):
1272
+ variable_name = key[:-1]
1273
+ if variable_name in variables:
1274
+ # If the variable is already set, don't set it.
1275
+ continue
1276
+ if the_dict_key == "variables" and variable_name in the_dict:
1277
+ # If the variable is set without a % in the_dict, and the_dict is a
1278
+ # variables dict (making |variables| a variables sub-dict of a
1279
+ # variables dict), use the_dict's definition.
1280
+ value = the_dict[variable_name]
1281
+ else:
1282
+ variable_name = key
1283
+
1284
+ variables[variable_name] = value
1285
+
1286
+
1287
+ def ProcessVariablesAndConditionsInDict(
1288
+ the_dict, phase, variables_in, build_file, the_dict_key=None
1289
+ ):
1290
+ """Handle all variable and command expansion and conditional evaluation.
1291
+
1292
+ This function is the public entry point for all variable expansions and
1293
+ conditional evaluations. The variables_in dictionary will not be modified
1294
+ by this function.
1295
+ """
1296
+
1297
+ # Make a copy of the variables_in dict that can be modified during the
1298
+ # loading of automatics and the loading of the variables dict.
1299
+ variables = variables_in.copy()
1300
+ LoadAutomaticVariablesFromDict(variables, the_dict)
1301
+
1302
+ if "variables" in the_dict:
1303
+ # Make sure all the local variables are added to the variables
1304
+ # list before we process them so that you can reference one
1305
+ # variable from another. They will be fully expanded by recursion
1306
+ # in ExpandVariables.
1307
+ for key, value in the_dict["variables"].items():
1308
+ variables[key] = value
1309
+
1310
+ # Handle the associated variables dict first, so that any variable
1311
+ # references within can be resolved prior to using them as variables.
1312
+ # Pass a copy of the variables dict to avoid having it be tainted.
1313
+ # Otherwise, it would have extra automatics added for everything that
1314
+ # should just be an ordinary variable in this scope.
1315
+ ProcessVariablesAndConditionsInDict(
1316
+ the_dict["variables"], phase, variables, build_file, "variables"
1317
+ )
1318
+
1319
+ LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
1320
+
1321
+ for key, value in the_dict.items():
1322
+ # Skip "variables", which was already processed if present.
1323
+ if key != "variables" and isinstance(value, str):
1324
+ expanded = ExpandVariables(value, phase, variables, build_file)
1325
+ if type(expanded) not in (str, int):
1326
+ raise ValueError(
1327
+ "Variable expansion in this context permits str and int "
1328
+ + "only, found "
1329
+ + expanded.__class__.__name__
1330
+ + " for "
1331
+ + key
1332
+ )
1333
+ the_dict[key] = expanded
1334
+
1335
+ # Variable expansion may have resulted in changes to automatics. Reload.
1336
+ # TODO(mark): Optimization: only reload if no changes were made.
1337
+ variables = variables_in.copy()
1338
+ LoadAutomaticVariablesFromDict(variables, the_dict)
1339
+ LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
1340
+
1341
+ # Process conditions in this dict. This is done after variable expansion
1342
+ # so that conditions may take advantage of expanded variables. For example,
1343
+ # if the_dict contains:
1344
+ # {'type': '<(library_type)',
1345
+ # 'conditions': [['_type=="static_library"', { ... }]]},
1346
+ # _type, as used in the condition, will only be set to the value of
1347
+ # library_type if variable expansion is performed before condition
1348
+ # processing. However, condition processing should occur prior to recursion
1349
+ # so that variables (both automatic and "variables" dict type) may be
1350
+ # adjusted by conditions sections, merged into the_dict, and have the
1351
+ # intended impact on contained dicts.
1352
+ #
1353
+ # This arrangement means that a "conditions" section containing a "variables"
1354
+ # section will only have those variables effective in subdicts, not in
1355
+ # the_dict. The workaround is to put a "conditions" section within a
1356
+ # "variables" section. For example:
1357
+ # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]],
1358
+ # 'defines': ['<(define)'],
1359
+ # 'my_subdict': {'defines': ['<(define)']}},
1360
+ # will not result in "IS_MAC" being appended to the "defines" list in the
1361
+ # current scope but would result in it being appended to the "defines" list
1362
+ # within "my_subdict". By comparison:
1363
+ # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]},
1364
+ # 'defines': ['<(define)'],
1365
+ # 'my_subdict': {'defines': ['<(define)']}},
1366
+ # will append "IS_MAC" to both "defines" lists.
1367
+
1368
+ # Evaluate conditions sections, allowing variable expansions within them
1369
+ # as well as nested conditionals. This will process a 'conditions' or
1370
+ # 'target_conditions' section, perform appropriate merging and recursive
1371
+ # conditional and variable processing, and then remove the conditions section
1372
+ # from the_dict if it is present.
1373
+ ProcessConditionsInDict(the_dict, phase, variables, build_file)
1374
+
1375
+ # Conditional processing may have resulted in changes to automatics or the
1376
+ # variables dict. Reload.
1377
+ variables = variables_in.copy()
1378
+ LoadAutomaticVariablesFromDict(variables, the_dict)
1379
+ LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
1380
+
1381
+ # Recurse into child dicts, or process child lists which may result in
1382
+ # further recursion into descendant dicts.
1383
+ for key, value in the_dict.items():
1384
+ # Skip "variables" and string values, which were already processed if
1385
+ # present.
1386
+ if key == "variables" or isinstance(value, str):
1387
+ continue
1388
+ if isinstance(value, dict):
1389
+ # Pass a copy of the variables dict so that subdicts can't influence
1390
+ # parents.
1391
+ ProcessVariablesAndConditionsInDict(
1392
+ value, phase, variables, build_file, key
1393
+ )
1394
+ elif isinstance(value, list):
1395
+ # The list itself can't influence the variables dict, and
1396
+ # ProcessVariablesAndConditionsInList will make copies of the variables
1397
+ # dict if it needs to pass it to something that can influence it. No
1398
+ # copy is necessary here.
1399
+ ProcessVariablesAndConditionsInList(value, phase, variables, build_file)
1400
+ elif not isinstance(value, int):
1401
+ raise TypeError("Unknown type " + value.__class__.__name__ + " for " + key)
1402
+
1403
+
1404
+ def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file):
1405
+ # Iterate using an index so that new values can be assigned into the_list.
1406
+ index = 0
1407
+ while index < len(the_list):
1408
+ item = the_list[index]
1409
+ if isinstance(item, dict):
1410
+ # Make a copy of the variables dict so that it won't influence anything
1411
+ # outside of its own scope.
1412
+ ProcessVariablesAndConditionsInDict(item, phase, variables, build_file)
1413
+ elif isinstance(item, list):
1414
+ ProcessVariablesAndConditionsInList(item, phase, variables, build_file)
1415
+ elif isinstance(item, str):
1416
+ expanded = ExpandVariables(item, phase, variables, build_file)
1417
+ if type(expanded) in (str, int):
1418
+ the_list[index] = expanded
1419
+ elif isinstance(expanded, list):
1420
+ the_list[index : index + 1] = expanded
1421
+ index += len(expanded)
1422
+
1423
+ # index now identifies the next item to examine. Continue right now
1424
+ # without falling into the index increment below.
1425
+ continue
1426
+ else:
1427
+ raise ValueError(
1428
+ "Variable expansion in this context permits strings and "
1429
+ + "lists only, found "
1430
+ + expanded.__class__.__name__
1431
+ + " at "
1432
+ + index
1433
+ )
1434
+ elif not isinstance(item, int):
1435
+ raise TypeError(
1436
+ "Unknown type " + item.__class__.__name__ + " at index " + index
1437
+ )
1438
+ index = index + 1
1439
+
1440
+
1441
+ def BuildTargetsDict(data):
1442
+ """Builds a dict mapping fully-qualified target names to their target dicts.
1443
+
1444
+ |data| is a dict mapping loaded build files by pathname relative to the
1445
+ current directory. Values in |data| are build file contents. For each
1446
+ |data| value with a "targets" key, the value of the "targets" key is taken
1447
+ as a list containing target dicts. Each target's fully-qualified name is
1448
+ constructed from the pathname of the build file (|data| key) and its
1449
+ "target_name" property. These fully-qualified names are used as the keys
1450
+ in the returned dict. These keys provide access to the target dicts,
1451
+ the dicts in the "targets" lists.
1452
+ """
1453
+
1454
+ targets = {}
1455
+ for build_file in data["target_build_files"]:
1456
+ for target in data[build_file].get("targets", []):
1457
+ target_name = gyp.common.QualifiedTarget(
1458
+ build_file, target["target_name"], target["toolset"]
1459
+ )
1460
+ if target_name in targets:
1461
+ raise GypError("Duplicate target definitions for " + target_name)
1462
+ targets[target_name] = target
1463
+
1464
+ return targets
1465
+
1466
+
1467
+ def QualifyDependencies(targets):
1468
+ """Make dependency links fully-qualified relative to the current directory.
1469
+
1470
+ |targets| is a dict mapping fully-qualified target names to their target
1471
+ dicts. For each target in this dict, keys known to contain dependency
1472
+ links are examined, and any dependencies referenced will be rewritten
1473
+ so that they are fully-qualified and relative to the current directory.
1474
+ All rewritten dependencies are suitable for use as keys to |targets| or a
1475
+ similar dict.
1476
+ """
1477
+
1478
+ all_dependency_sections = [
1479
+ dep + op for dep in dependency_sections for op in ("", "!", "/")
1480
+ ]
1481
+
1482
+ for target, target_dict in targets.items():
1483
+ target_build_file = gyp.common.BuildFile(target)
1484
+ toolset = target_dict["toolset"]
1485
+ for dependency_key in all_dependency_sections:
1486
+ dependencies = target_dict.get(dependency_key, [])
1487
+ for index, dep in enumerate(dependencies):
1488
+ dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget(
1489
+ target_build_file, dep, toolset
1490
+ )
1491
+ if not multiple_toolsets:
1492
+ # Ignore toolset specification in the dependency if it is specified.
1493
+ dep_toolset = toolset
1494
+ dependency = gyp.common.QualifiedTarget(
1495
+ dep_file, dep_target, dep_toolset
1496
+ )
1497
+ dependencies[index] = dependency
1498
+
1499
+ # Make sure anything appearing in a list other than "dependencies" also
1500
+ # appears in the "dependencies" list.
1501
+ if (
1502
+ dependency_key != "dependencies"
1503
+ and dependency not in target_dict["dependencies"]
1504
+ ):
1505
+ raise GypError(
1506
+ "Found "
1507
+ + dependency
1508
+ + " in "
1509
+ + dependency_key
1510
+ + " of "
1511
+ + target
1512
+ + ", but not in dependencies"
1513
+ )
1514
+
1515
+
1516
+ def ExpandWildcardDependencies(targets, data):
1517
+ """Expands dependencies specified as build_file:*.
1518
+
1519
+ For each target in |targets|, examines sections containing links to other
1520
+ targets. If any such section contains a link of the form build_file:*, it
1521
+ is taken as a wildcard link, and is expanded to list each target in
1522
+ build_file. The |data| dict provides access to build file dicts.
1523
+
1524
+ Any target that does not wish to be included by wildcard can provide an
1525
+ optional "suppress_wildcard" key in its target dict. When present and
1526
+ true, a wildcard dependency link will not include such targets.
1527
+
1528
+ All dependency names, including the keys to |targets| and the values in each
1529
+ dependency list, must be qualified when this function is called.
1530
+ """
1531
+
1532
+ for target, target_dict in targets.items():
1533
+ target_build_file = gyp.common.BuildFile(target)
1534
+ for dependency_key in dependency_sections:
1535
+ dependencies = target_dict.get(dependency_key, [])
1536
+
1537
+ # Loop this way instead of "for dependency in" or "for index in range"
1538
+ # because the dependencies list will be modified within the loop body.
1539
+ index = 0
1540
+ while index < len(dependencies):
1541
+ (
1542
+ dependency_build_file,
1543
+ dependency_target,
1544
+ dependency_toolset,
1545
+ ) = gyp.common.ParseQualifiedTarget(dependencies[index])
1546
+ if dependency_target != "*" and dependency_toolset != "*":
1547
+ # Not a wildcard. Keep it moving.
1548
+ index = index + 1
1549
+ continue
1550
+
1551
+ if dependency_build_file == target_build_file:
1552
+ # It's an error for a target to depend on all other targets in
1553
+ # the same file, because a target cannot depend on itself.
1554
+ raise GypError(
1555
+ "Found wildcard in "
1556
+ + dependency_key
1557
+ + " of "
1558
+ + target
1559
+ + " referring to same build file"
1560
+ )
1561
+
1562
+ # Take the wildcard out and adjust the index so that the next
1563
+ # dependency in the list will be processed the next time through the
1564
+ # loop.
1565
+ del dependencies[index]
1566
+ index = index - 1
1567
+
1568
+ # Loop through the targets in the other build file, adding them to
1569
+ # this target's list of dependencies in place of the removed
1570
+ # wildcard.
1571
+ dependency_target_dicts = data[dependency_build_file]["targets"]
1572
+ for dependency_target_dict in dependency_target_dicts:
1573
+ if int(dependency_target_dict.get("suppress_wildcard", False)):
1574
+ continue
1575
+ dependency_target_name = dependency_target_dict["target_name"]
1576
+ if (
1577
+ dependency_target not in {"*", dependency_target_name}
1578
+ ):
1579
+ continue
1580
+ dependency_target_toolset = dependency_target_dict["toolset"]
1581
+ if (
1582
+ dependency_toolset not in {"*", dependency_target_toolset}
1583
+ ):
1584
+ continue
1585
+ dependency = gyp.common.QualifiedTarget(
1586
+ dependency_build_file,
1587
+ dependency_target_name,
1588
+ dependency_target_toolset,
1589
+ )
1590
+ index = index + 1
1591
+ dependencies.insert(index, dependency)
1592
+
1593
+ index = index + 1
1594
+
1595
+
1596
+ def Unify(items):
1597
+ """Removes duplicate elements from items, keeping the first element."""
1598
+ seen = {}
1599
+ return [seen.setdefault(e, e) for e in items if e not in seen]
1600
+
1601
+
1602
+ def RemoveDuplicateDependencies(targets):
1603
+ """Makes sure every dependency appears only once in all targets's dependency
1604
+ lists."""
1605
+ for target_name, target_dict in targets.items():
1606
+ for dependency_key in dependency_sections:
1607
+ dependencies = target_dict.get(dependency_key, [])
1608
+ if dependencies:
1609
+ target_dict[dependency_key] = Unify(dependencies)
1610
+
1611
+
1612
+ def Filter(items, item):
1613
+ """Removes item from items."""
1614
+ res = {}
1615
+ return [res.setdefault(e, e) for e in items if e != item]
1616
+
1617
+
1618
+ def RemoveSelfDependencies(targets):
1619
+ """Remove self dependencies from targets that have the prune_self_dependency
1620
+ variable set."""
1621
+ for target_name, target_dict in targets.items():
1622
+ for dependency_key in dependency_sections:
1623
+ dependencies = target_dict.get(dependency_key, [])
1624
+ if dependencies:
1625
+ for t in dependencies:
1626
+ if t == target_name and (
1627
+ targets[t]
1628
+ .get("variables", {})
1629
+ .get("prune_self_dependency", 0)
1630
+ ):
1631
+ target_dict[dependency_key] = Filter(
1632
+ dependencies, target_name
1633
+ )
1634
+
1635
+
1636
+ def RemoveLinkDependenciesFromNoneTargets(targets):
1637
+ """Remove dependencies having the 'link_dependency' attribute from the 'none'
1638
+ targets."""
1639
+ for target_name, target_dict in targets.items():
1640
+ for dependency_key in dependency_sections:
1641
+ dependencies = target_dict.get(dependency_key, [])
1642
+ if dependencies:
1643
+ for t in dependencies:
1644
+ if target_dict.get("type", None) == "none":
1645
+ if targets[t].get("variables", {}).get("link_dependency", 0):
1646
+ target_dict[dependency_key] = Filter(
1647
+ target_dict[dependency_key], t
1648
+ )
1649
+
1650
+
1651
+ class DependencyGraphNode:
1652
+ """
1653
+
1654
+ Attributes:
1655
+ ref: A reference to an object that this DependencyGraphNode represents.
1656
+ dependencies: List of DependencyGraphNodes on which this one depends.
1657
+ dependents: List of DependencyGraphNodes that depend on this one.
1658
+ """
1659
+
1660
+ class CircularException(GypError):
1661
+ pass
1662
+
1663
+ def __init__(self, ref):
1664
+ self.ref = ref
1665
+ self.dependencies = []
1666
+ self.dependents = []
1667
+
1668
+ def __repr__(self):
1669
+ return "<DependencyGraphNode: %r>" % self.ref
1670
+
1671
+ def FlattenToList(self):
1672
+ # flat_list is the sorted list of dependencies - actually, the list items
1673
+ # are the "ref" attributes of DependencyGraphNodes. Every target will
1674
+ # appear in flat_list after all of its dependencies, and before all of its
1675
+ # dependents.
1676
+ flat_list = OrderedSet()
1677
+
1678
+ def ExtractNodeRef(node):
1679
+ """Extracts the object that the node represents from the given node."""
1680
+ return node.ref
1681
+
1682
+ # in_degree_zeros is the list of DependencyGraphNodes that have no
1683
+ # dependencies not in flat_list. Initially, it is a copy of the children
1684
+ # of this node, because when the graph was built, nodes with no
1685
+ # dependencies were made implicit dependents of the root node.
1686
+ in_degree_zeros = sorted(self.dependents[:], key=ExtractNodeRef)
1687
+
1688
+ while in_degree_zeros:
1689
+ # Nodes in in_degree_zeros have no dependencies not in flat_list, so they
1690
+ # can be appended to flat_list. Take these nodes out of in_degree_zeros
1691
+ # as work progresses, so that the next node to process from the list can
1692
+ # always be accessed at a consistent position.
1693
+ node = in_degree_zeros.pop()
1694
+ flat_list.add(node.ref)
1695
+
1696
+ # Look at dependents of the node just added to flat_list. Some of them
1697
+ # may now belong in in_degree_zeros.
1698
+ for node_dependent in sorted(node.dependents, key=ExtractNodeRef):
1699
+ is_in_degree_zero = True
1700
+ # TODO: We want to check through the
1701
+ # node_dependent.dependencies list but if it's long and we
1702
+ # always start at the beginning, then we get O(n^2) behaviour.
1703
+ for node_dependent_dependency in sorted(
1704
+ node_dependent.dependencies, key=ExtractNodeRef
1705
+ ):
1706
+ if node_dependent_dependency.ref not in flat_list:
1707
+ # The dependent one or more dependencies not in flat_list.
1708
+ # There will be more chances to add it to flat_list
1709
+ # when examining it again as a dependent of those other
1710
+ # dependencies, provided that there are no cycles.
1711
+ is_in_degree_zero = False
1712
+ break
1713
+
1714
+ if is_in_degree_zero:
1715
+ # All of the dependent's dependencies are already in flat_list. Add
1716
+ # it to in_degree_zeros where it will be processed in a future
1717
+ # iteration of the outer loop.
1718
+ in_degree_zeros += [node_dependent]
1719
+
1720
+ return list(flat_list)
1721
+
1722
+ def FindCycles(self):
1723
+ """
1724
+ Returns a list of cycles in the graph, where each cycle is its own list.
1725
+ """
1726
+ results = []
1727
+ visited = set()
1728
+
1729
+ def Visit(node, path):
1730
+ for child in node.dependents:
1731
+ if child in path:
1732
+ results.append([child] + path[: path.index(child) + 1])
1733
+ elif child not in visited:
1734
+ visited.add(child)
1735
+ Visit(child, [child] + path)
1736
+
1737
+ visited.add(self)
1738
+ Visit(self, [self])
1739
+
1740
+ return results
1741
+
1742
+ def DirectDependencies(self, dependencies=None):
1743
+ """Returns a list of just direct dependencies."""
1744
+ if dependencies is None:
1745
+ dependencies = []
1746
+
1747
+ for dependency in self.dependencies:
1748
+ # Check for None, corresponding to the root node.
1749
+ if dependency.ref and dependency.ref not in dependencies:
1750
+ dependencies.append(dependency.ref)
1751
+
1752
+ return dependencies
1753
+
1754
+ def _AddImportedDependencies(self, targets, dependencies=None):
1755
+ """Given a list of direct dependencies, adds indirect dependencies that
1756
+ other dependencies have declared to export their settings.
1757
+
1758
+ This method does not operate on self. Rather, it operates on the list
1759
+ of dependencies in the |dependencies| argument. For each dependency in
1760
+ that list, if any declares that it exports the settings of one of its
1761
+ own dependencies, those dependencies whose settings are "passed through"
1762
+ are added to the list. As new items are added to the list, they too will
1763
+ be processed, so it is possible to import settings through multiple levels
1764
+ of dependencies.
1765
+
1766
+ This method is not terribly useful on its own, it depends on being
1767
+ "primed" with a list of direct dependencies such as one provided by
1768
+ DirectDependencies. DirectAndImportedDependencies is intended to be the
1769
+ public entry point.
1770
+ """
1771
+
1772
+ if dependencies is None:
1773
+ dependencies = []
1774
+
1775
+ index = 0
1776
+ while index < len(dependencies):
1777
+ dependency = dependencies[index]
1778
+ dependency_dict = targets[dependency]
1779
+ # Add any dependencies whose settings should be imported to the list
1780
+ # if not already present. Newly-added items will be checked for
1781
+ # their own imports when the list iteration reaches them.
1782
+ # Rather than simply appending new items, insert them after the
1783
+ # dependency that exported them. This is done to more closely match
1784
+ # the depth-first method used by DeepDependencies.
1785
+ add_index = 1
1786
+ for imported_dependency in dependency_dict.get(
1787
+ "export_dependent_settings", []
1788
+ ):
1789
+ if imported_dependency not in dependencies:
1790
+ dependencies.insert(index + add_index, imported_dependency)
1791
+ add_index = add_index + 1
1792
+ index = index + 1
1793
+
1794
+ return dependencies
1795
+
1796
+ def DirectAndImportedDependencies(self, targets, dependencies=None):
1797
+ """Returns a list of a target's direct dependencies and all indirect
1798
+ dependencies that a dependency has advertised settings should be exported
1799
+ through the dependency for.
1800
+ """
1801
+
1802
+ dependencies = self.DirectDependencies(dependencies)
1803
+ return self._AddImportedDependencies(targets, dependencies)
1804
+
1805
+ def DeepDependencies(self, dependencies=None):
1806
+ """Returns an OrderedSet of all of a target's dependencies, recursively."""
1807
+ if dependencies is None:
1808
+ # Using a list to get ordered output and a set to do fast "is it
1809
+ # already added" checks.
1810
+ dependencies = OrderedSet()
1811
+
1812
+ for dependency in self.dependencies:
1813
+ # Check for None, corresponding to the root node.
1814
+ if dependency.ref is None:
1815
+ continue
1816
+ if dependency.ref not in dependencies:
1817
+ dependency.DeepDependencies(dependencies)
1818
+ dependencies.add(dependency.ref)
1819
+
1820
+ return dependencies
1821
+
1822
+ def _LinkDependenciesInternal(
1823
+ self, targets, include_shared_libraries, dependencies=None, initial=True
1824
+ ):
1825
+ """Returns an OrderedSet of dependency targets that are linked
1826
+ into this target.
1827
+
1828
+ This function has a split personality, depending on the setting of
1829
+ |initial|. Outside callers should always leave |initial| at its default
1830
+ setting.
1831
+
1832
+ When adding a target to the list of dependencies, this function will
1833
+ recurse into itself with |initial| set to False, to collect dependencies
1834
+ that are linked into the linkable target for which the list is being built.
1835
+
1836
+ If |include_shared_libraries| is False, the resulting dependencies will not
1837
+ include shared_library targets that are linked into this target.
1838
+ """
1839
+ if dependencies is None:
1840
+ # Using a list to get ordered output and a set to do fast "is it
1841
+ # already added" checks.
1842
+ dependencies = OrderedSet()
1843
+
1844
+ # Check for None, corresponding to the root node.
1845
+ if self.ref is None:
1846
+ return dependencies
1847
+
1848
+ # It's kind of sucky that |targets| has to be passed into this function,
1849
+ # but that's presently the easiest way to access the target dicts so that
1850
+ # this function can find target types.
1851
+
1852
+ if "target_name" not in targets[self.ref]:
1853
+ raise GypError("Missing 'target_name' field in target.")
1854
+
1855
+ if "type" not in targets[self.ref]:
1856
+ raise GypError(
1857
+ "Missing 'type' field in target %s" % targets[self.ref]["target_name"]
1858
+ )
1859
+
1860
+ target_type = targets[self.ref]["type"]
1861
+
1862
+ is_linkable = target_type in linkable_types
1863
+
1864
+ if initial and not is_linkable:
1865
+ # If this is the first target being examined and it's not linkable,
1866
+ # return an empty list of link dependencies, because the link
1867
+ # dependencies are intended to apply to the target itself (initial is
1868
+ # True) and this target won't be linked.
1869
+ return dependencies
1870
+
1871
+ # Don't traverse 'none' targets if explicitly excluded.
1872
+ if target_type == "none" and not targets[self.ref].get(
1873
+ "dependencies_traverse", True
1874
+ ):
1875
+ dependencies.add(self.ref)
1876
+ return dependencies
1877
+
1878
+ # Executables, mac kernel extensions, windows drivers and loadable modules
1879
+ # are already fully and finally linked. Nothing else can be a link
1880
+ # dependency of them, there can only be dependencies in the sense that a
1881
+ # dependent target might run an executable or load the loadable_module.
1882
+ if not initial and target_type in (
1883
+ "executable",
1884
+ "loadable_module",
1885
+ "mac_kernel_extension",
1886
+ "windows_driver",
1887
+ ):
1888
+ return dependencies
1889
+
1890
+ # Shared libraries are already fully linked. They should only be included
1891
+ # in |dependencies| when adjusting static library dependencies (in order to
1892
+ # link against the shared_library's import lib), but should not be included
1893
+ # in |dependencies| when propagating link_settings.
1894
+ # The |include_shared_libraries| flag controls which of these two cases we
1895
+ # are handling.
1896
+ if (
1897
+ not initial
1898
+ and target_type == "shared_library"
1899
+ and not include_shared_libraries
1900
+ ):
1901
+ return dependencies
1902
+
1903
+ # The target is linkable, add it to the list of link dependencies.
1904
+ if self.ref not in dependencies:
1905
+ dependencies.add(self.ref)
1906
+ if initial or not is_linkable:
1907
+ # If this is a subsequent target and it's linkable, don't look any
1908
+ # further for linkable dependencies, as they'll already be linked into
1909
+ # this target linkable. Always look at dependencies of the initial
1910
+ # target, and always look at dependencies of non-linkables.
1911
+ for dependency in self.dependencies:
1912
+ dependency._LinkDependenciesInternal(
1913
+ targets, include_shared_libraries, dependencies, False
1914
+ )
1915
+
1916
+ return dependencies
1917
+
1918
+ def DependenciesForLinkSettings(self, targets):
1919
+ """
1920
+ Returns a list of dependency targets whose link_settings should be merged
1921
+ into this target.
1922
+ """
1923
+
1924
+ # TODO(sbaig) Currently, chrome depends on the bug that shared libraries'
1925
+ # link_settings are propagated. So for now, we will allow it, unless the
1926
+ # 'allow_sharedlib_linksettings_propagation' flag is explicitly set to
1927
+ # False. Once chrome is fixed, we can remove this flag.
1928
+ include_shared_libraries = targets[self.ref].get(
1929
+ "allow_sharedlib_linksettings_propagation", True
1930
+ )
1931
+ return self._LinkDependenciesInternal(targets, include_shared_libraries)
1932
+
1933
+ def DependenciesToLinkAgainst(self, targets):
1934
+ """
1935
+ Returns a list of dependency targets that are linked into this target.
1936
+ """
1937
+ return self._LinkDependenciesInternal(targets, True)
1938
+
1939
+
1940
+ def BuildDependencyList(targets):
1941
+ # Create a DependencyGraphNode for each target. Put it into a dict for easy
1942
+ # access.
1943
+ dependency_nodes = {}
1944
+ for target, spec in targets.items():
1945
+ if target not in dependency_nodes:
1946
+ dependency_nodes[target] = DependencyGraphNode(target)
1947
+
1948
+ # Set up the dependency links. Targets that have no dependencies are treated
1949
+ # as dependent on root_node.
1950
+ root_node = DependencyGraphNode(None)
1951
+ for target, spec in targets.items():
1952
+ target_node = dependency_nodes[target]
1953
+ dependencies = spec.get("dependencies")
1954
+ if not dependencies:
1955
+ target_node.dependencies = [root_node]
1956
+ root_node.dependents.append(target_node)
1957
+ else:
1958
+ for dependency in dependencies:
1959
+ dependency_node = dependency_nodes.get(dependency)
1960
+ if not dependency_node:
1961
+ raise GypError(
1962
+ "Dependency '%s' not found while "
1963
+ "trying to load target %s" % (dependency, target)
1964
+ )
1965
+ target_node.dependencies.append(dependency_node)
1966
+ dependency_node.dependents.append(target_node)
1967
+
1968
+ flat_list = root_node.FlattenToList()
1969
+
1970
+ # If there's anything left unvisited, there must be a circular dependency
1971
+ # (cycle).
1972
+ if len(flat_list) != len(targets):
1973
+ if not root_node.dependents:
1974
+ # If all targets have dependencies, add the first target as a dependent
1975
+ # of root_node so that the cycle can be discovered from root_node.
1976
+ target = next(iter(targets))
1977
+ target_node = dependency_nodes[target]
1978
+ target_node.dependencies.append(root_node)
1979
+ root_node.dependents.append(target_node)
1980
+
1981
+ cycles = []
1982
+ for cycle in root_node.FindCycles():
1983
+ paths = [node.ref for node in cycle]
1984
+ cycles.append("Cycle: %s" % " -> ".join(paths))
1985
+ raise DependencyGraphNode.CircularException(
1986
+ "Cycles in dependency graph detected:\n" + "\n".join(cycles)
1987
+ )
1988
+
1989
+ return [dependency_nodes, flat_list]
1990
+
1991
+
1992
+ def VerifyNoGYPFileCircularDependencies(targets):
1993
+ # Create a DependencyGraphNode for each gyp file containing a target. Put
1994
+ # it into a dict for easy access.
1995
+ dependency_nodes = {}
1996
+ for target in targets:
1997
+ build_file = gyp.common.BuildFile(target)
1998
+ if build_file not in dependency_nodes:
1999
+ dependency_nodes[build_file] = DependencyGraphNode(build_file)
2000
+
2001
+ # Set up the dependency links.
2002
+ for target, spec in targets.items():
2003
+ build_file = gyp.common.BuildFile(target)
2004
+ build_file_node = dependency_nodes[build_file]
2005
+ target_dependencies = spec.get("dependencies", [])
2006
+ for dependency in target_dependencies:
2007
+ try:
2008
+ dependency_build_file = gyp.common.BuildFile(dependency)
2009
+ except GypError as e:
2010
+ gyp.common.ExceptionAppend(
2011
+ e, "while computing dependencies of .gyp file %s" % build_file
2012
+ )
2013
+ raise
2014
+
2015
+ if dependency_build_file == build_file:
2016
+ # A .gyp file is allowed to refer back to itself.
2017
+ continue
2018
+ dependency_node = dependency_nodes.get(dependency_build_file)
2019
+ if not dependency_node:
2020
+ raise GypError("Dependency '%s' not found" % dependency_build_file)
2021
+ if dependency_node not in build_file_node.dependencies:
2022
+ build_file_node.dependencies.append(dependency_node)
2023
+ dependency_node.dependents.append(build_file_node)
2024
+
2025
+ # Files that have no dependencies are treated as dependent on root_node.
2026
+ root_node = DependencyGraphNode(None)
2027
+ for build_file_node in dependency_nodes.values():
2028
+ if len(build_file_node.dependencies) == 0:
2029
+ build_file_node.dependencies.append(root_node)
2030
+ root_node.dependents.append(build_file_node)
2031
+
2032
+ flat_list = root_node.FlattenToList()
2033
+
2034
+ # If there's anything left unvisited, there must be a circular dependency
2035
+ # (cycle).
2036
+ if len(flat_list) != len(dependency_nodes):
2037
+ if not root_node.dependents:
2038
+ # If all files have dependencies, add the first file as a dependent
2039
+ # of root_node so that the cycle can be discovered from root_node.
2040
+ file_node = next(iter(dependency_nodes.values()))
2041
+ file_node.dependencies.append(root_node)
2042
+ root_node.dependents.append(file_node)
2043
+ cycles = []
2044
+ for cycle in root_node.FindCycles():
2045
+ paths = [node.ref for node in cycle]
2046
+ cycles.append("Cycle: %s" % " -> ".join(paths))
2047
+ raise DependencyGraphNode.CircularException(
2048
+ "Cycles in .gyp file dependency graph detected:\n" + "\n".join(cycles)
2049
+ )
2050
+
2051
+
2052
+ def DoDependentSettings(key, flat_list, targets, dependency_nodes):
2053
+ # key should be one of all_dependent_settings, direct_dependent_settings,
2054
+ # or link_settings.
2055
+
2056
+ for target in flat_list:
2057
+ target_dict = targets[target]
2058
+ build_file = gyp.common.BuildFile(target)
2059
+
2060
+ if key == "all_dependent_settings":
2061
+ dependencies = dependency_nodes[target].DeepDependencies()
2062
+ elif key == "direct_dependent_settings":
2063
+ dependencies = dependency_nodes[target].DirectAndImportedDependencies(
2064
+ targets
2065
+ )
2066
+ elif key == "link_settings":
2067
+ dependencies = dependency_nodes[target].DependenciesForLinkSettings(targets)
2068
+ else:
2069
+ raise GypError(
2070
+ "DoDependentSettings doesn't know how to determine "
2071
+ "dependencies for " + key
2072
+ )
2073
+
2074
+ for dependency in dependencies:
2075
+ dependency_dict = targets[dependency]
2076
+ if key not in dependency_dict:
2077
+ continue
2078
+ dependency_build_file = gyp.common.BuildFile(dependency)
2079
+ MergeDicts(
2080
+ target_dict, dependency_dict[key], build_file, dependency_build_file
2081
+ )
2082
+
2083
+
2084
+ def AdjustStaticLibraryDependencies(
2085
+ flat_list, targets, dependency_nodes, sort_dependencies
2086
+ ):
2087
+ # Recompute target "dependencies" properties. For each static library
2088
+ # target, remove "dependencies" entries referring to other static libraries,
2089
+ # unless the dependency has the "hard_dependency" attribute set. For each
2090
+ # linkable target, add a "dependencies" entry referring to all of the
2091
+ # target's computed list of link dependencies (including static libraries
2092
+ # if no such entry is already present.
2093
+ for target in flat_list:
2094
+ target_dict = targets[target]
2095
+ target_type = target_dict["type"]
2096
+
2097
+ if target_type == "static_library":
2098
+ if "dependencies" not in target_dict:
2099
+ continue
2100
+
2101
+ target_dict["dependencies_original"] = target_dict.get("dependencies", [])[
2102
+ :
2103
+ ]
2104
+
2105
+ # A static library should not depend on another static library unless
2106
+ # the dependency relationship is "hard," which should only be done when
2107
+ # a dependent relies on some side effect other than just the build
2108
+ # product, like a rule or action output. Further, if a target has a
2109
+ # non-hard dependency, but that dependency exports a hard dependency,
2110
+ # the non-hard dependency can safely be removed, but the exported hard
2111
+ # dependency must be added to the target to keep the same dependency
2112
+ # ordering.
2113
+ dependencies = dependency_nodes[target].DirectAndImportedDependencies(
2114
+ targets
2115
+ )
2116
+ index = 0
2117
+ while index < len(dependencies):
2118
+ dependency = dependencies[index]
2119
+ dependency_dict = targets[dependency]
2120
+
2121
+ # Remove every non-hard static library dependency and remove every
2122
+ # non-static library dependency that isn't a direct dependency.
2123
+ if (
2124
+ dependency_dict["type"] == "static_library"
2125
+ and not dependency_dict.get("hard_dependency", False)
2126
+ ) or (
2127
+ dependency_dict["type"] != "static_library"
2128
+ and dependency not in target_dict["dependencies"]
2129
+ ):
2130
+ # Take the dependency out of the list, and don't increment index
2131
+ # because the next dependency to analyze will shift into the index
2132
+ # formerly occupied by the one being removed.
2133
+ del dependencies[index]
2134
+ else:
2135
+ index = index + 1
2136
+
2137
+ # Update the dependencies. If the dependencies list is empty, it's not
2138
+ # needed, so unhook it.
2139
+ if len(dependencies) > 0:
2140
+ target_dict["dependencies"] = dependencies
2141
+ else:
2142
+ del target_dict["dependencies"]
2143
+
2144
+ elif target_type in linkable_types:
2145
+ # Get a list of dependency targets that should be linked into this
2146
+ # target. Add them to the dependencies list if they're not already
2147
+ # present.
2148
+
2149
+ link_dependencies = dependency_nodes[target].DependenciesToLinkAgainst(
2150
+ targets
2151
+ )
2152
+ for dependency in link_dependencies:
2153
+ if dependency == target:
2154
+ continue
2155
+ if "dependencies" not in target_dict:
2156
+ target_dict["dependencies"] = []
2157
+ if dependency not in target_dict["dependencies"]:
2158
+ target_dict["dependencies"].append(dependency)
2159
+ # Sort the dependencies list in the order from dependents to dependencies.
2160
+ # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D.
2161
+ # Note: flat_list is already sorted in the order from dependencies to
2162
+ # dependents.
2163
+ if sort_dependencies and "dependencies" in target_dict:
2164
+ target_dict["dependencies"] = [
2165
+ dep
2166
+ for dep in reversed(flat_list)
2167
+ if dep in target_dict["dependencies"]
2168
+ ]
2169
+
2170
+
2171
+ # Initialize this here to speed up MakePathRelative.
2172
+ exception_re = re.compile(r"""["']?[-/$<>^]""")
2173
+
2174
+
2175
+ def MakePathRelative(to_file, fro_file, item):
2176
+ # If item is a relative path, it's relative to the build file dict that it's
2177
+ # coming from. Fix it up to make it relative to the build file dict that
2178
+ # it's going into.
2179
+ # Exception: any |item| that begins with these special characters is
2180
+ # returned without modification.
2181
+ # / Used when a path is already absolute (shortcut optimization;
2182
+ # such paths would be returned as absolute anyway)
2183
+ # $ Used for build environment variables
2184
+ # - Used for some build environment flags (such as -lapr-1 in a
2185
+ # "libraries" section)
2186
+ # < Used for our own variable and command expansions (see ExpandVariables)
2187
+ # > Used for our own variable and command expansions (see ExpandVariables)
2188
+ # ^ Used for our own variable and command expansions (see ExpandVariables)
2189
+ #
2190
+ # "/' Used when a value is quoted. If these are present, then we
2191
+ # check the second character instead.
2192
+ #
2193
+ if to_file == fro_file or exception_re.match(item):
2194
+ return item
2195
+ else:
2196
+ # TODO(dglazkov) The backslash/forward-slash replacement at the end is a
2197
+ # temporary measure. This should really be addressed by keeping all paths
2198
+ # in POSIX until actual project generation.
2199
+ ret = os.path.normpath(
2200
+ os.path.join(
2201
+ gyp.common.RelativePath(
2202
+ os.path.dirname(fro_file), os.path.dirname(to_file)
2203
+ ),
2204
+ item,
2205
+ )
2206
+ ).replace("\\", "/")
2207
+ if item.endswith("/"):
2208
+ ret += "/"
2209
+ return ret
2210
+
2211
+
2212
+ def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True):
2213
+ # Python documentation recommends objects which do not support hash
2214
+ # set this value to None. Python library objects follow this rule.
2215
+ def is_hashable(val):
2216
+ return val.__hash__
2217
+
2218
+ # If x is hashable, returns whether x is in s. Else returns whether x is in items.
2219
+ def is_in_set_or_list(x, s, items):
2220
+ if is_hashable(x):
2221
+ return x in s
2222
+ return x in items
2223
+
2224
+ prepend_index = 0
2225
+
2226
+ # Make membership testing of hashables in |to| (in particular, strings)
2227
+ # faster.
2228
+ hashable_to_set = {x for x in to if is_hashable(x)}
2229
+ for item in fro:
2230
+ singleton = False
2231
+ if type(item) in (str, int):
2232
+ # The cheap and easy case.
2233
+ to_item = MakePathRelative(to_file, fro_file, item) if is_paths else item
2234
+
2235
+ if not (isinstance(item, str) and item.startswith("-")):
2236
+ # Any string that doesn't begin with a "-" is a singleton - it can
2237
+ # only appear once in a list, to be enforced by the list merge append
2238
+ # or prepend.
2239
+ singleton = True
2240
+ elif isinstance(item, dict):
2241
+ # Make a copy of the dictionary, continuing to look for paths to fix.
2242
+ # The other intelligent aspects of merge processing won't apply because
2243
+ # item is being merged into an empty dict.
2244
+ to_item = {}
2245
+ MergeDicts(to_item, item, to_file, fro_file)
2246
+ elif isinstance(item, list):
2247
+ # Recurse, making a copy of the list. If the list contains any
2248
+ # descendant dicts, path fixing will occur. Note that here, custom
2249
+ # values for is_paths and append are dropped; those are only to be
2250
+ # applied to |to| and |fro|, not sublists of |fro|. append shouldn't
2251
+ # matter anyway because the new |to_item| list is empty.
2252
+ to_item = []
2253
+ MergeLists(to_item, item, to_file, fro_file)
2254
+ else:
2255
+ raise TypeError(
2256
+ "Attempt to merge list item of unsupported type "
2257
+ + item.__class__.__name__
2258
+ )
2259
+
2260
+ if append:
2261
+ # If appending a singleton that's already in the list, don't append.
2262
+ # This ensures that the earliest occurrence of the item will stay put.
2263
+ if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to):
2264
+ to.append(to_item)
2265
+ if is_hashable(to_item):
2266
+ hashable_to_set.add(to_item)
2267
+ else:
2268
+ # If prepending a singleton that's already in the list, remove the
2269
+ # existing instance and proceed with the prepend. This ensures that the
2270
+ # item appears at the earliest possible position in the list.
2271
+ while singleton and to_item in to:
2272
+ to.remove(to_item)
2273
+
2274
+ # Don't just insert everything at index 0. That would prepend the new
2275
+ # items to the list in reverse order, which would be an unwelcome
2276
+ # surprise.
2277
+ to.insert(prepend_index, to_item)
2278
+ if is_hashable(to_item):
2279
+ hashable_to_set.add(to_item)
2280
+ prepend_index = prepend_index + 1
2281
+
2282
+
2283
+ def MergeDicts(to, fro, to_file, fro_file):
2284
+ # I wanted to name the parameter "from" but it's a Python keyword...
2285
+ for k, v in fro.items():
2286
+ # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give
2287
+ # copy semantics. Something else may want to merge from the |fro| dict
2288
+ # later, and having the same dict ref pointed to twice in the tree isn't
2289
+ # what anyone wants considering that the dicts may subsequently be
2290
+ # modified.
2291
+ if k in to:
2292
+ bad_merge = False
2293
+ if type(v) in (str, int):
2294
+ if type(to[k]) not in (str, int):
2295
+ bad_merge = True
2296
+ elif not isinstance(v, type(to[k])):
2297
+ bad_merge = True
2298
+
2299
+ if bad_merge:
2300
+ raise TypeError(
2301
+ "Attempt to merge dict value of type "
2302
+ + v.__class__.__name__
2303
+ + " into incompatible type "
2304
+ + to[k].__class__.__name__
2305
+ + " for key "
2306
+ + k
2307
+ )
2308
+ if type(v) in (str, int):
2309
+ # Overwrite the existing value, if any. Cheap and easy.
2310
+ is_path = IsPathSection(k)
2311
+ if is_path:
2312
+ to[k] = MakePathRelative(to_file, fro_file, v)
2313
+ else:
2314
+ to[k] = v
2315
+ elif isinstance(v, dict):
2316
+ # Recurse, guaranteeing copies will be made of objects that require it.
2317
+ if k not in to:
2318
+ to[k] = {}
2319
+ MergeDicts(to[k], v, to_file, fro_file)
2320
+ elif isinstance(v, list):
2321
+ # Lists in dicts can be merged with different policies, depending on
2322
+ # how the key in the "from" dict (k, the from-key) is written.
2323
+ #
2324
+ # If the from-key has ...the to-list will have this action
2325
+ # this character appended:... applied when receiving the from-list:
2326
+ # = replace
2327
+ # + prepend
2328
+ # ? set, only if to-list does not yet exist
2329
+ # (none) append
2330
+ #
2331
+ # This logic is list-specific, but since it relies on the associated
2332
+ # dict key, it's checked in this dict-oriented function.
2333
+ ext = k[-1]
2334
+ append = True
2335
+ if ext == "=":
2336
+ list_base = k[:-1]
2337
+ lists_incompatible = [list_base, list_base + "?"]
2338
+ to[list_base] = []
2339
+ elif ext == "+":
2340
+ list_base = k[:-1]
2341
+ lists_incompatible = [list_base + "=", list_base + "?"]
2342
+ append = False
2343
+ elif ext == "?":
2344
+ list_base = k[:-1]
2345
+ lists_incompatible = [list_base, list_base + "=", list_base + "+"]
2346
+ else:
2347
+ list_base = k
2348
+ lists_incompatible = [list_base + "=", list_base + "?"]
2349
+
2350
+ # Some combinations of merge policies appearing together are meaningless.
2351
+ # It's stupid to replace and append simultaneously, for example. Append
2352
+ # and prepend are the only policies that can coexist.
2353
+ for list_incompatible in lists_incompatible:
2354
+ if list_incompatible in fro:
2355
+ raise GypError(
2356
+ "Incompatible list policies " + k + " and " + list_incompatible
2357
+ )
2358
+
2359
+ if list_base in to:
2360
+ if ext == "?":
2361
+ # If the key ends in "?", the list will only be merged if it doesn't
2362
+ # already exist.
2363
+ continue
2364
+ elif not isinstance(to[list_base], list):
2365
+ # This may not have been checked above if merging in a list with an
2366
+ # extension character.
2367
+ raise TypeError(
2368
+ "Attempt to merge dict value of type "
2369
+ + v.__class__.__name__
2370
+ + " into incompatible type "
2371
+ + to[list_base].__class__.__name__
2372
+ + " for key "
2373
+ + list_base
2374
+ + "("
2375
+ + k
2376
+ + ")"
2377
+ )
2378
+ else:
2379
+ to[list_base] = []
2380
+
2381
+ # Call MergeLists, which will make copies of objects that require it.
2382
+ # MergeLists can recurse back into MergeDicts, although this will be
2383
+ # to make copies of dicts (with paths fixed), there will be no
2384
+ # subsequent dict "merging" once entering a list because lists are
2385
+ # always replaced, appended to, or prepended to.
2386
+ is_paths = IsPathSection(list_base)
2387
+ MergeLists(to[list_base], v, to_file, fro_file, is_paths, append)
2388
+ else:
2389
+ raise TypeError(
2390
+ "Attempt to merge dict value of unsupported type "
2391
+ + v.__class__.__name__
2392
+ + " for key "
2393
+ + k
2394
+ )
2395
+
2396
+
2397
+ def MergeConfigWithInheritance(
2398
+ new_configuration_dict, build_file, target_dict, configuration, visited
2399
+ ):
2400
+ # Skip if previously visited.
2401
+ if configuration in visited:
2402
+ return
2403
+
2404
+ # Look at this configuration.
2405
+ configuration_dict = target_dict["configurations"][configuration]
2406
+
2407
+ # Merge in parents.
2408
+ for parent in configuration_dict.get("inherit_from", []):
2409
+ MergeConfigWithInheritance(
2410
+ new_configuration_dict,
2411
+ build_file,
2412
+ target_dict,
2413
+ parent,
2414
+ visited + [configuration],
2415
+ )
2416
+
2417
+ # Merge it into the new config.
2418
+ MergeDicts(new_configuration_dict, configuration_dict, build_file, build_file)
2419
+
2420
+ # Drop abstract.
2421
+ if "abstract" in new_configuration_dict:
2422
+ del new_configuration_dict["abstract"]
2423
+
2424
+
2425
+ def SetUpConfigurations(target, target_dict):
2426
+ # key_suffixes is a list of key suffixes that might appear on key names.
2427
+ # These suffixes are handled in conditional evaluations (for =, +, and ?)
2428
+ # and rules/exclude processing (for ! and /). Keys with these suffixes
2429
+ # should be treated the same as keys without.
2430
+ key_suffixes = ["=", "+", "?", "!", "/"]
2431
+
2432
+ build_file = gyp.common.BuildFile(target)
2433
+
2434
+ # Provide a single configuration by default if none exists.
2435
+ # TODO(mark): Signal an error if default_configurations exists but
2436
+ # configurations does not.
2437
+ if "configurations" not in target_dict:
2438
+ target_dict["configurations"] = {"Default": {}}
2439
+ if "default_configuration" not in target_dict:
2440
+ concrete = [
2441
+ i
2442
+ for (i, config) in target_dict["configurations"].items()
2443
+ if not config.get("abstract")
2444
+ ]
2445
+ target_dict["default_configuration"] = sorted(concrete)[0]
2446
+
2447
+ merged_configurations = {}
2448
+ configs = target_dict["configurations"]
2449
+ for (configuration, old_configuration_dict) in configs.items():
2450
+ # Skip abstract configurations (saves work only).
2451
+ if old_configuration_dict.get("abstract"):
2452
+ continue
2453
+ # Configurations inherit (most) settings from the enclosing target scope.
2454
+ # Get the inheritance relationship right by making a copy of the target
2455
+ # dict.
2456
+ new_configuration_dict = {}
2457
+ for (key, target_val) in target_dict.items():
2458
+ key_ext = key[-1:]
2459
+ key_base = key[:-1] if key_ext in key_suffixes else key
2460
+ if key_base not in non_configuration_keys:
2461
+ new_configuration_dict[key] = gyp.simple_copy.deepcopy(target_val)
2462
+
2463
+ # Merge in configuration (with all its parents first).
2464
+ MergeConfigWithInheritance(
2465
+ new_configuration_dict, build_file, target_dict, configuration, []
2466
+ )
2467
+
2468
+ merged_configurations[configuration] = new_configuration_dict
2469
+
2470
+ # Put the new configurations back into the target dict as a configuration.
2471
+ for configuration, value in merged_configurations.items():
2472
+ target_dict["configurations"][configuration] = value
2473
+ # Now drop all the abstract ones.
2474
+ configs = target_dict["configurations"]
2475
+ target_dict["configurations"] = {
2476
+ k: v for k, v in configs.items() if not v.get("abstract")
2477
+ }
2478
+
2479
+ # Now that all of the target's configurations have been built, go through
2480
+ # the target dict's keys and remove everything that's been moved into a
2481
+ # "configurations" section.
2482
+ delete_keys = []
2483
+ for key in target_dict:
2484
+ key_ext = key[-1:]
2485
+ key_base = key[:-1] if key_ext in key_suffixes else key
2486
+ if key_base not in non_configuration_keys:
2487
+ delete_keys.append(key)
2488
+ for key in delete_keys:
2489
+ del target_dict[key]
2490
+
2491
+ # Check the configurations to see if they contain invalid keys.
2492
+ for configuration in target_dict["configurations"]:
2493
+ configuration_dict = target_dict["configurations"][configuration]
2494
+ for key in configuration_dict:
2495
+ if key in invalid_configuration_keys:
2496
+ raise GypError(
2497
+ "%s not allowed in the %s configuration, found in "
2498
+ "target %s" % (key, configuration, target)
2499
+ )
2500
+
2501
+
2502
+ def ProcessListFiltersInDict(name, the_dict):
2503
+ """Process regular expression and exclusion-based filters on lists.
2504
+
2505
+ An exclusion list is in a dict key named with a trailing "!", like
2506
+ "sources!". Every item in such a list is removed from the associated
2507
+ main list, which in this example, would be "sources". Removed items are
2508
+ placed into a "sources_excluded" list in the dict.
2509
+
2510
+ Regular expression (regex) filters are contained in dict keys named with a
2511
+ trailing "/", such as "sources/" to operate on the "sources" list. Regex
2512
+ filters in a dict take the form:
2513
+ 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
2514
+ ['include', '_mac\\.cc$'] ],
2515
+ The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
2516
+ _win.cc. The second filter then includes all files ending in _mac.cc that
2517
+ are now or were once in the "sources" list. Items matching an "exclude"
2518
+ filter are subject to the same processing as would occur if they were listed
2519
+ by name in an exclusion list (ending in "!"). Items matching an "include"
2520
+ filter are brought back into the main list if previously excluded by an
2521
+ exclusion list or exclusion regex filter. Subsequent matching "exclude"
2522
+ patterns can still cause items to be excluded after matching an "include".
2523
+ """
2524
+
2525
+ # Look through the dictionary for any lists whose keys end in "!" or "/".
2526
+ # These are lists that will be treated as exclude lists and regular
2527
+ # expression-based exclude/include lists. Collect the lists that are
2528
+ # needed first, looking for the lists that they operate on, and assemble
2529
+ # then into |lists|. This is done in a separate loop up front, because
2530
+ # the _included and _excluded keys need to be added to the_dict, and that
2531
+ # can't be done while iterating through it.
2532
+
2533
+ lists = []
2534
+ del_lists = []
2535
+ for key, value in the_dict.items():
2536
+ if not key:
2537
+ continue
2538
+ operation = key[-1]
2539
+ if operation not in {"!", "/"}:
2540
+ continue
2541
+
2542
+ if not isinstance(value, list):
2543
+ raise ValueError(
2544
+ name + " key " + key + " must be list, not " + value.__class__.__name__
2545
+ )
2546
+
2547
+ list_key = key[:-1]
2548
+ if list_key not in the_dict:
2549
+ # This happens when there's a list like "sources!" but no corresponding
2550
+ # "sources" list. Since there's nothing for it to operate on, queue up
2551
+ # the "sources!" list for deletion now.
2552
+ del_lists.append(key)
2553
+ continue
2554
+
2555
+ if not isinstance(the_dict[list_key], list):
2556
+ value = the_dict[list_key]
2557
+ raise ValueError(
2558
+ name
2559
+ + " key "
2560
+ + list_key
2561
+ + " must be list, not "
2562
+ + value.__class__.__name__
2563
+ + " when applying "
2564
+ + {"!": "exclusion", "/": "regex"}[operation]
2565
+ )
2566
+
2567
+ if list_key not in lists:
2568
+ lists.append(list_key)
2569
+
2570
+ # Delete the lists that are known to be unneeded at this point.
2571
+ for del_list in del_lists:
2572
+ del the_dict[del_list]
2573
+
2574
+ for list_key in lists:
2575
+ the_list = the_dict[list_key]
2576
+
2577
+ # Initialize the list_actions list, which is parallel to the_list. Each
2578
+ # item in list_actions identifies whether the corresponding item in
2579
+ # the_list should be excluded, unconditionally preserved (included), or
2580
+ # whether no exclusion or inclusion has been applied. Items for which
2581
+ # no exclusion or inclusion has been applied (yet) have value -1, items
2582
+ # excluded have value 0, and items included have value 1. Includes and
2583
+ # excludes override previous actions. All items in list_actions are
2584
+ # initialized to -1 because no excludes or includes have been processed
2585
+ # yet.
2586
+ list_actions = list((-1,) * len(the_list))
2587
+
2588
+ exclude_key = list_key + "!"
2589
+ if exclude_key in the_dict:
2590
+ for exclude_item in the_dict[exclude_key]:
2591
+ for index, list_item in enumerate(the_list):
2592
+ if exclude_item == list_item:
2593
+ # This item matches the exclude_item, so set its action to 0
2594
+ # (exclude).
2595
+ list_actions[index] = 0
2596
+
2597
+ # The "whatever!" list is no longer needed, dump it.
2598
+ del the_dict[exclude_key]
2599
+
2600
+ regex_key = list_key + "/"
2601
+ if regex_key in the_dict:
2602
+ for regex_item in the_dict[regex_key]:
2603
+ [action, pattern] = regex_item
2604
+ pattern_re = re.compile(pattern)
2605
+
2606
+ if action == "exclude":
2607
+ # This item matches an exclude regex, set its value to 0 (exclude).
2608
+ action_value = 0
2609
+ elif action == "include":
2610
+ # This item matches an include regex, set its value to 1 (include).
2611
+ action_value = 1
2612
+ else:
2613
+ # This is an action that doesn't make any sense.
2614
+ raise ValueError(
2615
+ "Unrecognized action "
2616
+ + action
2617
+ + " in "
2618
+ + name
2619
+ + " key "
2620
+ + regex_key
2621
+ )
2622
+
2623
+ for index, list_item in enumerate(the_list):
2624
+ if list_actions[index] == action_value:
2625
+ # Even if the regex matches, nothing will change so continue
2626
+ # (regex searches are expensive).
2627
+ continue
2628
+ if pattern_re.search(list_item):
2629
+ # Regular expression match.
2630
+ list_actions[index] = action_value
2631
+
2632
+ # The "whatever/" list is no longer needed, dump it.
2633
+ del the_dict[regex_key]
2634
+
2635
+ # Add excluded items to the excluded list.
2636
+ #
2637
+ # Note that exclude_key ("sources!") is different from excluded_key
2638
+ # ("sources_excluded"). The exclude_key list is input and it was already
2639
+ # processed and deleted; the excluded_key list is output and it's about
2640
+ # to be created.
2641
+ excluded_key = list_key + "_excluded"
2642
+ if excluded_key in the_dict:
2643
+ raise GypError(
2644
+ name + " key " + excluded_key + " must not be present prior "
2645
+ " to applying exclusion/regex filters for " + list_key
2646
+ )
2647
+
2648
+ excluded_list = []
2649
+
2650
+ # Go backwards through the list_actions list so that as items are deleted,
2651
+ # the indices of items that haven't been seen yet don't shift. That means
2652
+ # that things need to be prepended to excluded_list to maintain them in the
2653
+ # same order that they existed in the_list.
2654
+ for index in range(len(list_actions) - 1, -1, -1):
2655
+ if list_actions[index] == 0:
2656
+ # Dump anything with action 0 (exclude). Keep anything with action 1
2657
+ # (include) or -1 (no include or exclude seen for the item).
2658
+ excluded_list.insert(0, the_list[index])
2659
+ del the_list[index]
2660
+
2661
+ # If anything was excluded, put the excluded list into the_dict at
2662
+ # excluded_key.
2663
+ if len(excluded_list) > 0:
2664
+ the_dict[excluded_key] = excluded_list
2665
+
2666
+ # Now recurse into subdicts and lists that may contain dicts.
2667
+ for key, value in the_dict.items():
2668
+ if isinstance(value, dict):
2669
+ ProcessListFiltersInDict(key, value)
2670
+ elif isinstance(value, list):
2671
+ ProcessListFiltersInList(key, value)
2672
+
2673
+
2674
+ def ProcessListFiltersInList(name, the_list):
2675
+ for item in the_list:
2676
+ if isinstance(item, dict):
2677
+ ProcessListFiltersInDict(name, item)
2678
+ elif isinstance(item, list):
2679
+ ProcessListFiltersInList(name, item)
2680
+
2681
+
2682
+ def ValidateTargetType(target, target_dict):
2683
+ """Ensures the 'type' field on the target is one of the known types.
2684
+
2685
+ Arguments:
2686
+ target: string, name of target.
2687
+ target_dict: dict, target spec.
2688
+
2689
+ Raises an exception on error.
2690
+ """
2691
+ VALID_TARGET_TYPES = (
2692
+ "executable",
2693
+ "loadable_module",
2694
+ "static_library",
2695
+ "shared_library",
2696
+ "mac_kernel_extension",
2697
+ "none",
2698
+ "windows_driver",
2699
+ )
2700
+ target_type = target_dict.get("type", None)
2701
+ if target_type not in VALID_TARGET_TYPES:
2702
+ raise GypError(
2703
+ "Target %s has an invalid target type '%s'. "
2704
+ "Must be one of %s." % (target, target_type, "/".join(VALID_TARGET_TYPES))
2705
+ )
2706
+ if (
2707
+ target_dict.get("standalone_static_library", 0)
2708
+ and not target_type == "static_library"
2709
+ ):
2710
+ raise GypError(
2711
+ "Target %s has type %s but standalone_static_library flag is"
2712
+ " only valid for static_library type." % (target, target_type)
2713
+ )
2714
+
2715
+
2716
+ def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules):
2717
+ """Ensures that the rules sections in target_dict are valid and consistent,
2718
+ and determines which sources they apply to.
2719
+
2720
+ Arguments:
2721
+ target: string, name of target.
2722
+ target_dict: dict, target spec containing "rules" and "sources" lists.
2723
+ extra_sources_for_rules: a list of keys to scan for rule matches in
2724
+ addition to 'sources'.
2725
+ """
2726
+
2727
+ # Dicts to map between values found in rules' 'rule_name' and 'extension'
2728
+ # keys and the rule dicts themselves.
2729
+ rule_names = {}
2730
+ rule_extensions = {}
2731
+
2732
+ rules = target_dict.get("rules", [])
2733
+ for rule in rules:
2734
+ # Make sure that there's no conflict among rule names and extensions.
2735
+ rule_name = rule["rule_name"]
2736
+ if rule_name in rule_names:
2737
+ raise GypError(
2738
+ f"rule {rule_name} exists in duplicate, target {target}"
2739
+ )
2740
+ rule_names[rule_name] = rule
2741
+
2742
+ rule_extension = rule["extension"]
2743
+ if rule_extension.startswith("."):
2744
+ rule_extension = rule_extension[1:]
2745
+ if rule_extension in rule_extensions:
2746
+ raise GypError(
2747
+ (
2748
+ "extension %s associated with multiple rules, "
2749
+ + "target %s rules %s and %s"
2750
+ )
2751
+ % (
2752
+ rule_extension,
2753
+ target,
2754
+ rule_extensions[rule_extension]["rule_name"],
2755
+ rule_name,
2756
+ )
2757
+ )
2758
+ rule_extensions[rule_extension] = rule
2759
+
2760
+ # Make sure rule_sources isn't already there. It's going to be
2761
+ # created below if needed.
2762
+ if "rule_sources" in rule:
2763
+ raise GypError(
2764
+ "rule_sources must not exist in input, target %s rule %s"
2765
+ % (target, rule_name)
2766
+ )
2767
+
2768
+ rule_sources = []
2769
+ source_keys = ["sources"]
2770
+ source_keys.extend(extra_sources_for_rules)
2771
+ for source_key in source_keys:
2772
+ for source in target_dict.get(source_key, []):
2773
+ (source_root, source_extension) = os.path.splitext(source)
2774
+ if source_extension.startswith("."):
2775
+ source_extension = source_extension[1:]
2776
+ if source_extension == rule_extension:
2777
+ rule_sources.append(source)
2778
+
2779
+ if len(rule_sources) > 0:
2780
+ rule["rule_sources"] = rule_sources
2781
+
2782
+
2783
+ def ValidateRunAsInTarget(target, target_dict, build_file):
2784
+ target_name = target_dict.get("target_name")
2785
+ run_as = target_dict.get("run_as")
2786
+ if not run_as:
2787
+ return
2788
+ if not isinstance(run_as, dict):
2789
+ raise GypError(
2790
+ "The 'run_as' in target %s from file %s should be a "
2791
+ "dictionary." % (target_name, build_file)
2792
+ )
2793
+ action = run_as.get("action")
2794
+ if not action:
2795
+ raise GypError(
2796
+ "The 'run_as' in target %s from file %s must have an "
2797
+ "'action' section." % (target_name, build_file)
2798
+ )
2799
+ if not isinstance(action, list):
2800
+ raise GypError(
2801
+ "The 'action' for 'run_as' in target %s from file %s "
2802
+ "must be a list." % (target_name, build_file)
2803
+ )
2804
+ working_directory = run_as.get("working_directory")
2805
+ if working_directory and not isinstance(working_directory, str):
2806
+ raise GypError(
2807
+ "The 'working_directory' for 'run_as' in target %s "
2808
+ "in file %s should be a string." % (target_name, build_file)
2809
+ )
2810
+ environment = run_as.get("environment")
2811
+ if environment and not isinstance(environment, dict):
2812
+ raise GypError(
2813
+ "The 'environment' for 'run_as' in target %s "
2814
+ "in file %s should be a dictionary." % (target_name, build_file)
2815
+ )
2816
+
2817
+
2818
+ def ValidateActionsInTarget(target, target_dict, build_file):
2819
+ """Validates the inputs to the actions in a target."""
2820
+ target_name = target_dict.get("target_name")
2821
+ actions = target_dict.get("actions", [])
2822
+ for action in actions:
2823
+ action_name = action.get("action_name")
2824
+ if not action_name:
2825
+ raise GypError(
2826
+ "Anonymous action in target %s. "
2827
+ "An action must have an 'action_name' field." % target_name
2828
+ )
2829
+ inputs = action.get("inputs", None)
2830
+ if inputs is None:
2831
+ raise GypError("Action in target %s has no inputs." % target_name)
2832
+ action_command = action.get("action")
2833
+ if action_command and not action_command[0]:
2834
+ raise GypError("Empty action as command in target %s." % target_name)
2835
+
2836
+
2837
+ def TurnIntIntoStrInDict(the_dict):
2838
+ """Given dict the_dict, recursively converts all integers into strings.
2839
+ """
2840
+ # Use items instead of iteritems because there's no need to try to look at
2841
+ # reinserted keys and their associated values.
2842
+ for k, v in the_dict.items():
2843
+ if isinstance(v, int):
2844
+ v = str(v)
2845
+ the_dict[k] = v
2846
+ elif isinstance(v, dict):
2847
+ TurnIntIntoStrInDict(v)
2848
+ elif isinstance(v, list):
2849
+ TurnIntIntoStrInList(v)
2850
+
2851
+ if isinstance(k, int):
2852
+ del the_dict[k]
2853
+ the_dict[str(k)] = v
2854
+
2855
+
2856
+ def TurnIntIntoStrInList(the_list):
2857
+ """Given list the_list, recursively converts all integers into strings.
2858
+ """
2859
+ for index, item in enumerate(the_list):
2860
+ if isinstance(item, int):
2861
+ the_list[index] = str(item)
2862
+ elif isinstance(item, dict):
2863
+ TurnIntIntoStrInDict(item)
2864
+ elif isinstance(item, list):
2865
+ TurnIntIntoStrInList(item)
2866
+
2867
+
2868
+ def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, data):
2869
+ """Return only the targets that are deep dependencies of |root_targets|."""
2870
+ qualified_root_targets = []
2871
+ for target in root_targets:
2872
+ target = target.strip()
2873
+ qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list)
2874
+ if not qualified_targets:
2875
+ raise GypError("Could not find target %s" % target)
2876
+ qualified_root_targets.extend(qualified_targets)
2877
+
2878
+ wanted_targets = {}
2879
+ for target in qualified_root_targets:
2880
+ wanted_targets[target] = targets[target]
2881
+ for dependency in dependency_nodes[target].DeepDependencies():
2882
+ wanted_targets[dependency] = targets[dependency]
2883
+
2884
+ wanted_flat_list = [t for t in flat_list if t in wanted_targets]
2885
+
2886
+ # Prune unwanted targets from each build_file's data dict.
2887
+ for build_file in data["target_build_files"]:
2888
+ if "targets" not in data[build_file]:
2889
+ continue
2890
+ new_targets = []
2891
+ for target in data[build_file]["targets"]:
2892
+ qualified_name = gyp.common.QualifiedTarget(
2893
+ build_file, target["target_name"], target["toolset"]
2894
+ )
2895
+ if qualified_name in wanted_targets:
2896
+ new_targets.append(target)
2897
+ data[build_file]["targets"] = new_targets
2898
+
2899
+ return wanted_targets, wanted_flat_list
2900
+
2901
+
2902
+ def VerifyNoCollidingTargets(targets):
2903
+ """Verify that no two targets in the same directory share the same name.
2904
+
2905
+ Arguments:
2906
+ targets: A list of targets in the form 'path/to/file.gyp:target_name'.
2907
+ """
2908
+ # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'.
2909
+ used = {}
2910
+ for target in targets:
2911
+ # Separate out 'path/to/file.gyp, 'target_name' from
2912
+ # 'path/to/file.gyp:target_name'.
2913
+ path, name = target.rsplit(":", 1)
2914
+ # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'.
2915
+ subdir, gyp = os.path.split(path)
2916
+ # Use '.' for the current directory '', so that the error messages make
2917
+ # more sense.
2918
+ if not subdir:
2919
+ subdir = "."
2920
+ # Prepare a key like 'path/to:target_name'.
2921
+ key = subdir + ":" + name
2922
+ if key in used:
2923
+ # Complain if this target is already used.
2924
+ raise GypError(
2925
+ 'Duplicate target name "%s" in directory "%s" used both '
2926
+ 'in "%s" and "%s".' % (name, subdir, gyp, used[key])
2927
+ )
2928
+ used[key] = gyp
2929
+
2930
+
2931
+ def SetGeneratorGlobals(generator_input_info):
2932
+ # Set up path_sections and non_configuration_keys with the default data plus
2933
+ # the generator-specific data.
2934
+ global path_sections
2935
+ path_sections = set(base_path_sections)
2936
+ path_sections.update(generator_input_info["path_sections"])
2937
+
2938
+ global non_configuration_keys
2939
+ non_configuration_keys = base_non_configuration_keys[:]
2940
+ non_configuration_keys.extend(generator_input_info["non_configuration_keys"])
2941
+
2942
+ global multiple_toolsets
2943
+ multiple_toolsets = generator_input_info["generator_supports_multiple_toolsets"]
2944
+
2945
+ global generator_filelist_paths
2946
+ generator_filelist_paths = generator_input_info["generator_filelist_paths"]
2947
+
2948
+
2949
+ def Load(
2950
+ build_files,
2951
+ variables,
2952
+ includes,
2953
+ depth,
2954
+ generator_input_info,
2955
+ check,
2956
+ circular_check,
2957
+ parallel,
2958
+ root_targets,
2959
+ ):
2960
+ SetGeneratorGlobals(generator_input_info)
2961
+ # A generator can have other lists (in addition to sources) be processed
2962
+ # for rules.
2963
+ extra_sources_for_rules = generator_input_info["extra_sources_for_rules"]
2964
+
2965
+ # Load build files. This loads every target-containing build file into
2966
+ # the |data| dictionary such that the keys to |data| are build file names,
2967
+ # and the values are the entire build file contents after "early" or "pre"
2968
+ # processing has been done and includes have been resolved.
2969
+ # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as
2970
+ # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps
2971
+ # track of the keys corresponding to "target" files.
2972
+ data = {"target_build_files": set()}
2973
+ # Normalize paths everywhere. This is important because paths will be
2974
+ # used as keys to the data dict and for references between input files.
2975
+ build_files = set(map(os.path.normpath, build_files))
2976
+ if parallel:
2977
+ LoadTargetBuildFilesParallel(
2978
+ build_files, data, variables, includes, depth, check, generator_input_info
2979
+ )
2980
+ else:
2981
+ aux_data = {}
2982
+ for build_file in build_files:
2983
+ try:
2984
+ LoadTargetBuildFile(
2985
+ build_file, data, aux_data, variables, includes, depth, check, True
2986
+ )
2987
+ except Exception as e:
2988
+ gyp.common.ExceptionAppend(e, "while trying to load %s" % build_file)
2989
+ raise
2990
+
2991
+ # Build a dict to access each target's subdict by qualified name.
2992
+ targets = BuildTargetsDict(data)
2993
+
2994
+ # Fully qualify all dependency links.
2995
+ QualifyDependencies(targets)
2996
+
2997
+ # Remove self-dependencies from targets that have 'prune_self_dependencies'
2998
+ # set to 1.
2999
+ RemoveSelfDependencies(targets)
3000
+
3001
+ # Expand dependencies specified as build_file:*.
3002
+ ExpandWildcardDependencies(targets, data)
3003
+
3004
+ # Remove all dependencies marked as 'link_dependency' from the targets of
3005
+ # type 'none'.
3006
+ RemoveLinkDependenciesFromNoneTargets(targets)
3007
+
3008
+ # Apply exclude (!) and regex (/) list filters only for dependency_sections.
3009
+ for target_name, target_dict in targets.items():
3010
+ tmp_dict = {}
3011
+ for key_base in dependency_sections:
3012
+ for op in ("", "!", "/"):
3013
+ key = key_base + op
3014
+ if key in target_dict:
3015
+ tmp_dict[key] = target_dict[key]
3016
+ del target_dict[key]
3017
+ ProcessListFiltersInDict(target_name, tmp_dict)
3018
+ # Write the results back to |target_dict|.
3019
+ for key, value in tmp_dict.items():
3020
+ target_dict[key] = value
3021
+
3022
+ # Make sure every dependency appears at most once.
3023
+ RemoveDuplicateDependencies(targets)
3024
+
3025
+ if circular_check:
3026
+ # Make sure that any targets in a.gyp don't contain dependencies in other
3027
+ # .gyp files that further depend on a.gyp.
3028
+ VerifyNoGYPFileCircularDependencies(targets)
3029
+
3030
+ [dependency_nodes, flat_list] = BuildDependencyList(targets)
3031
+
3032
+ if root_targets:
3033
+ # Remove, from |targets| and |flat_list|, the targets that are not deep
3034
+ # dependencies of the targets specified in |root_targets|.
3035
+ targets, flat_list = PruneUnwantedTargets(
3036
+ targets, flat_list, dependency_nodes, root_targets, data
3037
+ )
3038
+
3039
+ # Check that no two targets in the same directory have the same name.
3040
+ VerifyNoCollidingTargets(flat_list)
3041
+
3042
+ # Handle dependent settings of various types.
3043
+ for settings_type in [
3044
+ "all_dependent_settings",
3045
+ "direct_dependent_settings",
3046
+ "link_settings",
3047
+ ]:
3048
+ DoDependentSettings(settings_type, flat_list, targets, dependency_nodes)
3049
+
3050
+ # Take out the dependent settings now that they've been published to all
3051
+ # of the targets that require them.
3052
+ for target in flat_list:
3053
+ if settings_type in targets[target]:
3054
+ del targets[target][settings_type]
3055
+
3056
+ # Make sure static libraries don't declare dependencies on other static
3057
+ # libraries, but that linkables depend on all unlinked static libraries
3058
+ # that they need so that their link steps will be correct.
3059
+ gii = generator_input_info
3060
+ if gii["generator_wants_static_library_dependencies_adjusted"]:
3061
+ AdjustStaticLibraryDependencies(
3062
+ flat_list,
3063
+ targets,
3064
+ dependency_nodes,
3065
+ gii["generator_wants_sorted_dependencies"],
3066
+ )
3067
+
3068
+ # Apply "post"/"late"/"target" variable expansions and condition evaluations.
3069
+ for target in flat_list:
3070
+ target_dict = targets[target]
3071
+ build_file = gyp.common.BuildFile(target)
3072
+ ProcessVariablesAndConditionsInDict(
3073
+ target_dict, PHASE_LATE, variables, build_file
3074
+ )
3075
+
3076
+ # Move everything that can go into a "configurations" section into one.
3077
+ for target in flat_list:
3078
+ target_dict = targets[target]
3079
+ SetUpConfigurations(target, target_dict)
3080
+
3081
+ # Apply exclude (!) and regex (/) list filters.
3082
+ for target in flat_list:
3083
+ target_dict = targets[target]
3084
+ ProcessListFiltersInDict(target, target_dict)
3085
+
3086
+ # Apply "latelate" variable expansions and condition evaluations.
3087
+ for target in flat_list:
3088
+ target_dict = targets[target]
3089
+ build_file = gyp.common.BuildFile(target)
3090
+ ProcessVariablesAndConditionsInDict(
3091
+ target_dict, PHASE_LATELATE, variables, build_file
3092
+ )
3093
+
3094
+ # Make sure that the rules make sense, and build up rule_sources lists as
3095
+ # needed. Not all generators will need to use the rule_sources lists, but
3096
+ # some may, and it seems best to build the list in a common spot.
3097
+ # Also validate actions and run_as elements in targets.
3098
+ for target in flat_list:
3099
+ target_dict = targets[target]
3100
+ build_file = gyp.common.BuildFile(target)
3101
+ ValidateTargetType(target, target_dict)
3102
+ ValidateRulesInTarget(target, target_dict, extra_sources_for_rules)
3103
+ ValidateRunAsInTarget(target, target_dict, build_file)
3104
+ ValidateActionsInTarget(target, target_dict, build_file)
3105
+
3106
+ # Generators might not expect ints. Turn them into strs.
3107
+ TurnIntIntoStrInDict(data)
3108
+
3109
+ # TODO(mark): Return |data| for now because the generator needs a list of
3110
+ # build files that came in. In the future, maybe it should just accept
3111
+ # a list, and not the whole data dict.
3112
+ return [flat_list, targets, data]