wsba-hockey 1.0.3__py3-none-any.whl → 1.0.4__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 (130) hide show
  1. wsba_hockey/data_pipelines.py +183 -0
  2. wsba_hockey/evidence/weakside-breakout/node_modules/duckdb/vendor.py +146 -0
  3. wsba_hockey/evidence/weakside-breakout/node_modules/flatted/python/flatted.py +149 -0
  4. wsba_hockey/evidence/weakside-breakout/node_modules/flatted/python/test.py +63 -0
  5. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  6. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +367 -0
  7. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  8. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1270 -0
  9. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  10. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  11. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +153 -0
  12. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +271 -0
  13. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  14. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +690 -0
  15. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/common.py +661 -0
  16. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +78 -0
  17. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +165 -0
  18. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +109 -0
  19. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  20. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  21. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +808 -0
  22. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1173 -0
  23. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1321 -0
  24. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +120 -0
  25. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +103 -0
  26. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +464 -0
  27. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  28. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +58 -0
  29. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2714 -0
  30. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3981 -0
  31. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  32. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2936 -0
  33. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +55 -0
  34. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1394 -0
  35. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +25 -0
  36. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/input.py +3130 -0
  37. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +98 -0
  38. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +771 -0
  39. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1271 -0
  40. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  41. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  42. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +374 -0
  43. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1939 -0
  44. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +302 -0
  45. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3197 -0
  46. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  47. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/test_gyp.py +261 -0
  48. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/graphviz.py +102 -0
  49. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/pretty_gyp.py +156 -0
  50. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/pretty_sln.py +181 -0
  51. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/pretty_vcproj.py +339 -0
  52. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/test/fixtures/test-charmap.py +31 -0
  53. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/update-gyp.py +64 -0
  54. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  55. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +367 -0
  56. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  57. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1270 -0
  58. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  59. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  60. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +153 -0
  61. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +271 -0
  62. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  63. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +666 -0
  64. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/common.py +654 -0
  65. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +78 -0
  66. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +165 -0
  67. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +109 -0
  68. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  69. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  70. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +808 -0
  71. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1173 -0
  72. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1321 -0
  73. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +120 -0
  74. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +103 -0
  75. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +464 -0
  76. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  77. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +58 -0
  78. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2518 -0
  79. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3978 -0
  80. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  81. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2936 -0
  82. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +55 -0
  83. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1394 -0
  84. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +25 -0
  85. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/input.py +3137 -0
  86. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +98 -0
  87. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +771 -0
  88. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1271 -0
  89. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  90. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  91. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +374 -0
  92. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1939 -0
  93. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +302 -0
  94. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3197 -0
  95. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  96. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/setup.py +42 -0
  97. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/test_gyp.py +260 -0
  98. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/graphviz.py +102 -0
  99. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/pretty_gyp.py +156 -0
  100. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/pretty_sln.py +181 -0
  101. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/pretty_vcproj.py +339 -0
  102. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/test/fixtures/test-charmap.py +31 -0
  103. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/update-gyp.py +46 -0
  104. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/game_stats/app.py +401 -0
  105. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/game_stats/name_fix.py +47 -0
  106. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/heatmaps/app.py +108 -0
  107. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/heatmaps/plot.py +93 -0
  108. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/heatmaps/rink_plot.py +245 -0
  109. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/matchups/app.py +145 -0
  110. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/matchups/plot.py +77 -0
  111. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/matchups/rink_plot.py +245 -0
  112. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/pbp/app.py +389 -0
  113. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/pbp/plot.py +70 -0
  114. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/pbp/rink_plot.py +245 -0
  115. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/skater/app.py +110 -0
  116. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/skater/plot.py +58 -0
  117. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/skater/rink_plot.py +245 -0
  118. wsba_hockey/tools/agg.py +242 -53
  119. wsba_hockey/tools/plotting.py +12 -17
  120. wsba_hockey/tools/scraping.py +149 -258
  121. wsba_hockey/tools/xg_model.py +357 -311
  122. wsba_hockey/workspace.py +22 -117
  123. wsba_hockey/wsba_main.py +493 -165
  124. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.4.dist-info}/METADATA +1 -1
  125. wsba_hockey-1.0.4.dist-info/RECORD +135 -0
  126. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.4.dist-info}/WHEEL +1 -1
  127. wsba_hockey/stats/calculate_viz/shot_impact.py +0 -2
  128. wsba_hockey-1.0.3.dist-info/RECORD +0 -19
  129. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.4.dist-info}/licenses/LICENSE +0 -0
  130. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.4.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,3130 @@
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
+
8
+ import gyp.common
9
+ import gyp.simple_copy
10
+ import multiprocessing
11
+ import os.path
12
+ import re
13
+ import shlex
14
+ import signal
15
+ import subprocess
16
+ import sys
17
+ import threading
18
+ import traceback
19
+ from distutils.version import StrictVersion
20
+ from gyp.common import GypError
21
+ from gyp.common import 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 type(build_file_data) is not 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 type(v) is dict:
307
+ LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, None, check)
308
+ elif type(v) is 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 type(item) is dict:
316
+ LoadBuildFileIncludesIntoDict(
317
+ item, sublist_path, data, aux_data, None, check
318
+ )
319
+ elif type(item) is 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 type(condition) is list:
354
+ for condition_dict in condition[1:]:
355
+ if type(condition_dict) is 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 type(string) is 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 type(cmd) is 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
+ if type(contents) is list:
874
+ contents_list = contents
875
+ else:
876
+ contents_list = contents.split(" ")
877
+ replacement = contents_list[0]
878
+ if os.path.isabs(replacement):
879
+ raise GypError('| cannot handle absolute paths, got "%s"' % replacement)
880
+
881
+ if not generator_filelist_paths:
882
+ path = os.path.join(build_file_dir, replacement)
883
+ else:
884
+ if os.path.isabs(build_file_dir):
885
+ toplevel = generator_filelist_paths["toplevel"]
886
+ rel_build_file_dir = gyp.common.RelativePath(
887
+ build_file_dir, toplevel
888
+ )
889
+ else:
890
+ rel_build_file_dir = build_file_dir
891
+ qualified_out_dir = generator_filelist_paths["qualified_out_dir"]
892
+ path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement)
893
+ gyp.common.EnsureDirExists(path)
894
+
895
+ replacement = gyp.common.RelativePath(path, build_file_dir)
896
+ f = gyp.common.WriteOnDiff(path)
897
+ for i in contents_list[1:]:
898
+ f.write("%s\n" % i)
899
+ f.close()
900
+
901
+ elif run_command:
902
+ use_shell = True
903
+ if match["is_array"]:
904
+ contents = eval(contents)
905
+ use_shell = False
906
+
907
+ # Check for a cached value to avoid executing commands, or generating
908
+ # file lists more than once. The cache key contains the command to be
909
+ # run as well as the directory to run it from, to account for commands
910
+ # that depend on their current directory.
911
+ # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory,
912
+ # someone could author a set of GYP files where each time the command
913
+ # is invoked it produces different output by design. When the need
914
+ # arises, the syntax should be extended to support no caching off a
915
+ # command's output so it is run every time.
916
+ cache_key = (str(contents), build_file_dir)
917
+ cached_value = cached_command_results.get(cache_key, None)
918
+ if cached_value is None:
919
+ gyp.DebugOutput(
920
+ gyp.DEBUG_VARIABLES,
921
+ "Executing command '%s' in directory '%s'",
922
+ contents,
923
+ build_file_dir,
924
+ )
925
+
926
+ replacement = ""
927
+
928
+ if command_string == "pymod_do_main":
929
+ # <!pymod_do_main(modulename param eters) loads |modulename| as a
930
+ # python module and then calls that module's DoMain() function,
931
+ # passing ["param", "eters"] as a single list argument. For modules
932
+ # that don't load quickly, this can be faster than
933
+ # <!(python modulename param eters). Do this in |build_file_dir|.
934
+ oldwd = os.getcwd() # Python doesn't like os.open('.'): no fchdir.
935
+ if build_file_dir: # build_file_dir may be None (see above).
936
+ os.chdir(build_file_dir)
937
+ sys.path.append(os.getcwd())
938
+ try:
939
+
940
+ parsed_contents = shlex.split(contents)
941
+ try:
942
+ py_module = __import__(parsed_contents[0])
943
+ except ImportError as e:
944
+ raise GypError(
945
+ "Error importing pymod_do_main"
946
+ "module (%s): %s" % (parsed_contents[0], e)
947
+ )
948
+ replacement = str(
949
+ py_module.DoMain(parsed_contents[1:])
950
+ ).rstrip()
951
+ finally:
952
+ sys.path.pop()
953
+ os.chdir(oldwd)
954
+ assert replacement is not None
955
+ elif command_string:
956
+ raise GypError(
957
+ "Unknown command string '%s' in '%s'."
958
+ % (command_string, contents)
959
+ )
960
+ else:
961
+ # Fix up command with platform specific workarounds.
962
+ contents = FixupPlatformCommand(contents)
963
+ try:
964
+ # stderr will be printed no matter what
965
+ result = subprocess.run(
966
+ contents,
967
+ stdout=subprocess.PIPE,
968
+ shell=use_shell,
969
+ cwd=build_file_dir,
970
+ check=False
971
+ )
972
+ except Exception as e:
973
+ raise GypError(
974
+ "%s while executing command '%s' in %s"
975
+ % (e, contents, build_file)
976
+ )
977
+
978
+ if result.returncode > 0:
979
+ raise GypError(
980
+ "Call to '%s' returned exit status %d while in %s."
981
+ % (contents, result.returncode, build_file)
982
+ )
983
+ replacement = result.stdout.decode("utf-8").rstrip()
984
+
985
+ cached_command_results[cache_key] = replacement
986
+ else:
987
+ gyp.DebugOutput(
988
+ gyp.DEBUG_VARIABLES,
989
+ "Had cache value for command '%s' in directory '%s'",
990
+ contents,
991
+ build_file_dir,
992
+ )
993
+ replacement = cached_value
994
+
995
+ else:
996
+ if contents not in variables:
997
+ if contents[-1] in ["!", "/"]:
998
+ # In order to allow cross-compiles (nacl) to happen more naturally,
999
+ # we will allow references to >(sources/) etc. to resolve to
1000
+ # and empty list if undefined. This allows actions to:
1001
+ # 'action!': [
1002
+ # '>@(_sources!)',
1003
+ # ],
1004
+ # 'action/': [
1005
+ # '>@(_sources/)',
1006
+ # ],
1007
+ replacement = []
1008
+ else:
1009
+ raise GypError(
1010
+ "Undefined variable " + contents + " in " + build_file
1011
+ )
1012
+ else:
1013
+ replacement = variables[contents]
1014
+
1015
+ if isinstance(replacement, bytes) and not isinstance(replacement, str):
1016
+ replacement = replacement.decode("utf-8") # done on Python 3 only
1017
+ if type(replacement) is list:
1018
+ for item in replacement:
1019
+ if isinstance(item, bytes) and not isinstance(item, str):
1020
+ item = item.decode("utf-8") # done on Python 3 only
1021
+ if not contents[-1] == "/" and type(item) not in (str, int):
1022
+ raise GypError(
1023
+ "Variable "
1024
+ + contents
1025
+ + " must expand to a string or list of strings; "
1026
+ + "list contains a "
1027
+ + item.__class__.__name__
1028
+ )
1029
+ # Run through the list and handle variable expansions in it. Since
1030
+ # the list is guaranteed not to contain dicts, this won't do anything
1031
+ # with conditions sections.
1032
+ ProcessVariablesAndConditionsInList(
1033
+ replacement, phase, variables, build_file
1034
+ )
1035
+ elif type(replacement) not in (str, int):
1036
+ raise GypError(
1037
+ "Variable "
1038
+ + contents
1039
+ + " must expand to a string or list of strings; "
1040
+ + "found a "
1041
+ + replacement.__class__.__name__
1042
+ )
1043
+
1044
+ if expand_to_list:
1045
+ # Expanding in list context. It's guaranteed that there's only one
1046
+ # replacement to do in |input_str| and that it's this replacement. See
1047
+ # above.
1048
+ if type(replacement) is list:
1049
+ # If it's already a list, make a copy.
1050
+ output = replacement[:]
1051
+ else:
1052
+ # Split it the same way sh would split arguments.
1053
+ output = shlex.split(str(replacement))
1054
+ else:
1055
+ # Expanding in string context.
1056
+ encoded_replacement = ""
1057
+ if type(replacement) is list:
1058
+ # When expanding a list into string context, turn the list items
1059
+ # into a string in a way that will work with a subprocess call.
1060
+ #
1061
+ # TODO(mark): This isn't completely correct. This should
1062
+ # call a generator-provided function that observes the
1063
+ # proper list-to-argument quoting rules on a specific
1064
+ # platform instead of just calling the POSIX encoding
1065
+ # routine.
1066
+ encoded_replacement = gyp.common.EncodePOSIXShellList(replacement)
1067
+ else:
1068
+ encoded_replacement = replacement
1069
+
1070
+ output = (
1071
+ output[:replace_start] + str(encoded_replacement) + output[replace_end:]
1072
+ )
1073
+ # Prepare for the next match iteration.
1074
+ input_str = output
1075
+
1076
+ if output == input:
1077
+ gyp.DebugOutput(
1078
+ gyp.DEBUG_VARIABLES,
1079
+ "Found only identity matches on %r, avoiding infinite " "recursion.",
1080
+ output,
1081
+ )
1082
+ else:
1083
+ # Look for more matches now that we've replaced some, to deal with
1084
+ # expanding local variables (variables defined in the same
1085
+ # variables block as this one).
1086
+ gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %r, recursing.", output)
1087
+ if type(output) is list:
1088
+ if output and type(output[0]) is list:
1089
+ # Leave output alone if it's a list of lists.
1090
+ # We don't want such lists to be stringified.
1091
+ pass
1092
+ else:
1093
+ new_output = []
1094
+ for item in output:
1095
+ new_output.append(
1096
+ ExpandVariables(item, phase, variables, build_file)
1097
+ )
1098
+ output = new_output
1099
+ else:
1100
+ output = ExpandVariables(output, phase, variables, build_file)
1101
+
1102
+ # Convert all strings that are canonically-represented integers into integers.
1103
+ if type(output) is list:
1104
+ for index, outstr in enumerate(output):
1105
+ if IsStrCanonicalInt(outstr):
1106
+ output[index] = int(outstr)
1107
+ elif IsStrCanonicalInt(output):
1108
+ output = int(output)
1109
+
1110
+ return output
1111
+
1112
+
1113
+ # The same condition is often evaluated over and over again so it
1114
+ # makes sense to cache as much as possible between evaluations.
1115
+ cached_conditions_asts = {}
1116
+
1117
+
1118
+ def EvalCondition(condition, conditions_key, phase, variables, build_file):
1119
+ """Returns the dict that should be used or None if the result was
1120
+ that nothing should be used."""
1121
+ if type(condition) is not list:
1122
+ raise GypError(conditions_key + " must be a list")
1123
+ if len(condition) < 2:
1124
+ # It's possible that condition[0] won't work in which case this
1125
+ # attempt will raise its own IndexError. That's probably fine.
1126
+ raise GypError(
1127
+ conditions_key
1128
+ + " "
1129
+ + condition[0]
1130
+ + " must be at least length 2, not "
1131
+ + str(len(condition))
1132
+ )
1133
+
1134
+ i = 0
1135
+ result = None
1136
+ while i < len(condition):
1137
+ cond_expr = condition[i]
1138
+ true_dict = condition[i + 1]
1139
+ if type(true_dict) is not dict:
1140
+ raise GypError(
1141
+ "{} {} must be followed by a dictionary, not {}".format(
1142
+ conditions_key, cond_expr, type(true_dict)
1143
+ )
1144
+ )
1145
+ if len(condition) > i + 2 and type(condition[i + 2]) is dict:
1146
+ false_dict = condition[i + 2]
1147
+ i = i + 3
1148
+ if i != len(condition):
1149
+ raise GypError(
1150
+ "{} {} has {} unexpected trailing items".format(
1151
+ conditions_key, cond_expr, len(condition) - i
1152
+ )
1153
+ )
1154
+ else:
1155
+ false_dict = None
1156
+ i = i + 2
1157
+ if result is None:
1158
+ result = EvalSingleCondition(
1159
+ cond_expr, true_dict, false_dict, phase, variables, build_file
1160
+ )
1161
+
1162
+ return result
1163
+
1164
+
1165
+ def EvalSingleCondition(cond_expr, true_dict, false_dict, phase, variables, build_file):
1166
+ """Returns true_dict if cond_expr evaluates to true, and false_dict
1167
+ otherwise."""
1168
+ # Do expansions on the condition itself. Since the condition can naturally
1169
+ # contain variable references without needing to resort to GYP expansion
1170
+ # syntax, this is of dubious value for variables, but someone might want to
1171
+ # use a command expansion directly inside a condition.
1172
+ cond_expr_expanded = ExpandVariables(cond_expr, phase, variables, build_file)
1173
+ if type(cond_expr_expanded) not in (str, int):
1174
+ raise ValueError(
1175
+ "Variable expansion in this context permits str and int "
1176
+ + "only, found "
1177
+ + cond_expr_expanded.__class__.__name__
1178
+ )
1179
+
1180
+ try:
1181
+ if cond_expr_expanded in cached_conditions_asts:
1182
+ ast_code = cached_conditions_asts[cond_expr_expanded]
1183
+ else:
1184
+ ast_code = compile(cond_expr_expanded, "<string>", "eval")
1185
+ cached_conditions_asts[cond_expr_expanded] = ast_code
1186
+ env = {"__builtins__": {}, "v": StrictVersion}
1187
+ if eval(ast_code, env, variables):
1188
+ return true_dict
1189
+ return false_dict
1190
+ except SyntaxError as e:
1191
+ syntax_error = SyntaxError(
1192
+ "%s while evaluating condition '%s' in %s "
1193
+ "at character %d." % (str(e.args[0]), e.text, build_file, e.offset),
1194
+ e.filename,
1195
+ e.lineno,
1196
+ e.offset,
1197
+ e.text,
1198
+ )
1199
+ raise syntax_error
1200
+ except NameError as e:
1201
+ gyp.common.ExceptionAppend(
1202
+ e,
1203
+ f"while evaluating condition '{cond_expr_expanded}' in {build_file}",
1204
+ )
1205
+ raise GypError(e)
1206
+
1207
+
1208
+ def ProcessConditionsInDict(the_dict, phase, variables, build_file):
1209
+ # Process a 'conditions' or 'target_conditions' section in the_dict,
1210
+ # depending on phase.
1211
+ # early -> conditions
1212
+ # late -> target_conditions
1213
+ # latelate -> no conditions
1214
+ #
1215
+ # Each item in a conditions list consists of cond_expr, a string expression
1216
+ # evaluated as the condition, and true_dict, a dict that will be merged into
1217
+ # the_dict if cond_expr evaluates to true. Optionally, a third item,
1218
+ # false_dict, may be present. false_dict is merged into the_dict if
1219
+ # cond_expr evaluates to false.
1220
+ #
1221
+ # Any dict merged into the_dict will be recursively processed for nested
1222
+ # conditionals and other expansions, also according to phase, immediately
1223
+ # prior to being merged.
1224
+
1225
+ if phase == PHASE_EARLY:
1226
+ conditions_key = "conditions"
1227
+ elif phase == PHASE_LATE:
1228
+ conditions_key = "target_conditions"
1229
+ elif phase == PHASE_LATELATE:
1230
+ return
1231
+ else:
1232
+ assert False
1233
+
1234
+ if conditions_key not in the_dict:
1235
+ return
1236
+
1237
+ conditions_list = the_dict[conditions_key]
1238
+ # Unhook the conditions list, it's no longer needed.
1239
+ del the_dict[conditions_key]
1240
+
1241
+ for condition in conditions_list:
1242
+ merge_dict = EvalCondition(
1243
+ condition, conditions_key, phase, variables, build_file
1244
+ )
1245
+
1246
+ if merge_dict is not None:
1247
+ # Expand variables and nested conditinals in the merge_dict before
1248
+ # merging it.
1249
+ ProcessVariablesAndConditionsInDict(
1250
+ merge_dict, phase, variables, build_file
1251
+ )
1252
+
1253
+ MergeDicts(the_dict, merge_dict, build_file, build_file)
1254
+
1255
+
1256
+ def LoadAutomaticVariablesFromDict(variables, the_dict):
1257
+ # Any keys with plain string values in the_dict become automatic variables.
1258
+ # The variable name is the key name with a "_" character prepended.
1259
+ for key, value in the_dict.items():
1260
+ if type(value) in (str, int, list):
1261
+ variables["_" + key] = value
1262
+
1263
+
1264
+ def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key):
1265
+ # Any keys in the_dict's "variables" dict, if it has one, becomes a
1266
+ # variable. The variable name is the key name in the "variables" dict.
1267
+ # Variables that end with the % character are set only if they are unset in
1268
+ # the variables dict. the_dict_key is the name of the key that accesses
1269
+ # the_dict in the_dict's parent dict. If the_dict's parent is not a dict
1270
+ # (it could be a list or it could be parentless because it is a root dict),
1271
+ # the_dict_key will be None.
1272
+ for key, value in the_dict.get("variables", {}).items():
1273
+ if type(value) not in (str, int, list):
1274
+ continue
1275
+
1276
+ if key.endswith("%"):
1277
+ variable_name = key[:-1]
1278
+ if variable_name in variables:
1279
+ # If the variable is already set, don't set it.
1280
+ continue
1281
+ if the_dict_key == "variables" and variable_name in the_dict:
1282
+ # If the variable is set without a % in the_dict, and the_dict is a
1283
+ # variables dict (making |variables| a variables sub-dict of a
1284
+ # variables dict), use the_dict's definition.
1285
+ value = the_dict[variable_name]
1286
+ else:
1287
+ variable_name = key
1288
+
1289
+ variables[variable_name] = value
1290
+
1291
+
1292
+ def ProcessVariablesAndConditionsInDict(
1293
+ the_dict, phase, variables_in, build_file, the_dict_key=None
1294
+ ):
1295
+ """Handle all variable and command expansion and conditional evaluation.
1296
+
1297
+ This function is the public entry point for all variable expansions and
1298
+ conditional evaluations. The variables_in dictionary will not be modified
1299
+ by this function.
1300
+ """
1301
+
1302
+ # Make a copy of the variables_in dict that can be modified during the
1303
+ # loading of automatics and the loading of the variables dict.
1304
+ variables = variables_in.copy()
1305
+ LoadAutomaticVariablesFromDict(variables, the_dict)
1306
+
1307
+ if "variables" in the_dict:
1308
+ # Make sure all the local variables are added to the variables
1309
+ # list before we process them so that you can reference one
1310
+ # variable from another. They will be fully expanded by recursion
1311
+ # in ExpandVariables.
1312
+ for key, value in the_dict["variables"].items():
1313
+ variables[key] = value
1314
+
1315
+ # Handle the associated variables dict first, so that any variable
1316
+ # references within can be resolved prior to using them as variables.
1317
+ # Pass a copy of the variables dict to avoid having it be tainted.
1318
+ # Otherwise, it would have extra automatics added for everything that
1319
+ # should just be an ordinary variable in this scope.
1320
+ ProcessVariablesAndConditionsInDict(
1321
+ the_dict["variables"], phase, variables, build_file, "variables"
1322
+ )
1323
+
1324
+ LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
1325
+
1326
+ for key, value in the_dict.items():
1327
+ # Skip "variables", which was already processed if present.
1328
+ if key != "variables" and type(value) is str:
1329
+ expanded = ExpandVariables(value, phase, variables, build_file)
1330
+ if type(expanded) not in (str, int):
1331
+ raise ValueError(
1332
+ "Variable expansion in this context permits str and int "
1333
+ + "only, found "
1334
+ + expanded.__class__.__name__
1335
+ + " for "
1336
+ + key
1337
+ )
1338
+ the_dict[key] = expanded
1339
+
1340
+ # Variable expansion may have resulted in changes to automatics. Reload.
1341
+ # TODO(mark): Optimization: only reload if no changes were made.
1342
+ variables = variables_in.copy()
1343
+ LoadAutomaticVariablesFromDict(variables, the_dict)
1344
+ LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
1345
+
1346
+ # Process conditions in this dict. This is done after variable expansion
1347
+ # so that conditions may take advantage of expanded variables. For example,
1348
+ # if the_dict contains:
1349
+ # {'type': '<(library_type)',
1350
+ # 'conditions': [['_type=="static_library"', { ... }]]},
1351
+ # _type, as used in the condition, will only be set to the value of
1352
+ # library_type if variable expansion is performed before condition
1353
+ # processing. However, condition processing should occur prior to recursion
1354
+ # so that variables (both automatic and "variables" dict type) may be
1355
+ # adjusted by conditions sections, merged into the_dict, and have the
1356
+ # intended impact on contained dicts.
1357
+ #
1358
+ # This arrangement means that a "conditions" section containing a "variables"
1359
+ # section will only have those variables effective in subdicts, not in
1360
+ # the_dict. The workaround is to put a "conditions" section within a
1361
+ # "variables" section. For example:
1362
+ # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]],
1363
+ # 'defines': ['<(define)'],
1364
+ # 'my_subdict': {'defines': ['<(define)']}},
1365
+ # will not result in "IS_MAC" being appended to the "defines" list in the
1366
+ # current scope but would result in it being appended to the "defines" list
1367
+ # within "my_subdict". By comparison:
1368
+ # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]},
1369
+ # 'defines': ['<(define)'],
1370
+ # 'my_subdict': {'defines': ['<(define)']}},
1371
+ # will append "IS_MAC" to both "defines" lists.
1372
+
1373
+ # Evaluate conditions sections, allowing variable expansions within them
1374
+ # as well as nested conditionals. This will process a 'conditions' or
1375
+ # 'target_conditions' section, perform appropriate merging and recursive
1376
+ # conditional and variable processing, and then remove the conditions section
1377
+ # from the_dict if it is present.
1378
+ ProcessConditionsInDict(the_dict, phase, variables, build_file)
1379
+
1380
+ # Conditional processing may have resulted in changes to automatics or the
1381
+ # variables dict. Reload.
1382
+ variables = variables_in.copy()
1383
+ LoadAutomaticVariablesFromDict(variables, the_dict)
1384
+ LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key)
1385
+
1386
+ # Recurse into child dicts, or process child lists which may result in
1387
+ # further recursion into descendant dicts.
1388
+ for key, value in the_dict.items():
1389
+ # Skip "variables" and string values, which were already processed if
1390
+ # present.
1391
+ if key == "variables" or type(value) is str:
1392
+ continue
1393
+ if type(value) is dict:
1394
+ # Pass a copy of the variables dict so that subdicts can't influence
1395
+ # parents.
1396
+ ProcessVariablesAndConditionsInDict(
1397
+ value, phase, variables, build_file, key
1398
+ )
1399
+ elif type(value) is list:
1400
+ # The list itself can't influence the variables dict, and
1401
+ # ProcessVariablesAndConditionsInList will make copies of the variables
1402
+ # dict if it needs to pass it to something that can influence it. No
1403
+ # copy is necessary here.
1404
+ ProcessVariablesAndConditionsInList(value, phase, variables, build_file)
1405
+ elif type(value) is not int:
1406
+ raise TypeError("Unknown type " + value.__class__.__name__ + " for " + key)
1407
+
1408
+
1409
+ def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file):
1410
+ # Iterate using an index so that new values can be assigned into the_list.
1411
+ index = 0
1412
+ while index < len(the_list):
1413
+ item = the_list[index]
1414
+ if type(item) is dict:
1415
+ # Make a copy of the variables dict so that it won't influence anything
1416
+ # outside of its own scope.
1417
+ ProcessVariablesAndConditionsInDict(item, phase, variables, build_file)
1418
+ elif type(item) is list:
1419
+ ProcessVariablesAndConditionsInList(item, phase, variables, build_file)
1420
+ elif type(item) is str:
1421
+ expanded = ExpandVariables(item, phase, variables, build_file)
1422
+ if type(expanded) in (str, int):
1423
+ the_list[index] = expanded
1424
+ elif type(expanded) is list:
1425
+ the_list[index : index + 1] = expanded
1426
+ index += len(expanded)
1427
+
1428
+ # index now identifies the next item to examine. Continue right now
1429
+ # without falling into the index increment below.
1430
+ continue
1431
+ else:
1432
+ raise ValueError(
1433
+ "Variable expansion in this context permits strings and "
1434
+ + "lists only, found "
1435
+ + expanded.__class__.__name__
1436
+ + " at "
1437
+ + index
1438
+ )
1439
+ elif type(item) is not int:
1440
+ raise TypeError(
1441
+ "Unknown type " + item.__class__.__name__ + " at index " + index
1442
+ )
1443
+ index = index + 1
1444
+
1445
+
1446
+ def BuildTargetsDict(data):
1447
+ """Builds a dict mapping fully-qualified target names to their target dicts.
1448
+
1449
+ |data| is a dict mapping loaded build files by pathname relative to the
1450
+ current directory. Values in |data| are build file contents. For each
1451
+ |data| value with a "targets" key, the value of the "targets" key is taken
1452
+ as a list containing target dicts. Each target's fully-qualified name is
1453
+ constructed from the pathname of the build file (|data| key) and its
1454
+ "target_name" property. These fully-qualified names are used as the keys
1455
+ in the returned dict. These keys provide access to the target dicts,
1456
+ the dicts in the "targets" lists.
1457
+ """
1458
+
1459
+ targets = {}
1460
+ for build_file in data["target_build_files"]:
1461
+ for target in data[build_file].get("targets", []):
1462
+ target_name = gyp.common.QualifiedTarget(
1463
+ build_file, target["target_name"], target["toolset"]
1464
+ )
1465
+ if target_name in targets:
1466
+ raise GypError("Duplicate target definitions for " + target_name)
1467
+ targets[target_name] = target
1468
+
1469
+ return targets
1470
+
1471
+
1472
+ def QualifyDependencies(targets):
1473
+ """Make dependency links fully-qualified relative to the current directory.
1474
+
1475
+ |targets| is a dict mapping fully-qualified target names to their target
1476
+ dicts. For each target in this dict, keys known to contain dependency
1477
+ links are examined, and any dependencies referenced will be rewritten
1478
+ so that they are fully-qualified and relative to the current directory.
1479
+ All rewritten dependencies are suitable for use as keys to |targets| or a
1480
+ similar dict.
1481
+ """
1482
+
1483
+ all_dependency_sections = [
1484
+ dep + op for dep in dependency_sections for op in ("", "!", "/")
1485
+ ]
1486
+
1487
+ for target, target_dict in targets.items():
1488
+ target_build_file = gyp.common.BuildFile(target)
1489
+ toolset = target_dict["toolset"]
1490
+ for dependency_key in all_dependency_sections:
1491
+ dependencies = target_dict.get(dependency_key, [])
1492
+ for index, dep in enumerate(dependencies):
1493
+ dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget(
1494
+ target_build_file, dep, toolset
1495
+ )
1496
+ if not multiple_toolsets:
1497
+ # Ignore toolset specification in the dependency if it is specified.
1498
+ dep_toolset = toolset
1499
+ dependency = gyp.common.QualifiedTarget(
1500
+ dep_file, dep_target, dep_toolset
1501
+ )
1502
+ dependencies[index] = dependency
1503
+
1504
+ # Make sure anything appearing in a list other than "dependencies" also
1505
+ # appears in the "dependencies" list.
1506
+ if (
1507
+ dependency_key != "dependencies"
1508
+ and dependency not in target_dict["dependencies"]
1509
+ ):
1510
+ raise GypError(
1511
+ "Found "
1512
+ + dependency
1513
+ + " in "
1514
+ + dependency_key
1515
+ + " of "
1516
+ + target
1517
+ + ", but not in dependencies"
1518
+ )
1519
+
1520
+
1521
+ def ExpandWildcardDependencies(targets, data):
1522
+ """Expands dependencies specified as build_file:*.
1523
+
1524
+ For each target in |targets|, examines sections containing links to other
1525
+ targets. If any such section contains a link of the form build_file:*, it
1526
+ is taken as a wildcard link, and is expanded to list each target in
1527
+ build_file. The |data| dict provides access to build file dicts.
1528
+
1529
+ Any target that does not wish to be included by wildcard can provide an
1530
+ optional "suppress_wildcard" key in its target dict. When present and
1531
+ true, a wildcard dependency link will not include such targets.
1532
+
1533
+ All dependency names, including the keys to |targets| and the values in each
1534
+ dependency list, must be qualified when this function is called.
1535
+ """
1536
+
1537
+ for target, target_dict in targets.items():
1538
+ target_build_file = gyp.common.BuildFile(target)
1539
+ for dependency_key in dependency_sections:
1540
+ dependencies = target_dict.get(dependency_key, [])
1541
+
1542
+ # Loop this way instead of "for dependency in" or "for index in range"
1543
+ # because the dependencies list will be modified within the loop body.
1544
+ index = 0
1545
+ while index < len(dependencies):
1546
+ (
1547
+ dependency_build_file,
1548
+ dependency_target,
1549
+ dependency_toolset,
1550
+ ) = gyp.common.ParseQualifiedTarget(dependencies[index])
1551
+ if dependency_target != "*" and dependency_toolset != "*":
1552
+ # Not a wildcard. Keep it moving.
1553
+ index = index + 1
1554
+ continue
1555
+
1556
+ if dependency_build_file == target_build_file:
1557
+ # It's an error for a target to depend on all other targets in
1558
+ # the same file, because a target cannot depend on itself.
1559
+ raise GypError(
1560
+ "Found wildcard in "
1561
+ + dependency_key
1562
+ + " of "
1563
+ + target
1564
+ + " referring to same build file"
1565
+ )
1566
+
1567
+ # Take the wildcard out and adjust the index so that the next
1568
+ # dependency in the list will be processed the next time through the
1569
+ # loop.
1570
+ del dependencies[index]
1571
+ index = index - 1
1572
+
1573
+ # Loop through the targets in the other build file, adding them to
1574
+ # this target's list of dependencies in place of the removed
1575
+ # wildcard.
1576
+ dependency_target_dicts = data[dependency_build_file]["targets"]
1577
+ for dependency_target_dict in dependency_target_dicts:
1578
+ if int(dependency_target_dict.get("suppress_wildcard", False)):
1579
+ continue
1580
+ dependency_target_name = dependency_target_dict["target_name"]
1581
+ if (
1582
+ dependency_target != "*"
1583
+ and dependency_target != dependency_target_name
1584
+ ):
1585
+ continue
1586
+ dependency_target_toolset = dependency_target_dict["toolset"]
1587
+ if (
1588
+ dependency_toolset != "*"
1589
+ and dependency_toolset != dependency_target_toolset
1590
+ ):
1591
+ continue
1592
+ dependency = gyp.common.QualifiedTarget(
1593
+ dependency_build_file,
1594
+ dependency_target_name,
1595
+ dependency_target_toolset,
1596
+ )
1597
+ index = index + 1
1598
+ dependencies.insert(index, dependency)
1599
+
1600
+ index = index + 1
1601
+
1602
+
1603
+ def Unify(items):
1604
+ """Removes duplicate elements from items, keeping the first element."""
1605
+ seen = {}
1606
+ return [seen.setdefault(e, e) for e in items if e not in seen]
1607
+
1608
+
1609
+ def RemoveDuplicateDependencies(targets):
1610
+ """Makes sure every dependency appears only once in all targets's dependency
1611
+ lists."""
1612
+ for target_name, target_dict in targets.items():
1613
+ for dependency_key in dependency_sections:
1614
+ dependencies = target_dict.get(dependency_key, [])
1615
+ if dependencies:
1616
+ target_dict[dependency_key] = Unify(dependencies)
1617
+
1618
+
1619
+ def Filter(items, item):
1620
+ """Removes item from items."""
1621
+ res = {}
1622
+ return [res.setdefault(e, e) for e in items if e != item]
1623
+
1624
+
1625
+ def RemoveSelfDependencies(targets):
1626
+ """Remove self dependencies from targets that have the prune_self_dependency
1627
+ variable set."""
1628
+ for target_name, target_dict in targets.items():
1629
+ for dependency_key in dependency_sections:
1630
+ dependencies = target_dict.get(dependency_key, [])
1631
+ if dependencies:
1632
+ for t in dependencies:
1633
+ if t == target_name:
1634
+ if (
1635
+ targets[t]
1636
+ .get("variables", {})
1637
+ .get("prune_self_dependency", 0)
1638
+ ):
1639
+ target_dict[dependency_key] = Filter(
1640
+ dependencies, target_name
1641
+ )
1642
+
1643
+
1644
+ def RemoveLinkDependenciesFromNoneTargets(targets):
1645
+ """Remove dependencies having the 'link_dependency' attribute from the 'none'
1646
+ targets."""
1647
+ for target_name, target_dict in targets.items():
1648
+ for dependency_key in dependency_sections:
1649
+ dependencies = target_dict.get(dependency_key, [])
1650
+ if dependencies:
1651
+ for t in dependencies:
1652
+ if target_dict.get("type", None) == "none":
1653
+ if targets[t].get("variables", {}).get("link_dependency", 0):
1654
+ target_dict[dependency_key] = Filter(
1655
+ target_dict[dependency_key], t
1656
+ )
1657
+
1658
+
1659
+ class DependencyGraphNode:
1660
+ """
1661
+
1662
+ Attributes:
1663
+ ref: A reference to an object that this DependencyGraphNode represents.
1664
+ dependencies: List of DependencyGraphNodes on which this one depends.
1665
+ dependents: List of DependencyGraphNodes that depend on this one.
1666
+ """
1667
+
1668
+ class CircularException(GypError):
1669
+ pass
1670
+
1671
+ def __init__(self, ref):
1672
+ self.ref = ref
1673
+ self.dependencies = []
1674
+ self.dependents = []
1675
+
1676
+ def __repr__(self):
1677
+ return "<DependencyGraphNode: %r>" % self.ref
1678
+
1679
+ def FlattenToList(self):
1680
+ # flat_list is the sorted list of dependencies - actually, the list items
1681
+ # are the "ref" attributes of DependencyGraphNodes. Every target will
1682
+ # appear in flat_list after all of its dependencies, and before all of its
1683
+ # dependents.
1684
+ flat_list = OrderedSet()
1685
+
1686
+ def ExtractNodeRef(node):
1687
+ """Extracts the object that the node represents from the given node."""
1688
+ return node.ref
1689
+
1690
+ # in_degree_zeros is the list of DependencyGraphNodes that have no
1691
+ # dependencies not in flat_list. Initially, it is a copy of the children
1692
+ # of this node, because when the graph was built, nodes with no
1693
+ # dependencies were made implicit dependents of the root node.
1694
+ in_degree_zeros = sorted(self.dependents[:], key=ExtractNodeRef)
1695
+
1696
+ while in_degree_zeros:
1697
+ # Nodes in in_degree_zeros have no dependencies not in flat_list, so they
1698
+ # can be appended to flat_list. Take these nodes out of in_degree_zeros
1699
+ # as work progresses, so that the next node to process from the list can
1700
+ # always be accessed at a consistent position.
1701
+ node = in_degree_zeros.pop()
1702
+ flat_list.add(node.ref)
1703
+
1704
+ # Look at dependents of the node just added to flat_list. Some of them
1705
+ # may now belong in in_degree_zeros.
1706
+ for node_dependent in sorted(node.dependents, key=ExtractNodeRef):
1707
+ is_in_degree_zero = True
1708
+ # TODO: We want to check through the
1709
+ # node_dependent.dependencies list but if it's long and we
1710
+ # always start at the beginning, then we get O(n^2) behaviour.
1711
+ for node_dependent_dependency in sorted(
1712
+ node_dependent.dependencies, key=ExtractNodeRef
1713
+ ):
1714
+ if node_dependent_dependency.ref not in flat_list:
1715
+ # The dependent one or more dependencies not in flat_list.
1716
+ # There will be more chances to add it to flat_list
1717
+ # when examining it again as a dependent of those other
1718
+ # dependencies, provided that there are no cycles.
1719
+ is_in_degree_zero = False
1720
+ break
1721
+
1722
+ if is_in_degree_zero:
1723
+ # All of the dependent's dependencies are already in flat_list. Add
1724
+ # it to in_degree_zeros where it will be processed in a future
1725
+ # iteration of the outer loop.
1726
+ in_degree_zeros += [node_dependent]
1727
+
1728
+ return list(flat_list)
1729
+
1730
+ def FindCycles(self):
1731
+ """
1732
+ Returns a list of cycles in the graph, where each cycle is its own list.
1733
+ """
1734
+ results = []
1735
+ visited = set()
1736
+
1737
+ def Visit(node, path):
1738
+ for child in node.dependents:
1739
+ if child in path:
1740
+ results.append([child] + path[: path.index(child) + 1])
1741
+ elif child not in visited:
1742
+ visited.add(child)
1743
+ Visit(child, [child] + path)
1744
+
1745
+ visited.add(self)
1746
+ Visit(self, [self])
1747
+
1748
+ return results
1749
+
1750
+ def DirectDependencies(self, dependencies=None):
1751
+ """Returns a list of just direct dependencies."""
1752
+ if dependencies is None:
1753
+ dependencies = []
1754
+
1755
+ for dependency in self.dependencies:
1756
+ # Check for None, corresponding to the root node.
1757
+ if dependency.ref and dependency.ref not in dependencies:
1758
+ dependencies.append(dependency.ref)
1759
+
1760
+ return dependencies
1761
+
1762
+ def _AddImportedDependencies(self, targets, dependencies=None):
1763
+ """Given a list of direct dependencies, adds indirect dependencies that
1764
+ other dependencies have declared to export their settings.
1765
+
1766
+ This method does not operate on self. Rather, it operates on the list
1767
+ of dependencies in the |dependencies| argument. For each dependency in
1768
+ that list, if any declares that it exports the settings of one of its
1769
+ own dependencies, those dependencies whose settings are "passed through"
1770
+ are added to the list. As new items are added to the list, they too will
1771
+ be processed, so it is possible to import settings through multiple levels
1772
+ of dependencies.
1773
+
1774
+ This method is not terribly useful on its own, it depends on being
1775
+ "primed" with a list of direct dependencies such as one provided by
1776
+ DirectDependencies. DirectAndImportedDependencies is intended to be the
1777
+ public entry point.
1778
+ """
1779
+
1780
+ if dependencies is None:
1781
+ dependencies = []
1782
+
1783
+ index = 0
1784
+ while index < len(dependencies):
1785
+ dependency = dependencies[index]
1786
+ dependency_dict = targets[dependency]
1787
+ # Add any dependencies whose settings should be imported to the list
1788
+ # if not already present. Newly-added items will be checked for
1789
+ # their own imports when the list iteration reaches them.
1790
+ # Rather than simply appending new items, insert them after the
1791
+ # dependency that exported them. This is done to more closely match
1792
+ # the depth-first method used by DeepDependencies.
1793
+ add_index = 1
1794
+ for imported_dependency in dependency_dict.get(
1795
+ "export_dependent_settings", []
1796
+ ):
1797
+ if imported_dependency not in dependencies:
1798
+ dependencies.insert(index + add_index, imported_dependency)
1799
+ add_index = add_index + 1
1800
+ index = index + 1
1801
+
1802
+ return dependencies
1803
+
1804
+ def DirectAndImportedDependencies(self, targets, dependencies=None):
1805
+ """Returns a list of a target's direct dependencies and all indirect
1806
+ dependencies that a dependency has advertised settings should be exported
1807
+ through the dependency for.
1808
+ """
1809
+
1810
+ dependencies = self.DirectDependencies(dependencies)
1811
+ return self._AddImportedDependencies(targets, dependencies)
1812
+
1813
+ def DeepDependencies(self, dependencies=None):
1814
+ """Returns an OrderedSet of all of a target's dependencies, recursively."""
1815
+ if dependencies is None:
1816
+ # Using a list to get ordered output and a set to do fast "is it
1817
+ # already added" checks.
1818
+ dependencies = OrderedSet()
1819
+
1820
+ for dependency in self.dependencies:
1821
+ # Check for None, corresponding to the root node.
1822
+ if dependency.ref is None:
1823
+ continue
1824
+ if dependency.ref not in dependencies:
1825
+ dependency.DeepDependencies(dependencies)
1826
+ dependencies.add(dependency.ref)
1827
+
1828
+ return dependencies
1829
+
1830
+ def _LinkDependenciesInternal(
1831
+ self, targets, include_shared_libraries, dependencies=None, initial=True
1832
+ ):
1833
+ """Returns an OrderedSet of dependency targets that are linked
1834
+ into this target.
1835
+
1836
+ This function has a split personality, depending on the setting of
1837
+ |initial|. Outside callers should always leave |initial| at its default
1838
+ setting.
1839
+
1840
+ When adding a target to the list of dependencies, this function will
1841
+ recurse into itself with |initial| set to False, to collect dependencies
1842
+ that are linked into the linkable target for which the list is being built.
1843
+
1844
+ If |include_shared_libraries| is False, the resulting dependencies will not
1845
+ include shared_library targets that are linked into this target.
1846
+ """
1847
+ if dependencies is None:
1848
+ # Using a list to get ordered output and a set to do fast "is it
1849
+ # already added" checks.
1850
+ dependencies = OrderedSet()
1851
+
1852
+ # Check for None, corresponding to the root node.
1853
+ if self.ref is None:
1854
+ return dependencies
1855
+
1856
+ # It's kind of sucky that |targets| has to be passed into this function,
1857
+ # but that's presently the easiest way to access the target dicts so that
1858
+ # this function can find target types.
1859
+
1860
+ if "target_name" not in targets[self.ref]:
1861
+ raise GypError("Missing 'target_name' field in target.")
1862
+
1863
+ if "type" not in targets[self.ref]:
1864
+ raise GypError(
1865
+ "Missing 'type' field in target %s" % targets[self.ref]["target_name"]
1866
+ )
1867
+
1868
+ target_type = targets[self.ref]["type"]
1869
+
1870
+ is_linkable = target_type in linkable_types
1871
+
1872
+ if initial and not is_linkable:
1873
+ # If this is the first target being examined and it's not linkable,
1874
+ # return an empty list of link dependencies, because the link
1875
+ # dependencies are intended to apply to the target itself (initial is
1876
+ # True) and this target won't be linked.
1877
+ return dependencies
1878
+
1879
+ # Don't traverse 'none' targets if explicitly excluded.
1880
+ if target_type == "none" and not targets[self.ref].get(
1881
+ "dependencies_traverse", True
1882
+ ):
1883
+ dependencies.add(self.ref)
1884
+ return dependencies
1885
+
1886
+ # Executables, mac kernel extensions, windows drivers and loadable modules
1887
+ # are already fully and finally linked. Nothing else can be a link
1888
+ # dependency of them, there can only be dependencies in the sense that a
1889
+ # dependent target might run an executable or load the loadable_module.
1890
+ if not initial and target_type in (
1891
+ "executable",
1892
+ "loadable_module",
1893
+ "mac_kernel_extension",
1894
+ "windows_driver",
1895
+ ):
1896
+ return dependencies
1897
+
1898
+ # Shared libraries are already fully linked. They should only be included
1899
+ # in |dependencies| when adjusting static library dependencies (in order to
1900
+ # link against the shared_library's import lib), but should not be included
1901
+ # in |dependencies| when propagating link_settings.
1902
+ # The |include_shared_libraries| flag controls which of these two cases we
1903
+ # are handling.
1904
+ if (
1905
+ not initial
1906
+ and target_type == "shared_library"
1907
+ and not include_shared_libraries
1908
+ ):
1909
+ return dependencies
1910
+
1911
+ # The target is linkable, add it to the list of link dependencies.
1912
+ if self.ref not in dependencies:
1913
+ dependencies.add(self.ref)
1914
+ if initial or not is_linkable:
1915
+ # If this is a subsequent target and it's linkable, don't look any
1916
+ # further for linkable dependencies, as they'll already be linked into
1917
+ # this target linkable. Always look at dependencies of the initial
1918
+ # target, and always look at dependencies of non-linkables.
1919
+ for dependency in self.dependencies:
1920
+ dependency._LinkDependenciesInternal(
1921
+ targets, include_shared_libraries, dependencies, False
1922
+ )
1923
+
1924
+ return dependencies
1925
+
1926
+ def DependenciesForLinkSettings(self, targets):
1927
+ """
1928
+ Returns a list of dependency targets whose link_settings should be merged
1929
+ into this target.
1930
+ """
1931
+
1932
+ # TODO(sbaig) Currently, chrome depends on the bug that shared libraries'
1933
+ # link_settings are propagated. So for now, we will allow it, unless the
1934
+ # 'allow_sharedlib_linksettings_propagation' flag is explicitly set to
1935
+ # False. Once chrome is fixed, we can remove this flag.
1936
+ include_shared_libraries = targets[self.ref].get(
1937
+ "allow_sharedlib_linksettings_propagation", True
1938
+ )
1939
+ return self._LinkDependenciesInternal(targets, include_shared_libraries)
1940
+
1941
+ def DependenciesToLinkAgainst(self, targets):
1942
+ """
1943
+ Returns a list of dependency targets that are linked into this target.
1944
+ """
1945
+ return self._LinkDependenciesInternal(targets, True)
1946
+
1947
+
1948
+ def BuildDependencyList(targets):
1949
+ # Create a DependencyGraphNode for each target. Put it into a dict for easy
1950
+ # access.
1951
+ dependency_nodes = {}
1952
+ for target, spec in targets.items():
1953
+ if target not in dependency_nodes:
1954
+ dependency_nodes[target] = DependencyGraphNode(target)
1955
+
1956
+ # Set up the dependency links. Targets that have no dependencies are treated
1957
+ # as dependent on root_node.
1958
+ root_node = DependencyGraphNode(None)
1959
+ for target, spec in targets.items():
1960
+ target_node = dependency_nodes[target]
1961
+ dependencies = spec.get("dependencies")
1962
+ if not dependencies:
1963
+ target_node.dependencies = [root_node]
1964
+ root_node.dependents.append(target_node)
1965
+ else:
1966
+ for dependency in dependencies:
1967
+ dependency_node = dependency_nodes.get(dependency)
1968
+ if not dependency_node:
1969
+ raise GypError(
1970
+ "Dependency '%s' not found while "
1971
+ "trying to load target %s" % (dependency, target)
1972
+ )
1973
+ target_node.dependencies.append(dependency_node)
1974
+ dependency_node.dependents.append(target_node)
1975
+
1976
+ flat_list = root_node.FlattenToList()
1977
+
1978
+ # If there's anything left unvisited, there must be a circular dependency
1979
+ # (cycle).
1980
+ if len(flat_list) != len(targets):
1981
+ if not root_node.dependents:
1982
+ # If all targets have dependencies, add the first target as a dependent
1983
+ # of root_node so that the cycle can be discovered from root_node.
1984
+ target = next(iter(targets))
1985
+ target_node = dependency_nodes[target]
1986
+ target_node.dependencies.append(root_node)
1987
+ root_node.dependents.append(target_node)
1988
+
1989
+ cycles = []
1990
+ for cycle in root_node.FindCycles():
1991
+ paths = [node.ref for node in cycle]
1992
+ cycles.append("Cycle: %s" % " -> ".join(paths))
1993
+ raise DependencyGraphNode.CircularException(
1994
+ "Cycles in dependency graph detected:\n" + "\n".join(cycles)
1995
+ )
1996
+
1997
+ return [dependency_nodes, flat_list]
1998
+
1999
+
2000
+ def VerifyNoGYPFileCircularDependencies(targets):
2001
+ # Create a DependencyGraphNode for each gyp file containing a target. Put
2002
+ # it into a dict for easy access.
2003
+ dependency_nodes = {}
2004
+ for target in targets:
2005
+ build_file = gyp.common.BuildFile(target)
2006
+ if build_file not in dependency_nodes:
2007
+ dependency_nodes[build_file] = DependencyGraphNode(build_file)
2008
+
2009
+ # Set up the dependency links.
2010
+ for target, spec in targets.items():
2011
+ build_file = gyp.common.BuildFile(target)
2012
+ build_file_node = dependency_nodes[build_file]
2013
+ target_dependencies = spec.get("dependencies", [])
2014
+ for dependency in target_dependencies:
2015
+ try:
2016
+ dependency_build_file = gyp.common.BuildFile(dependency)
2017
+ except GypError as e:
2018
+ gyp.common.ExceptionAppend(
2019
+ e, "while computing dependencies of .gyp file %s" % build_file
2020
+ )
2021
+ raise
2022
+
2023
+ if dependency_build_file == build_file:
2024
+ # A .gyp file is allowed to refer back to itself.
2025
+ continue
2026
+ dependency_node = dependency_nodes.get(dependency_build_file)
2027
+ if not dependency_node:
2028
+ raise GypError("Dependency '%s' not found" % dependency_build_file)
2029
+ if dependency_node not in build_file_node.dependencies:
2030
+ build_file_node.dependencies.append(dependency_node)
2031
+ dependency_node.dependents.append(build_file_node)
2032
+
2033
+ # Files that have no dependencies are treated as dependent on root_node.
2034
+ root_node = DependencyGraphNode(None)
2035
+ for build_file_node in dependency_nodes.values():
2036
+ if len(build_file_node.dependencies) == 0:
2037
+ build_file_node.dependencies.append(root_node)
2038
+ root_node.dependents.append(build_file_node)
2039
+
2040
+ flat_list = root_node.FlattenToList()
2041
+
2042
+ # If there's anything left unvisited, there must be a circular dependency
2043
+ # (cycle).
2044
+ if len(flat_list) != len(dependency_nodes):
2045
+ if not root_node.dependents:
2046
+ # If all files have dependencies, add the first file as a dependent
2047
+ # of root_node so that the cycle can be discovered from root_node.
2048
+ file_node = next(iter(dependency_nodes.values()))
2049
+ file_node.dependencies.append(root_node)
2050
+ root_node.dependents.append(file_node)
2051
+ cycles = []
2052
+ for cycle in root_node.FindCycles():
2053
+ paths = [node.ref for node in cycle]
2054
+ cycles.append("Cycle: %s" % " -> ".join(paths))
2055
+ raise DependencyGraphNode.CircularException(
2056
+ "Cycles in .gyp file dependency graph detected:\n" + "\n".join(cycles)
2057
+ )
2058
+
2059
+
2060
+ def DoDependentSettings(key, flat_list, targets, dependency_nodes):
2061
+ # key should be one of all_dependent_settings, direct_dependent_settings,
2062
+ # or link_settings.
2063
+
2064
+ for target in flat_list:
2065
+ target_dict = targets[target]
2066
+ build_file = gyp.common.BuildFile(target)
2067
+
2068
+ if key == "all_dependent_settings":
2069
+ dependencies = dependency_nodes[target].DeepDependencies()
2070
+ elif key == "direct_dependent_settings":
2071
+ dependencies = dependency_nodes[target].DirectAndImportedDependencies(
2072
+ targets
2073
+ )
2074
+ elif key == "link_settings":
2075
+ dependencies = dependency_nodes[target].DependenciesForLinkSettings(targets)
2076
+ else:
2077
+ raise GypError(
2078
+ "DoDependentSettings doesn't know how to determine "
2079
+ "dependencies for " + key
2080
+ )
2081
+
2082
+ for dependency in dependencies:
2083
+ dependency_dict = targets[dependency]
2084
+ if key not in dependency_dict:
2085
+ continue
2086
+ dependency_build_file = gyp.common.BuildFile(dependency)
2087
+ MergeDicts(
2088
+ target_dict, dependency_dict[key], build_file, dependency_build_file
2089
+ )
2090
+
2091
+
2092
+ def AdjustStaticLibraryDependencies(
2093
+ flat_list, targets, dependency_nodes, sort_dependencies
2094
+ ):
2095
+ # Recompute target "dependencies" properties. For each static library
2096
+ # target, remove "dependencies" entries referring to other static libraries,
2097
+ # unless the dependency has the "hard_dependency" attribute set. For each
2098
+ # linkable target, add a "dependencies" entry referring to all of the
2099
+ # target's computed list of link dependencies (including static libraries
2100
+ # if no such entry is already present.
2101
+ for target in flat_list:
2102
+ target_dict = targets[target]
2103
+ target_type = target_dict["type"]
2104
+
2105
+ if target_type == "static_library":
2106
+ if "dependencies" not in target_dict:
2107
+ continue
2108
+
2109
+ target_dict["dependencies_original"] = target_dict.get("dependencies", [])[
2110
+ :
2111
+ ]
2112
+
2113
+ # A static library should not depend on another static library unless
2114
+ # the dependency relationship is "hard," which should only be done when
2115
+ # a dependent relies on some side effect other than just the build
2116
+ # product, like a rule or action output. Further, if a target has a
2117
+ # non-hard dependency, but that dependency exports a hard dependency,
2118
+ # the non-hard dependency can safely be removed, but the exported hard
2119
+ # dependency must be added to the target to keep the same dependency
2120
+ # ordering.
2121
+ dependencies = dependency_nodes[target].DirectAndImportedDependencies(
2122
+ targets
2123
+ )
2124
+ index = 0
2125
+ while index < len(dependencies):
2126
+ dependency = dependencies[index]
2127
+ dependency_dict = targets[dependency]
2128
+
2129
+ # Remove every non-hard static library dependency and remove every
2130
+ # non-static library dependency that isn't a direct dependency.
2131
+ if (
2132
+ dependency_dict["type"] == "static_library"
2133
+ and not dependency_dict.get("hard_dependency", False)
2134
+ ) or (
2135
+ dependency_dict["type"] != "static_library"
2136
+ and dependency not in target_dict["dependencies"]
2137
+ ):
2138
+ # Take the dependency out of the list, and don't increment index
2139
+ # because the next dependency to analyze will shift into the index
2140
+ # formerly occupied by the one being removed.
2141
+ del dependencies[index]
2142
+ else:
2143
+ index = index + 1
2144
+
2145
+ # Update the dependencies. If the dependencies list is empty, it's not
2146
+ # needed, so unhook it.
2147
+ if len(dependencies) > 0:
2148
+ target_dict["dependencies"] = dependencies
2149
+ else:
2150
+ del target_dict["dependencies"]
2151
+
2152
+ elif target_type in linkable_types:
2153
+ # Get a list of dependency targets that should be linked into this
2154
+ # target. Add them to the dependencies list if they're not already
2155
+ # present.
2156
+
2157
+ link_dependencies = dependency_nodes[target].DependenciesToLinkAgainst(
2158
+ targets
2159
+ )
2160
+ for dependency in link_dependencies:
2161
+ if dependency == target:
2162
+ continue
2163
+ if "dependencies" not in target_dict:
2164
+ target_dict["dependencies"] = []
2165
+ if dependency not in target_dict["dependencies"]:
2166
+ target_dict["dependencies"].append(dependency)
2167
+ # Sort the dependencies list in the order from dependents to dependencies.
2168
+ # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D.
2169
+ # Note: flat_list is already sorted in the order from dependencies to
2170
+ # dependents.
2171
+ if sort_dependencies and "dependencies" in target_dict:
2172
+ target_dict["dependencies"] = [
2173
+ dep
2174
+ for dep in reversed(flat_list)
2175
+ if dep in target_dict["dependencies"]
2176
+ ]
2177
+
2178
+
2179
+ # Initialize this here to speed up MakePathRelative.
2180
+ exception_re = re.compile(r"""["']?[-/$<>^]""")
2181
+
2182
+
2183
+ def MakePathRelative(to_file, fro_file, item):
2184
+ # If item is a relative path, it's relative to the build file dict that it's
2185
+ # coming from. Fix it up to make it relative to the build file dict that
2186
+ # it's going into.
2187
+ # Exception: any |item| that begins with these special characters is
2188
+ # returned without modification.
2189
+ # / Used when a path is already absolute (shortcut optimization;
2190
+ # such paths would be returned as absolute anyway)
2191
+ # $ Used for build environment variables
2192
+ # - Used for some build environment flags (such as -lapr-1 in a
2193
+ # "libraries" section)
2194
+ # < Used for our own variable and command expansions (see ExpandVariables)
2195
+ # > Used for our own variable and command expansions (see ExpandVariables)
2196
+ # ^ Used for our own variable and command expansions (see ExpandVariables)
2197
+ #
2198
+ # "/' Used when a value is quoted. If these are present, then we
2199
+ # check the second character instead.
2200
+ #
2201
+ if to_file == fro_file or exception_re.match(item):
2202
+ return item
2203
+ else:
2204
+ # TODO(dglazkov) The backslash/forward-slash replacement at the end is a
2205
+ # temporary measure. This should really be addressed by keeping all paths
2206
+ # in POSIX until actual project generation.
2207
+ ret = os.path.normpath(
2208
+ os.path.join(
2209
+ gyp.common.RelativePath(
2210
+ os.path.dirname(fro_file), os.path.dirname(to_file)
2211
+ ),
2212
+ item,
2213
+ )
2214
+ ).replace("\\", "/")
2215
+ if item.endswith("/"):
2216
+ ret += "/"
2217
+ return ret
2218
+
2219
+
2220
+ def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True):
2221
+ # Python documentation recommends objects which do not support hash
2222
+ # set this value to None. Python library objects follow this rule.
2223
+ def is_hashable(val):
2224
+ return val.__hash__
2225
+
2226
+ # If x is hashable, returns whether x is in s. Else returns whether x is in items.
2227
+ def is_in_set_or_list(x, s, items):
2228
+ if is_hashable(x):
2229
+ return x in s
2230
+ return x in items
2231
+
2232
+ prepend_index = 0
2233
+
2234
+ # Make membership testing of hashables in |to| (in particular, strings)
2235
+ # faster.
2236
+ hashable_to_set = {x for x in to if is_hashable(x)}
2237
+ for item in fro:
2238
+ singleton = False
2239
+ if type(item) in (str, int):
2240
+ # The cheap and easy case.
2241
+ if is_paths:
2242
+ to_item = MakePathRelative(to_file, fro_file, item)
2243
+ else:
2244
+ to_item = item
2245
+
2246
+ if not (type(item) is str and item.startswith("-")):
2247
+ # Any string that doesn't begin with a "-" is a singleton - it can
2248
+ # only appear once in a list, to be enforced by the list merge append
2249
+ # or prepend.
2250
+ singleton = True
2251
+ elif type(item) is dict:
2252
+ # Make a copy of the dictionary, continuing to look for paths to fix.
2253
+ # The other intelligent aspects of merge processing won't apply because
2254
+ # item is being merged into an empty dict.
2255
+ to_item = {}
2256
+ MergeDicts(to_item, item, to_file, fro_file)
2257
+ elif type(item) is list:
2258
+ # Recurse, making a copy of the list. If the list contains any
2259
+ # descendant dicts, path fixing will occur. Note that here, custom
2260
+ # values for is_paths and append are dropped; those are only to be
2261
+ # applied to |to| and |fro|, not sublists of |fro|. append shouldn't
2262
+ # matter anyway because the new |to_item| list is empty.
2263
+ to_item = []
2264
+ MergeLists(to_item, item, to_file, fro_file)
2265
+ else:
2266
+ raise TypeError(
2267
+ "Attempt to merge list item of unsupported type "
2268
+ + item.__class__.__name__
2269
+ )
2270
+
2271
+ if append:
2272
+ # If appending a singleton that's already in the list, don't append.
2273
+ # This ensures that the earliest occurrence of the item will stay put.
2274
+ if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to):
2275
+ to.append(to_item)
2276
+ if is_hashable(to_item):
2277
+ hashable_to_set.add(to_item)
2278
+ else:
2279
+ # If prepending a singleton that's already in the list, remove the
2280
+ # existing instance and proceed with the prepend. This ensures that the
2281
+ # item appears at the earliest possible position in the list.
2282
+ while singleton and to_item in to:
2283
+ to.remove(to_item)
2284
+
2285
+ # Don't just insert everything at index 0. That would prepend the new
2286
+ # items to the list in reverse order, which would be an unwelcome
2287
+ # surprise.
2288
+ to.insert(prepend_index, to_item)
2289
+ if is_hashable(to_item):
2290
+ hashable_to_set.add(to_item)
2291
+ prepend_index = prepend_index + 1
2292
+
2293
+
2294
+ def MergeDicts(to, fro, to_file, fro_file):
2295
+ # I wanted to name the parameter "from" but it's a Python keyword...
2296
+ for k, v in fro.items():
2297
+ # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give
2298
+ # copy semantics. Something else may want to merge from the |fro| dict
2299
+ # later, and having the same dict ref pointed to twice in the tree isn't
2300
+ # what anyone wants considering that the dicts may subsequently be
2301
+ # modified.
2302
+ if k in to:
2303
+ bad_merge = False
2304
+ if type(v) in (str, int):
2305
+ if type(to[k]) not in (str, int):
2306
+ bad_merge = True
2307
+ elif not isinstance(v, type(to[k])):
2308
+ bad_merge = True
2309
+
2310
+ if bad_merge:
2311
+ raise TypeError(
2312
+ "Attempt to merge dict value of type "
2313
+ + v.__class__.__name__
2314
+ + " into incompatible type "
2315
+ + to[k].__class__.__name__
2316
+ + " for key "
2317
+ + k
2318
+ )
2319
+ if type(v) in (str, int):
2320
+ # Overwrite the existing value, if any. Cheap and easy.
2321
+ is_path = IsPathSection(k)
2322
+ if is_path:
2323
+ to[k] = MakePathRelative(to_file, fro_file, v)
2324
+ else:
2325
+ to[k] = v
2326
+ elif type(v) is dict:
2327
+ # Recurse, guaranteeing copies will be made of objects that require it.
2328
+ if k not in to:
2329
+ to[k] = {}
2330
+ MergeDicts(to[k], v, to_file, fro_file)
2331
+ elif type(v) is list:
2332
+ # Lists in dicts can be merged with different policies, depending on
2333
+ # how the key in the "from" dict (k, the from-key) is written.
2334
+ #
2335
+ # If the from-key has ...the to-list will have this action
2336
+ # this character appended:... applied when receiving the from-list:
2337
+ # = replace
2338
+ # + prepend
2339
+ # ? set, only if to-list does not yet exist
2340
+ # (none) append
2341
+ #
2342
+ # This logic is list-specific, but since it relies on the associated
2343
+ # dict key, it's checked in this dict-oriented function.
2344
+ ext = k[-1]
2345
+ append = True
2346
+ if ext == "=":
2347
+ list_base = k[:-1]
2348
+ lists_incompatible = [list_base, list_base + "?"]
2349
+ to[list_base] = []
2350
+ elif ext == "+":
2351
+ list_base = k[:-1]
2352
+ lists_incompatible = [list_base + "=", list_base + "?"]
2353
+ append = False
2354
+ elif ext == "?":
2355
+ list_base = k[:-1]
2356
+ lists_incompatible = [list_base, list_base + "=", list_base + "+"]
2357
+ else:
2358
+ list_base = k
2359
+ lists_incompatible = [list_base + "=", list_base + "?"]
2360
+
2361
+ # Some combinations of merge policies appearing together are meaningless.
2362
+ # It's stupid to replace and append simultaneously, for example. Append
2363
+ # and prepend are the only policies that can coexist.
2364
+ for list_incompatible in lists_incompatible:
2365
+ if list_incompatible in fro:
2366
+ raise GypError(
2367
+ "Incompatible list policies " + k + " and " + list_incompatible
2368
+ )
2369
+
2370
+ if list_base in to:
2371
+ if ext == "?":
2372
+ # If the key ends in "?", the list will only be merged if it doesn't
2373
+ # already exist.
2374
+ continue
2375
+ elif type(to[list_base]) is not list:
2376
+ # This may not have been checked above if merging in a list with an
2377
+ # extension character.
2378
+ raise TypeError(
2379
+ "Attempt to merge dict value of type "
2380
+ + v.__class__.__name__
2381
+ + " into incompatible type "
2382
+ + to[list_base].__class__.__name__
2383
+ + " for key "
2384
+ + list_base
2385
+ + "("
2386
+ + k
2387
+ + ")"
2388
+ )
2389
+ else:
2390
+ to[list_base] = []
2391
+
2392
+ # Call MergeLists, which will make copies of objects that require it.
2393
+ # MergeLists can recurse back into MergeDicts, although this will be
2394
+ # to make copies of dicts (with paths fixed), there will be no
2395
+ # subsequent dict "merging" once entering a list because lists are
2396
+ # always replaced, appended to, or prepended to.
2397
+ is_paths = IsPathSection(list_base)
2398
+ MergeLists(to[list_base], v, to_file, fro_file, is_paths, append)
2399
+ else:
2400
+ raise TypeError(
2401
+ "Attempt to merge dict value of unsupported type "
2402
+ + v.__class__.__name__
2403
+ + " for key "
2404
+ + k
2405
+ )
2406
+
2407
+
2408
+ def MergeConfigWithInheritance(
2409
+ new_configuration_dict, build_file, target_dict, configuration, visited
2410
+ ):
2411
+ # Skip if previously visited.
2412
+ if configuration in visited:
2413
+ return
2414
+
2415
+ # Look at this configuration.
2416
+ configuration_dict = target_dict["configurations"][configuration]
2417
+
2418
+ # Merge in parents.
2419
+ for parent in configuration_dict.get("inherit_from", []):
2420
+ MergeConfigWithInheritance(
2421
+ new_configuration_dict,
2422
+ build_file,
2423
+ target_dict,
2424
+ parent,
2425
+ visited + [configuration],
2426
+ )
2427
+
2428
+ # Merge it into the new config.
2429
+ MergeDicts(new_configuration_dict, configuration_dict, build_file, build_file)
2430
+
2431
+ # Drop abstract.
2432
+ if "abstract" in new_configuration_dict:
2433
+ del new_configuration_dict["abstract"]
2434
+
2435
+
2436
+ def SetUpConfigurations(target, target_dict):
2437
+ # key_suffixes is a list of key suffixes that might appear on key names.
2438
+ # These suffixes are handled in conditional evaluations (for =, +, and ?)
2439
+ # and rules/exclude processing (for ! and /). Keys with these suffixes
2440
+ # should be treated the same as keys without.
2441
+ key_suffixes = ["=", "+", "?", "!", "/"]
2442
+
2443
+ build_file = gyp.common.BuildFile(target)
2444
+
2445
+ # Provide a single configuration by default if none exists.
2446
+ # TODO(mark): Signal an error if default_configurations exists but
2447
+ # configurations does not.
2448
+ if "configurations" not in target_dict:
2449
+ target_dict["configurations"] = {"Default": {}}
2450
+ if "default_configuration" not in target_dict:
2451
+ concrete = [
2452
+ i
2453
+ for (i, config) in target_dict["configurations"].items()
2454
+ if not config.get("abstract")
2455
+ ]
2456
+ target_dict["default_configuration"] = sorted(concrete)[0]
2457
+
2458
+ merged_configurations = {}
2459
+ configs = target_dict["configurations"]
2460
+ for (configuration, old_configuration_dict) in configs.items():
2461
+ # Skip abstract configurations (saves work only).
2462
+ if old_configuration_dict.get("abstract"):
2463
+ continue
2464
+ # Configurations inherit (most) settings from the enclosing target scope.
2465
+ # Get the inheritance relationship right by making a copy of the target
2466
+ # dict.
2467
+ new_configuration_dict = {}
2468
+ for (key, target_val) in target_dict.items():
2469
+ key_ext = key[-1:]
2470
+ if key_ext in key_suffixes:
2471
+ key_base = key[:-1]
2472
+ else:
2473
+ key_base = key
2474
+ if key_base not in non_configuration_keys:
2475
+ new_configuration_dict[key] = gyp.simple_copy.deepcopy(target_val)
2476
+
2477
+ # Merge in configuration (with all its parents first).
2478
+ MergeConfigWithInheritance(
2479
+ new_configuration_dict, build_file, target_dict, configuration, []
2480
+ )
2481
+
2482
+ merged_configurations[configuration] = new_configuration_dict
2483
+
2484
+ # Put the new configurations back into the target dict as a configuration.
2485
+ for configuration in merged_configurations.keys():
2486
+ target_dict["configurations"][configuration] = merged_configurations[
2487
+ configuration
2488
+ ]
2489
+
2490
+ # Now drop all the abstract ones.
2491
+ configs = target_dict["configurations"]
2492
+ target_dict["configurations"] = {
2493
+ k: v for k, v in configs.items() if not v.get("abstract")
2494
+ }
2495
+
2496
+ # Now that all of the target's configurations have been built, go through
2497
+ # the target dict's keys and remove everything that's been moved into a
2498
+ # "configurations" section.
2499
+ delete_keys = []
2500
+ for key in target_dict:
2501
+ key_ext = key[-1:]
2502
+ if key_ext in key_suffixes:
2503
+ key_base = key[:-1]
2504
+ else:
2505
+ key_base = key
2506
+ if key_base not in non_configuration_keys:
2507
+ delete_keys.append(key)
2508
+ for key in delete_keys:
2509
+ del target_dict[key]
2510
+
2511
+ # Check the configurations to see if they contain invalid keys.
2512
+ for configuration in target_dict["configurations"].keys():
2513
+ configuration_dict = target_dict["configurations"][configuration]
2514
+ for key in configuration_dict.keys():
2515
+ if key in invalid_configuration_keys:
2516
+ raise GypError(
2517
+ "%s not allowed in the %s configuration, found in "
2518
+ "target %s" % (key, configuration, target)
2519
+ )
2520
+
2521
+
2522
+ def ProcessListFiltersInDict(name, the_dict):
2523
+ """Process regular expression and exclusion-based filters on lists.
2524
+
2525
+ An exclusion list is in a dict key named with a trailing "!", like
2526
+ "sources!". Every item in such a list is removed from the associated
2527
+ main list, which in this example, would be "sources". Removed items are
2528
+ placed into a "sources_excluded" list in the dict.
2529
+
2530
+ Regular expression (regex) filters are contained in dict keys named with a
2531
+ trailing "/", such as "sources/" to operate on the "sources" list. Regex
2532
+ filters in a dict take the form:
2533
+ 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
2534
+ ['include', '_mac\\.cc$'] ],
2535
+ The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
2536
+ _win.cc. The second filter then includes all files ending in _mac.cc that
2537
+ are now or were once in the "sources" list. Items matching an "exclude"
2538
+ filter are subject to the same processing as would occur if they were listed
2539
+ by name in an exclusion list (ending in "!"). Items matching an "include"
2540
+ filter are brought back into the main list if previously excluded by an
2541
+ exclusion list or exclusion regex filter. Subsequent matching "exclude"
2542
+ patterns can still cause items to be excluded after matching an "include".
2543
+ """
2544
+
2545
+ # Look through the dictionary for any lists whose keys end in "!" or "/".
2546
+ # These are lists that will be treated as exclude lists and regular
2547
+ # expression-based exclude/include lists. Collect the lists that are
2548
+ # needed first, looking for the lists that they operate on, and assemble
2549
+ # then into |lists|. This is done in a separate loop up front, because
2550
+ # the _included and _excluded keys need to be added to the_dict, and that
2551
+ # can't be done while iterating through it.
2552
+
2553
+ lists = []
2554
+ del_lists = []
2555
+ for key, value in the_dict.items():
2556
+ operation = key[-1]
2557
+ if operation != "!" and operation != "/":
2558
+ continue
2559
+
2560
+ if type(value) is not list:
2561
+ raise ValueError(
2562
+ name + " key " + key + " must be list, not " + value.__class__.__name__
2563
+ )
2564
+
2565
+ list_key = key[:-1]
2566
+ if list_key not in the_dict:
2567
+ # This happens when there's a list like "sources!" but no corresponding
2568
+ # "sources" list. Since there's nothing for it to operate on, queue up
2569
+ # the "sources!" list for deletion now.
2570
+ del_lists.append(key)
2571
+ continue
2572
+
2573
+ if type(the_dict[list_key]) is not list:
2574
+ value = the_dict[list_key]
2575
+ raise ValueError(
2576
+ name
2577
+ + " key "
2578
+ + list_key
2579
+ + " must be list, not "
2580
+ + value.__class__.__name__
2581
+ + " when applying "
2582
+ + {"!": "exclusion", "/": "regex"}[operation]
2583
+ )
2584
+
2585
+ if list_key not in lists:
2586
+ lists.append(list_key)
2587
+
2588
+ # Delete the lists that are known to be unneeded at this point.
2589
+ for del_list in del_lists:
2590
+ del the_dict[del_list]
2591
+
2592
+ for list_key in lists:
2593
+ the_list = the_dict[list_key]
2594
+
2595
+ # Initialize the list_actions list, which is parallel to the_list. Each
2596
+ # item in list_actions identifies whether the corresponding item in
2597
+ # the_list should be excluded, unconditionally preserved (included), or
2598
+ # whether no exclusion or inclusion has been applied. Items for which
2599
+ # no exclusion or inclusion has been applied (yet) have value -1, items
2600
+ # excluded have value 0, and items included have value 1. Includes and
2601
+ # excludes override previous actions. All items in list_actions are
2602
+ # initialized to -1 because no excludes or includes have been processed
2603
+ # yet.
2604
+ list_actions = list((-1,) * len(the_list))
2605
+
2606
+ exclude_key = list_key + "!"
2607
+ if exclude_key in the_dict:
2608
+ for exclude_item in the_dict[exclude_key]:
2609
+ for index, list_item in enumerate(the_list):
2610
+ if exclude_item == list_item:
2611
+ # This item matches the exclude_item, so set its action to 0
2612
+ # (exclude).
2613
+ list_actions[index] = 0
2614
+
2615
+ # The "whatever!" list is no longer needed, dump it.
2616
+ del the_dict[exclude_key]
2617
+
2618
+ regex_key = list_key + "/"
2619
+ if regex_key in the_dict:
2620
+ for regex_item in the_dict[regex_key]:
2621
+ [action, pattern] = regex_item
2622
+ pattern_re = re.compile(pattern)
2623
+
2624
+ if action == "exclude":
2625
+ # This item matches an exclude regex, set its value to 0 (exclude).
2626
+ action_value = 0
2627
+ elif action == "include":
2628
+ # This item matches an include regex, set its value to 1 (include).
2629
+ action_value = 1
2630
+ else:
2631
+ # This is an action that doesn't make any sense.
2632
+ raise ValueError(
2633
+ "Unrecognized action "
2634
+ + action
2635
+ + " in "
2636
+ + name
2637
+ + " key "
2638
+ + regex_key
2639
+ )
2640
+
2641
+ for index, list_item in enumerate(the_list):
2642
+ if list_actions[index] == action_value:
2643
+ # Even if the regex matches, nothing will change so continue
2644
+ # (regex searches are expensive).
2645
+ continue
2646
+ if pattern_re.search(list_item):
2647
+ # Regular expression match.
2648
+ list_actions[index] = action_value
2649
+
2650
+ # The "whatever/" list is no longer needed, dump it.
2651
+ del the_dict[regex_key]
2652
+
2653
+ # Add excluded items to the excluded list.
2654
+ #
2655
+ # Note that exclude_key ("sources!") is different from excluded_key
2656
+ # ("sources_excluded"). The exclude_key list is input and it was already
2657
+ # processed and deleted; the excluded_key list is output and it's about
2658
+ # to be created.
2659
+ excluded_key = list_key + "_excluded"
2660
+ if excluded_key in the_dict:
2661
+ raise GypError(
2662
+ name + " key " + excluded_key + " must not be present prior "
2663
+ " to applying exclusion/regex filters for " + list_key
2664
+ )
2665
+
2666
+ excluded_list = []
2667
+
2668
+ # Go backwards through the list_actions list so that as items are deleted,
2669
+ # the indices of items that haven't been seen yet don't shift. That means
2670
+ # that things need to be prepended to excluded_list to maintain them in the
2671
+ # same order that they existed in the_list.
2672
+ for index in range(len(list_actions) - 1, -1, -1):
2673
+ if list_actions[index] == 0:
2674
+ # Dump anything with action 0 (exclude). Keep anything with action 1
2675
+ # (include) or -1 (no include or exclude seen for the item).
2676
+ excluded_list.insert(0, the_list[index])
2677
+ del the_list[index]
2678
+
2679
+ # If anything was excluded, put the excluded list into the_dict at
2680
+ # excluded_key.
2681
+ if len(excluded_list) > 0:
2682
+ the_dict[excluded_key] = excluded_list
2683
+
2684
+ # Now recurse into subdicts and lists that may contain dicts.
2685
+ for key, value in the_dict.items():
2686
+ if type(value) is dict:
2687
+ ProcessListFiltersInDict(key, value)
2688
+ elif type(value) is list:
2689
+ ProcessListFiltersInList(key, value)
2690
+
2691
+
2692
+ def ProcessListFiltersInList(name, the_list):
2693
+ for item in the_list:
2694
+ if type(item) is dict:
2695
+ ProcessListFiltersInDict(name, item)
2696
+ elif type(item) is list:
2697
+ ProcessListFiltersInList(name, item)
2698
+
2699
+
2700
+ def ValidateTargetType(target, target_dict):
2701
+ """Ensures the 'type' field on the target is one of the known types.
2702
+
2703
+ Arguments:
2704
+ target: string, name of target.
2705
+ target_dict: dict, target spec.
2706
+
2707
+ Raises an exception on error.
2708
+ """
2709
+ VALID_TARGET_TYPES = (
2710
+ "executable",
2711
+ "loadable_module",
2712
+ "static_library",
2713
+ "shared_library",
2714
+ "mac_kernel_extension",
2715
+ "none",
2716
+ "windows_driver",
2717
+ )
2718
+ target_type = target_dict.get("type", None)
2719
+ if target_type not in VALID_TARGET_TYPES:
2720
+ raise GypError(
2721
+ "Target %s has an invalid target type '%s'. "
2722
+ "Must be one of %s." % (target, target_type, "/".join(VALID_TARGET_TYPES))
2723
+ )
2724
+ if (
2725
+ target_dict.get("standalone_static_library", 0)
2726
+ and not target_type == "static_library"
2727
+ ):
2728
+ raise GypError(
2729
+ "Target %s has type %s but standalone_static_library flag is"
2730
+ " only valid for static_library type." % (target, target_type)
2731
+ )
2732
+
2733
+
2734
+ def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules):
2735
+ """Ensures that the rules sections in target_dict are valid and consistent,
2736
+ and determines which sources they apply to.
2737
+
2738
+ Arguments:
2739
+ target: string, name of target.
2740
+ target_dict: dict, target spec containing "rules" and "sources" lists.
2741
+ extra_sources_for_rules: a list of keys to scan for rule matches in
2742
+ addition to 'sources'.
2743
+ """
2744
+
2745
+ # Dicts to map between values found in rules' 'rule_name' and 'extension'
2746
+ # keys and the rule dicts themselves.
2747
+ rule_names = {}
2748
+ rule_extensions = {}
2749
+
2750
+ rules = target_dict.get("rules", [])
2751
+ for rule in rules:
2752
+ # Make sure that there's no conflict among rule names and extensions.
2753
+ rule_name = rule["rule_name"]
2754
+ if rule_name in rule_names:
2755
+ raise GypError(
2756
+ f"rule {rule_name} exists in duplicate, target {target}"
2757
+ )
2758
+ rule_names[rule_name] = rule
2759
+
2760
+ rule_extension = rule["extension"]
2761
+ if rule_extension.startswith("."):
2762
+ rule_extension = rule_extension[1:]
2763
+ if rule_extension in rule_extensions:
2764
+ raise GypError(
2765
+ (
2766
+ "extension %s associated with multiple rules, "
2767
+ + "target %s rules %s and %s"
2768
+ )
2769
+ % (
2770
+ rule_extension,
2771
+ target,
2772
+ rule_extensions[rule_extension]["rule_name"],
2773
+ rule_name,
2774
+ )
2775
+ )
2776
+ rule_extensions[rule_extension] = rule
2777
+
2778
+ # Make sure rule_sources isn't already there. It's going to be
2779
+ # created below if needed.
2780
+ if "rule_sources" in rule:
2781
+ raise GypError(
2782
+ "rule_sources must not exist in input, target %s rule %s"
2783
+ % (target, rule_name)
2784
+ )
2785
+
2786
+ rule_sources = []
2787
+ source_keys = ["sources"]
2788
+ source_keys.extend(extra_sources_for_rules)
2789
+ for source_key in source_keys:
2790
+ for source in target_dict.get(source_key, []):
2791
+ (source_root, source_extension) = os.path.splitext(source)
2792
+ if source_extension.startswith("."):
2793
+ source_extension = source_extension[1:]
2794
+ if source_extension == rule_extension:
2795
+ rule_sources.append(source)
2796
+
2797
+ if len(rule_sources) > 0:
2798
+ rule["rule_sources"] = rule_sources
2799
+
2800
+
2801
+ def ValidateRunAsInTarget(target, target_dict, build_file):
2802
+ target_name = target_dict.get("target_name")
2803
+ run_as = target_dict.get("run_as")
2804
+ if not run_as:
2805
+ return
2806
+ if type(run_as) is not dict:
2807
+ raise GypError(
2808
+ "The 'run_as' in target %s from file %s should be a "
2809
+ "dictionary." % (target_name, build_file)
2810
+ )
2811
+ action = run_as.get("action")
2812
+ if not action:
2813
+ raise GypError(
2814
+ "The 'run_as' in target %s from file %s must have an "
2815
+ "'action' section." % (target_name, build_file)
2816
+ )
2817
+ if type(action) is not list:
2818
+ raise GypError(
2819
+ "The 'action' for 'run_as' in target %s from file %s "
2820
+ "must be a list." % (target_name, build_file)
2821
+ )
2822
+ working_directory = run_as.get("working_directory")
2823
+ if working_directory and type(working_directory) is not str:
2824
+ raise GypError(
2825
+ "The 'working_directory' for 'run_as' in target %s "
2826
+ "in file %s should be a string." % (target_name, build_file)
2827
+ )
2828
+ environment = run_as.get("environment")
2829
+ if environment and type(environment) is not dict:
2830
+ raise GypError(
2831
+ "The 'environment' for 'run_as' in target %s "
2832
+ "in file %s should be a dictionary." % (target_name, build_file)
2833
+ )
2834
+
2835
+
2836
+ def ValidateActionsInTarget(target, target_dict, build_file):
2837
+ """Validates the inputs to the actions in a target."""
2838
+ target_name = target_dict.get("target_name")
2839
+ actions = target_dict.get("actions", [])
2840
+ for action in actions:
2841
+ action_name = action.get("action_name")
2842
+ if not action_name:
2843
+ raise GypError(
2844
+ "Anonymous action in target %s. "
2845
+ "An action must have an 'action_name' field." % target_name
2846
+ )
2847
+ inputs = action.get("inputs", None)
2848
+ if inputs is None:
2849
+ raise GypError("Action in target %s has no inputs." % target_name)
2850
+ action_command = action.get("action")
2851
+ if action_command and not action_command[0]:
2852
+ raise GypError("Empty action as command in target %s." % target_name)
2853
+
2854
+
2855
+ def TurnIntIntoStrInDict(the_dict):
2856
+ """Given dict the_dict, recursively converts all integers into strings.
2857
+ """
2858
+ # Use items instead of iteritems because there's no need to try to look at
2859
+ # reinserted keys and their associated values.
2860
+ for k, v in the_dict.items():
2861
+ if type(v) is int:
2862
+ v = str(v)
2863
+ the_dict[k] = v
2864
+ elif type(v) is dict:
2865
+ TurnIntIntoStrInDict(v)
2866
+ elif type(v) is list:
2867
+ TurnIntIntoStrInList(v)
2868
+
2869
+ if type(k) is int:
2870
+ del the_dict[k]
2871
+ the_dict[str(k)] = v
2872
+
2873
+
2874
+ def TurnIntIntoStrInList(the_list):
2875
+ """Given list the_list, recursively converts all integers into strings.
2876
+ """
2877
+ for index, item in enumerate(the_list):
2878
+ if type(item) is int:
2879
+ the_list[index] = str(item)
2880
+ elif type(item) is dict:
2881
+ TurnIntIntoStrInDict(item)
2882
+ elif type(item) is list:
2883
+ TurnIntIntoStrInList(item)
2884
+
2885
+
2886
+ def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, data):
2887
+ """Return only the targets that are deep dependencies of |root_targets|."""
2888
+ qualified_root_targets = []
2889
+ for target in root_targets:
2890
+ target = target.strip()
2891
+ qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list)
2892
+ if not qualified_targets:
2893
+ raise GypError("Could not find target %s" % target)
2894
+ qualified_root_targets.extend(qualified_targets)
2895
+
2896
+ wanted_targets = {}
2897
+ for target in qualified_root_targets:
2898
+ wanted_targets[target] = targets[target]
2899
+ for dependency in dependency_nodes[target].DeepDependencies():
2900
+ wanted_targets[dependency] = targets[dependency]
2901
+
2902
+ wanted_flat_list = [t for t in flat_list if t in wanted_targets]
2903
+
2904
+ # Prune unwanted targets from each build_file's data dict.
2905
+ for build_file in data["target_build_files"]:
2906
+ if "targets" not in data[build_file]:
2907
+ continue
2908
+ new_targets = []
2909
+ for target in data[build_file]["targets"]:
2910
+ qualified_name = gyp.common.QualifiedTarget(
2911
+ build_file, target["target_name"], target["toolset"]
2912
+ )
2913
+ if qualified_name in wanted_targets:
2914
+ new_targets.append(target)
2915
+ data[build_file]["targets"] = new_targets
2916
+
2917
+ return wanted_targets, wanted_flat_list
2918
+
2919
+
2920
+ def VerifyNoCollidingTargets(targets):
2921
+ """Verify that no two targets in the same directory share the same name.
2922
+
2923
+ Arguments:
2924
+ targets: A list of targets in the form 'path/to/file.gyp:target_name'.
2925
+ """
2926
+ # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'.
2927
+ used = {}
2928
+ for target in targets:
2929
+ # Separate out 'path/to/file.gyp, 'target_name' from
2930
+ # 'path/to/file.gyp:target_name'.
2931
+ path, name = target.rsplit(":", 1)
2932
+ # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'.
2933
+ subdir, gyp = os.path.split(path)
2934
+ # Use '.' for the current directory '', so that the error messages make
2935
+ # more sense.
2936
+ if not subdir:
2937
+ subdir = "."
2938
+ # Prepare a key like 'path/to:target_name'.
2939
+ key = subdir + ":" + name
2940
+ if key in used:
2941
+ # Complain if this target is already used.
2942
+ raise GypError(
2943
+ 'Duplicate target name "%s" in directory "%s" used both '
2944
+ 'in "%s" and "%s".' % (name, subdir, gyp, used[key])
2945
+ )
2946
+ used[key] = gyp
2947
+
2948
+
2949
+ def SetGeneratorGlobals(generator_input_info):
2950
+ # Set up path_sections and non_configuration_keys with the default data plus
2951
+ # the generator-specific data.
2952
+ global path_sections
2953
+ path_sections = set(base_path_sections)
2954
+ path_sections.update(generator_input_info["path_sections"])
2955
+
2956
+ global non_configuration_keys
2957
+ non_configuration_keys = base_non_configuration_keys[:]
2958
+ non_configuration_keys.extend(generator_input_info["non_configuration_keys"])
2959
+
2960
+ global multiple_toolsets
2961
+ multiple_toolsets = generator_input_info["generator_supports_multiple_toolsets"]
2962
+
2963
+ global generator_filelist_paths
2964
+ generator_filelist_paths = generator_input_info["generator_filelist_paths"]
2965
+
2966
+
2967
+ def Load(
2968
+ build_files,
2969
+ variables,
2970
+ includes,
2971
+ depth,
2972
+ generator_input_info,
2973
+ check,
2974
+ circular_check,
2975
+ parallel,
2976
+ root_targets,
2977
+ ):
2978
+ SetGeneratorGlobals(generator_input_info)
2979
+ # A generator can have other lists (in addition to sources) be processed
2980
+ # for rules.
2981
+ extra_sources_for_rules = generator_input_info["extra_sources_for_rules"]
2982
+
2983
+ # Load build files. This loads every target-containing build file into
2984
+ # the |data| dictionary such that the keys to |data| are build file names,
2985
+ # and the values are the entire build file contents after "early" or "pre"
2986
+ # processing has been done and includes have been resolved.
2987
+ # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as
2988
+ # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps
2989
+ # track of the keys corresponding to "target" files.
2990
+ data = {"target_build_files": set()}
2991
+ # Normalize paths everywhere. This is important because paths will be
2992
+ # used as keys to the data dict and for references between input files.
2993
+ build_files = set(map(os.path.normpath, build_files))
2994
+ if parallel:
2995
+ LoadTargetBuildFilesParallel(
2996
+ build_files, data, variables, includes, depth, check, generator_input_info
2997
+ )
2998
+ else:
2999
+ aux_data = {}
3000
+ for build_file in build_files:
3001
+ try:
3002
+ LoadTargetBuildFile(
3003
+ build_file, data, aux_data, variables, includes, depth, check, True
3004
+ )
3005
+ except Exception as e:
3006
+ gyp.common.ExceptionAppend(e, "while trying to load %s" % build_file)
3007
+ raise
3008
+
3009
+ # Build a dict to access each target's subdict by qualified name.
3010
+ targets = BuildTargetsDict(data)
3011
+
3012
+ # Fully qualify all dependency links.
3013
+ QualifyDependencies(targets)
3014
+
3015
+ # Remove self-dependencies from targets that have 'prune_self_dependencies'
3016
+ # set to 1.
3017
+ RemoveSelfDependencies(targets)
3018
+
3019
+ # Expand dependencies specified as build_file:*.
3020
+ ExpandWildcardDependencies(targets, data)
3021
+
3022
+ # Remove all dependencies marked as 'link_dependency' from the targets of
3023
+ # type 'none'.
3024
+ RemoveLinkDependenciesFromNoneTargets(targets)
3025
+
3026
+ # Apply exclude (!) and regex (/) list filters only for dependency_sections.
3027
+ for target_name, target_dict in targets.items():
3028
+ tmp_dict = {}
3029
+ for key_base in dependency_sections:
3030
+ for op in ("", "!", "/"):
3031
+ key = key_base + op
3032
+ if key in target_dict:
3033
+ tmp_dict[key] = target_dict[key]
3034
+ del target_dict[key]
3035
+ ProcessListFiltersInDict(target_name, tmp_dict)
3036
+ # Write the results back to |target_dict|.
3037
+ for key in tmp_dict:
3038
+ target_dict[key] = tmp_dict[key]
3039
+
3040
+ # Make sure every dependency appears at most once.
3041
+ RemoveDuplicateDependencies(targets)
3042
+
3043
+ if circular_check:
3044
+ # Make sure that any targets in a.gyp don't contain dependencies in other
3045
+ # .gyp files that further depend on a.gyp.
3046
+ VerifyNoGYPFileCircularDependencies(targets)
3047
+
3048
+ [dependency_nodes, flat_list] = BuildDependencyList(targets)
3049
+
3050
+ if root_targets:
3051
+ # Remove, from |targets| and |flat_list|, the targets that are not deep
3052
+ # dependencies of the targets specified in |root_targets|.
3053
+ targets, flat_list = PruneUnwantedTargets(
3054
+ targets, flat_list, dependency_nodes, root_targets, data
3055
+ )
3056
+
3057
+ # Check that no two targets in the same directory have the same name.
3058
+ VerifyNoCollidingTargets(flat_list)
3059
+
3060
+ # Handle dependent settings of various types.
3061
+ for settings_type in [
3062
+ "all_dependent_settings",
3063
+ "direct_dependent_settings",
3064
+ "link_settings",
3065
+ ]:
3066
+ DoDependentSettings(settings_type, flat_list, targets, dependency_nodes)
3067
+
3068
+ # Take out the dependent settings now that they've been published to all
3069
+ # of the targets that require them.
3070
+ for target in flat_list:
3071
+ if settings_type in targets[target]:
3072
+ del targets[target][settings_type]
3073
+
3074
+ # Make sure static libraries don't declare dependencies on other static
3075
+ # libraries, but that linkables depend on all unlinked static libraries
3076
+ # that they need so that their link steps will be correct.
3077
+ gii = generator_input_info
3078
+ if gii["generator_wants_static_library_dependencies_adjusted"]:
3079
+ AdjustStaticLibraryDependencies(
3080
+ flat_list,
3081
+ targets,
3082
+ dependency_nodes,
3083
+ gii["generator_wants_sorted_dependencies"],
3084
+ )
3085
+
3086
+ # Apply "post"/"late"/"target" 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_LATE, variables, build_file
3092
+ )
3093
+
3094
+ # Move everything that can go into a "configurations" section into one.
3095
+ for target in flat_list:
3096
+ target_dict = targets[target]
3097
+ SetUpConfigurations(target, target_dict)
3098
+
3099
+ # Apply exclude (!) and regex (/) list filters.
3100
+ for target in flat_list:
3101
+ target_dict = targets[target]
3102
+ ProcessListFiltersInDict(target, target_dict)
3103
+
3104
+ # Apply "latelate" variable expansions and condition evaluations.
3105
+ for target in flat_list:
3106
+ target_dict = targets[target]
3107
+ build_file = gyp.common.BuildFile(target)
3108
+ ProcessVariablesAndConditionsInDict(
3109
+ target_dict, PHASE_LATELATE, variables, build_file
3110
+ )
3111
+
3112
+ # Make sure that the rules make sense, and build up rule_sources lists as
3113
+ # needed. Not all generators will need to use the rule_sources lists, but
3114
+ # some may, and it seems best to build the list in a common spot.
3115
+ # Also validate actions and run_as elements in targets.
3116
+ for target in flat_list:
3117
+ target_dict = targets[target]
3118
+ build_file = gyp.common.BuildFile(target)
3119
+ ValidateTargetType(target, target_dict)
3120
+ ValidateRulesInTarget(target, target_dict, extra_sources_for_rules)
3121
+ ValidateRunAsInTarget(target, target_dict, build_file)
3122
+ ValidateActionsInTarget(target, target_dict, build_file)
3123
+
3124
+ # Generators might not expect ints. Turn them into strs.
3125
+ TurnIntIntoStrInDict(data)
3126
+
3127
+ # TODO(mark): Return |data| for now because the generator needs a list of
3128
+ # build files that came in. In the future, maybe it should just accept
3129
+ # a list, and not the whole data dict.
3130
+ return [flat_list, targets, data]