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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. async_casbin_adapter/__init__.py +0 -0
  2. async_casbin_adapter/adapter.py +100 -0
  3. async_casbin_adapter/apps.py +24 -0
  4. async_casbin_adapter/enforcer.py +81 -0
  5. async_casbin_adapter/migrations/0001_initial.py +37 -0
  6. async_casbin_adapter/migrations/__init__.py +0 -0
  7. async_casbin_adapter/models.py +48 -0
  8. async_casbin_adapter/utils.py +25 -0
  9. casbin_async_django_orm_adapter-1.0.0.dist-info/METADATA +116 -0
  10. casbin_async_django_orm_adapter-1.0.0.dist-info/RECORD +74 -0
  11. casbin_async_django_orm_adapter-1.0.0.dist-info/WHEEL +5 -0
  12. casbin_async_django_orm_adapter-1.0.0.dist-info/licenses/LICENSE +201 -0
  13. casbin_async_django_orm_adapter-1.0.0.dist-info/top_level.txt +3 -0
  14. node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  15. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +365 -0
  16. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  17. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1272 -0
  18. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  19. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  20. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +152 -0
  21. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +270 -0
  22. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  23. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +704 -0
  24. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/common.py +709 -0
  25. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +173 -0
  26. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +169 -0
  27. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +113 -0
  28. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  29. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  30. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +805 -0
  31. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1172 -0
  32. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1319 -0
  33. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +128 -0
  34. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +104 -0
  35. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +462 -0
  36. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  37. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +56 -0
  38. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2745 -0
  39. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3976 -0
  40. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  41. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2965 -0
  42. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +67 -0
  43. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1391 -0
  44. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +26 -0
  45. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py +3112 -0
  46. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +99 -0
  47. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +767 -0
  48. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1260 -0
  49. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  50. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  51. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +373 -0
  52. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1939 -0
  53. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation_test.py +54 -0
  54. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +303 -0
  55. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3196 -0
  56. node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  57. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/__init__.py +15 -0
  58. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_elffile.py +108 -0
  59. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_manylinux.py +252 -0
  60. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_musllinux.py +83 -0
  61. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_parser.py +359 -0
  62. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_structures.py +61 -0
  63. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/_tokenizer.py +192 -0
  64. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/markers.py +252 -0
  65. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/metadata.py +825 -0
  66. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/py.typed +0 -0
  67. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/requirements.py +90 -0
  68. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/specifiers.py +1030 -0
  69. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/tags.py +553 -0
  70. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/utils.py +172 -0
  71. node_modules/npm/node_modules/node-gyp/gyp/pylib/packaging/version.py +563 -0
  72. node_modules/npm/node_modules/node-gyp/gyp/test_gyp.py +261 -0
  73. node_modules/semantic-release-pypi/dist/py/set_version.py +32 -0
  74. node_modules/semantic-release-pypi/dist/py/verify_setup.py +24 -0
@@ -0,0 +1,2745 @@
1
+ # Copyright (c) 2013 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
+ # Notes:
6
+ #
7
+ # This is all roughly based on the Makefile system used by the Linux
8
+ # kernel, but is a non-recursive make -- we put the entire dependency
9
+ # graph in front of make and let it figure it out.
10
+ #
11
+ # The code below generates a separate .mk file for each target, but
12
+ # all are sourced by the top-level Makefile. This means that all
13
+ # variables in .mk-files clobber one another. Be careful to use :=
14
+ # where appropriate for immediate evaluation, and similarly to watch
15
+ # that you're not relying on a variable value to last between different
16
+ # .mk files.
17
+ #
18
+ # TODOs:
19
+ #
20
+ # Global settings and utility functions are currently stuffed in the
21
+ # toplevel Makefile. It may make sense to generate some .mk files on
22
+ # the side to keep the files readable.
23
+
24
+
25
+ import hashlib
26
+ import os
27
+ import re
28
+ import subprocess
29
+ import sys
30
+
31
+ import gyp
32
+ import gyp.common
33
+ import gyp.xcode_emulation
34
+ from gyp.common import GetEnvironFallback
35
+
36
+ generator_default_variables = {
37
+ "EXECUTABLE_PREFIX": "",
38
+ "EXECUTABLE_SUFFIX": "",
39
+ "STATIC_LIB_PREFIX": "lib",
40
+ "SHARED_LIB_PREFIX": "lib",
41
+ "STATIC_LIB_SUFFIX": ".a",
42
+ "INTERMEDIATE_DIR": "$(obj).$(TOOLSET)/$(TARGET)/geni",
43
+ "SHARED_INTERMEDIATE_DIR": "$(obj)/gen",
44
+ "PRODUCT_DIR": "$(builddir)",
45
+ "RULE_INPUT_ROOT": "%(INPUT_ROOT)s", # This gets expanded by Python.
46
+ "RULE_INPUT_DIRNAME": "%(INPUT_DIRNAME)s", # This gets expanded by Python.
47
+ "RULE_INPUT_PATH": "$(abspath $<)",
48
+ "RULE_INPUT_EXT": "$(suffix $<)",
49
+ "RULE_INPUT_NAME": "$(notdir $<)",
50
+ "CONFIGURATION_NAME": "$(BUILDTYPE)",
51
+ }
52
+
53
+ # Make supports multiple toolsets
54
+ generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested()
55
+
56
+ # Request sorted dependencies in the order from dependents to dependencies.
57
+ generator_wants_sorted_dependencies = False
58
+
59
+ # Placates pylint.
60
+ generator_additional_non_configuration_keys = []
61
+ generator_additional_path_sections = []
62
+ generator_extra_sources_for_rules = []
63
+ generator_filelist_paths = None
64
+
65
+
66
+ def CalculateVariables(default_variables, params):
67
+ """Calculate additional variables for use in the build (called by gyp)."""
68
+ flavor = gyp.common.GetFlavor(params)
69
+ if flavor == "mac":
70
+ default_variables.setdefault("OS", "mac")
71
+ default_variables.setdefault("SHARED_LIB_SUFFIX", ".dylib")
72
+ default_variables.setdefault(
73
+ "SHARED_LIB_DIR", generator_default_variables["PRODUCT_DIR"]
74
+ )
75
+ default_variables.setdefault(
76
+ "LIB_DIR", generator_default_variables["PRODUCT_DIR"]
77
+ )
78
+
79
+ # Copy additional generator configuration data from Xcode, which is shared
80
+ # by the Mac Make generator.
81
+ import gyp.generator.xcode as xcode_generator
82
+
83
+ global generator_additional_non_configuration_keys
84
+ generator_additional_non_configuration_keys = getattr(
85
+ xcode_generator, "generator_additional_non_configuration_keys", []
86
+ )
87
+ global generator_additional_path_sections
88
+ generator_additional_path_sections = getattr(
89
+ xcode_generator, "generator_additional_path_sections", []
90
+ )
91
+ global generator_extra_sources_for_rules
92
+ generator_extra_sources_for_rules = getattr(
93
+ xcode_generator, "generator_extra_sources_for_rules", []
94
+ )
95
+ COMPILABLE_EXTENSIONS.update({".m": "objc", ".mm": "objcxx"})
96
+ else:
97
+ operating_system = flavor
98
+ if flavor == "android":
99
+ operating_system = "linux" # Keep this legacy behavior for now.
100
+ default_variables.setdefault("OS", operating_system)
101
+ if flavor == "aix":
102
+ default_variables.setdefault("SHARED_LIB_SUFFIX", ".a")
103
+ elif flavor == "zos":
104
+ default_variables.setdefault("SHARED_LIB_SUFFIX", ".x")
105
+ COMPILABLE_EXTENSIONS.update({".pli": "pli"})
106
+ else:
107
+ default_variables.setdefault("SHARED_LIB_SUFFIX", ".so")
108
+ default_variables.setdefault("SHARED_LIB_DIR", "$(builddir)/lib.$(TOOLSET)")
109
+ default_variables.setdefault("LIB_DIR", "$(obj).$(TOOLSET)")
110
+
111
+
112
+ def CalculateGeneratorInputInfo(params):
113
+ """Calculate the generator specific info that gets fed to input (called by
114
+ gyp)."""
115
+ generator_flags = params.get("generator_flags", {})
116
+ android_ndk_version = generator_flags.get("android_ndk_version", None)
117
+ # Android NDK requires a strict link order.
118
+ if android_ndk_version:
119
+ global generator_wants_sorted_dependencies
120
+ generator_wants_sorted_dependencies = True
121
+
122
+ output_dir = params["options"].generator_output or params["options"].toplevel_dir
123
+ builddir_name = generator_flags.get("output_dir", "out")
124
+ qualified_out_dir = os.path.normpath(
125
+ os.path.join(output_dir, builddir_name, "gypfiles")
126
+ )
127
+
128
+ global generator_filelist_paths
129
+ generator_filelist_paths = {
130
+ "toplevel": params["options"].toplevel_dir,
131
+ "qualified_out_dir": qualified_out_dir,
132
+ }
133
+
134
+
135
+ # The .d checking code below uses these functions:
136
+ # wildcard, sort, foreach, shell, wordlist
137
+ # wildcard can handle spaces, the rest can't.
138
+ # Since I could find no way to make foreach work with spaces in filenames
139
+ # correctly, the .d files have spaces replaced with another character. The .d
140
+ # file for
141
+ # Chromium\ Framework.framework/foo
142
+ # is for example
143
+ # out/Release/.deps/out/Release/Chromium?Framework.framework/foo
144
+ # This is the replacement character.
145
+ SPACE_REPLACEMENT = "?"
146
+
147
+
148
+ LINK_COMMANDS_LINUX = """\
149
+ quiet_cmd_alink = AR($(TOOLSET)) $@
150
+ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
151
+
152
+ quiet_cmd_alink_thin = AR($(TOOLSET)) $@
153
+ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
154
+
155
+ # Due to circular dependencies between libraries :(, we wrap the
156
+ # special "figure out circular dependencies" flags around the entire
157
+ # input list during linking.
158
+ quiet_cmd_link = LINK($(TOOLSET)) $@
159
+ cmd_link = $(LINK.$(TOOLSET)) -o $@ $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,--start-group $(LD_INPUTS) $(LIBS) -Wl,--end-group
160
+
161
+ # Note: this does not handle spaces in paths
162
+ define xargs
163
+ $(1) $(word 1,$(2))
164
+ $(if $(word 2,$(2)),$(call xargs,$(1),$(wordlist 2,$(words $(2)),$(2))))
165
+ endef
166
+
167
+ define write-to-file
168
+ @: >$(1)
169
+ $(call xargs,@printf "%s\\n" >>$(1),$(2))
170
+ endef
171
+
172
+ OBJ_FILE_LIST := ar-file-list
173
+
174
+ define create_archive
175
+ rm -f $(1) $(1).$(OBJ_FILE_LIST); mkdir -p `dirname $(1)`
176
+ $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2)))
177
+ $(AR.$(TOOLSET)) crs $(1) @$(1).$(OBJ_FILE_LIST)
178
+ endef
179
+
180
+ define create_thin_archive
181
+ rm -f $(1) $(OBJ_FILE_LIST); mkdir -p `dirname $(1)`
182
+ $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2)))
183
+ $(AR.$(TOOLSET)) crsT $(1) @$(1).$(OBJ_FILE_LIST)
184
+ endef
185
+
186
+ # We support two kinds of shared objects (.so):
187
+ # 1) shared_library, which is just bundling together many dependent libraries
188
+ # into a link line.
189
+ # 2) loadable_module, which is generating a module intended for dlopen().
190
+ #
191
+ # They differ only slightly:
192
+ # In the former case, we want to package all dependent code into the .so.
193
+ # In the latter case, we want to package just the API exposed by the
194
+ # outermost module.
195
+ # This means shared_library uses --whole-archive, while loadable_module doesn't.
196
+ # (Note that --whole-archive is incompatible with the --start-group used in
197
+ # normal linking.)
198
+
199
+ # Other shared-object link notes:
200
+ # - Set SONAME to the library filename so our binaries don't reference
201
+ # the local, absolute paths used on the link command-line.
202
+ quiet_cmd_solink = SOLINK($(TOOLSET)) $@
203
+ cmd_solink = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
204
+
205
+ quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
206
+ cmd_solink_module = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
207
+ """ # noqa: E501
208
+
209
+ LINK_COMMANDS_MAC = """\
210
+ quiet_cmd_alink = LIBTOOL-STATIC $@
211
+ cmd_alink = rm -f $@ && %(python)s gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %%.o,$^)
212
+
213
+ quiet_cmd_link = LINK($(TOOLSET)) $@
214
+ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
215
+
216
+ quiet_cmd_solink = SOLINK($(TOOLSET)) $@
217
+ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
218
+
219
+ quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
220
+ cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
221
+ """ % {'python': sys.executable} # noqa: E501
222
+
223
+ LINK_COMMANDS_ANDROID = """\
224
+ quiet_cmd_alink = AR($(TOOLSET)) $@
225
+ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
226
+
227
+ quiet_cmd_alink_thin = AR($(TOOLSET)) $@
228
+ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
229
+
230
+ # Note: this does not handle spaces in paths
231
+ define xargs
232
+ $(1) $(word 1,$(2))
233
+ $(if $(word 2,$(2)),$(call xargs,$(1),$(wordlist 2,$(words $(2)),$(2))))
234
+ endef
235
+
236
+ define write-to-file
237
+ @: >$(1)
238
+ $(call xargs,@printf "%s\\n" >>$(1),$(2))
239
+ endef
240
+
241
+ OBJ_FILE_LIST := ar-file-list
242
+
243
+ define create_archive
244
+ rm -f $(1) $(1).$(OBJ_FILE_LIST); mkdir -p `dirname $(1)`
245
+ $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2)))
246
+ $(AR.$(TOOLSET)) crs $(1) @$(1).$(OBJ_FILE_LIST)
247
+ endef
248
+
249
+ define create_thin_archive
250
+ rm -f $(1) $(OBJ_FILE_LIST); mkdir -p `dirname $(1)`
251
+ $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2)))
252
+ $(AR.$(TOOLSET)) crsT $(1) @$(1).$(OBJ_FILE_LIST)
253
+ endef
254
+
255
+ # Due to circular dependencies between libraries :(, we wrap the
256
+ # special "figure out circular dependencies" flags around the entire
257
+ # input list during linking.
258
+ quiet_cmd_link = LINK($(TOOLSET)) $@
259
+ quiet_cmd_link_host = LINK($(TOOLSET)) $@
260
+ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
261
+ cmd_link_host = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
262
+
263
+ # Other shared-object link notes:
264
+ # - Set SONAME to the library filename so our binaries don't reference
265
+ # the local, absolute paths used on the link command-line.
266
+ quiet_cmd_solink = SOLINK($(TOOLSET)) $@
267
+ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
268
+
269
+ quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
270
+ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
271
+ quiet_cmd_solink_module_host = SOLINK_MODULE($(TOOLSET)) $@
272
+ cmd_solink_module_host = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
273
+ """ # noqa: E501
274
+
275
+
276
+ LINK_COMMANDS_AIX = """\
277
+ quiet_cmd_alink = AR($(TOOLSET)) $@
278
+ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^)
279
+
280
+ quiet_cmd_alink_thin = AR($(TOOLSET)) $@
281
+ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^)
282
+
283
+ quiet_cmd_link = LINK($(TOOLSET)) $@
284
+ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
285
+
286
+ quiet_cmd_solink = SOLINK($(TOOLSET)) $@
287
+ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
288
+
289
+ quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
290
+ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
291
+ """ # noqa: E501
292
+
293
+
294
+ LINK_COMMANDS_OS400 = """\
295
+ quiet_cmd_alink = AR($(TOOLSET)) $@
296
+ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) -X64 crs $@ $(filter %.o,$^)
297
+
298
+ quiet_cmd_alink_thin = AR($(TOOLSET)) $@
299
+ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) -X64 crs $@ $(filter %.o,$^)
300
+
301
+ quiet_cmd_link = LINK($(TOOLSET)) $@
302
+ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
303
+
304
+ quiet_cmd_solink = SOLINK($(TOOLSET)) $@
305
+ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
306
+
307
+ quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
308
+ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
309
+ """ # noqa: E501
310
+
311
+
312
+ LINK_COMMANDS_OS390 = """\
313
+ quiet_cmd_alink = AR($(TOOLSET)) $@
314
+ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
315
+
316
+ quiet_cmd_alink_thin = AR($(TOOLSET)) $@
317
+ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
318
+
319
+ quiet_cmd_link = LINK($(TOOLSET)) $@
320
+ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
321
+
322
+ quiet_cmd_solink = SOLINK($(TOOLSET)) $@
323
+ cmd_solink = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
324
+
325
+ quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
326
+ cmd_solink_module = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
327
+ """ # noqa: E501
328
+
329
+
330
+ # Header of toplevel Makefile.
331
+ # This should go into the build tree, but it's easier to keep it here for now.
332
+ SHARED_HEADER = (
333
+ """\
334
+ # We borrow heavily from the kernel build setup, though we are simpler since
335
+ # we don't have Kconfig tweaking settings on us.
336
+
337
+ # The implicit make rules have it looking for RCS files, among other things.
338
+ # We instead explicitly write all the rules we care about.
339
+ # It's even quicker (saves ~200ms) to pass -r on the command line.
340
+ MAKEFLAGS=-r
341
+
342
+ # The source directory tree.
343
+ srcdir := %(srcdir)s
344
+ abs_srcdir := $(abspath $(srcdir))
345
+
346
+ # The name of the builddir.
347
+ builddir_name ?= %(builddir)s
348
+
349
+ # The V=1 flag on command line makes us verbosely print command lines.
350
+ ifdef V
351
+ quiet=
352
+ else
353
+ quiet=quiet_
354
+ endif
355
+
356
+ # Specify BUILDTYPE=Release on the command line for a release build.
357
+ BUILDTYPE ?= %(default_configuration)s
358
+
359
+ # Directory all our build output goes into.
360
+ # Note that this must be two directories beneath src/ for unit tests to pass,
361
+ # as they reach into the src/ directory for data with relative paths.
362
+ builddir ?= $(builddir_name)/$(BUILDTYPE)
363
+ abs_builddir := $(abspath $(builddir))
364
+ depsdir := $(builddir)/.deps
365
+
366
+ # Object output directory.
367
+ obj := $(builddir)/obj
368
+ abs_obj := $(abspath $(obj))
369
+
370
+ # We build up a list of every single one of the targets so we can slurp in the
371
+ # generated dependency rule Makefiles in one pass.
372
+ all_deps :=
373
+
374
+ %(make_global_settings)s
375
+
376
+ CC.target ?= %(CC.target)s
377
+ CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS)
378
+ CXX.target ?= %(CXX.target)s
379
+ CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS)
380
+ LINK.target ?= %(LINK.target)s
381
+ LDFLAGS.target ?= $(LDFLAGS)
382
+ AR.target ?= %(AR.target)s
383
+ PLI.target ?= %(PLI.target)s
384
+
385
+ # C++ apps need to be linked with g++.
386
+ LINK ?= $(CXX.target)
387
+
388
+ # TODO(evan): move all cross-compilation logic to gyp-time so we don't need
389
+ # to replicate this environment fallback in make as well.
390
+ CC.host ?= %(CC.host)s
391
+ CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host)
392
+ CXX.host ?= %(CXX.host)s
393
+ CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host)
394
+ LINK.host ?= %(LINK.host)s
395
+ LDFLAGS.host ?= $(LDFLAGS_host)
396
+ AR.host ?= %(AR.host)s
397
+ PLI.host ?= %(PLI.host)s
398
+
399
+ # Define a dir function that can handle spaces.
400
+ # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
401
+ # "leading spaces cannot appear in the text of the first argument as written.
402
+ # These characters can be put into the argument value by variable substitution."
403
+ empty :=
404
+ space := $(empty) $(empty)
405
+
406
+ # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
407
+ replace_spaces = $(subst $(space),"""
408
+ + SPACE_REPLACEMENT
409
+ + """,$1)
410
+ unreplace_spaces = $(subst """
411
+ + SPACE_REPLACEMENT
412
+ + """,$(space),$1)
413
+ dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
414
+
415
+ # Flags to make gcc output dependency info. Note that you need to be
416
+ # careful here to use the flags that ccache and distcc can understand.
417
+ # We write to a dep file on the side first and then rename at the end
418
+ # so we can't end up with a broken dep file.
419
+ depfile = $(depsdir)/$(call replace_spaces,$@).d
420
+ DEPFLAGS = %(makedep_args)s -MF $(depfile).raw
421
+
422
+ # We have to fixup the deps output in a few ways.
423
+ # (1) the file output should mention the proper .o file.
424
+ # ccache or distcc lose the path to the target, so we convert a rule of
425
+ # the form:
426
+ # foobar.o: DEP1 DEP2
427
+ # into
428
+ # path/to/foobar.o: DEP1 DEP2
429
+ # (2) we want missing files not to cause us to fail to build.
430
+ # We want to rewrite
431
+ # foobar.o: DEP1 DEP2 \\
432
+ # DEP3
433
+ # to
434
+ # DEP1:
435
+ # DEP2:
436
+ # DEP3:
437
+ # so if the files are missing, they're just considered phony rules.
438
+ # We have to do some pretty insane escaping to get those backslashes
439
+ # and dollar signs past make, the shell, and sed at the same time.
440
+ # Doesn't work with spaces, but that's fine: .d files have spaces in
441
+ # their names replaced with other characters."""
442
+ r"""
443
+ define fixup_dep
444
+ # The depfile may not exist if the input file didn't have any #includes.
445
+ touch $(depfile).raw
446
+ # Fixup path as in (1).""" +
447
+ (r"""
448
+ sed -e "s|^$(notdir $@)|$@|" -re 's/\\\\([^$$])/\/\1/g' $(depfile).raw >> $(depfile)"""
449
+ if sys.platform == 'win32' else r"""
450
+ sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)""") +
451
+ r"""
452
+ # Add extra rules as in (2).
453
+ # We remove slashes and replace spaces with new lines;
454
+ # remove blank lines;
455
+ # delete the first line and append a colon to the remaining lines.""" +
456
+ ("""
457
+ sed -e 's/\\\\\\\\$$//' -e 's/\\\\\\\\/\\//g' -e 'y| |\\n|' $(depfile).raw |\\"""
458
+ if sys.platform == 'win32' else """
459
+ sed -e 's|\\\\||' -e 'y| |\\n|' $(depfile).raw |\\""") +
460
+ r"""
461
+ grep -v '^$$' |\
462
+ sed -e 1d -e 's|$$|:|' \
463
+ >> $(depfile)
464
+ rm $(depfile).raw
465
+ endef
466
+ """
467
+ """
468
+ # Command definitions:
469
+ # - cmd_foo is the actual command to run;
470
+ # - quiet_cmd_foo is the brief-output summary of the command.
471
+
472
+ quiet_cmd_cc = CC($(TOOLSET)) $@
473
+ cmd_cc = $(CC.$(TOOLSET)) -o $@ $< $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c
474
+
475
+ quiet_cmd_cxx = CXX($(TOOLSET)) $@
476
+ cmd_cxx = $(CXX.$(TOOLSET)) -o $@ $< $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c
477
+ %(extra_commands)s
478
+ quiet_cmd_touch = TOUCH $@
479
+ cmd_touch = touch $@
480
+
481
+ quiet_cmd_copy = COPY $@
482
+ # send stderr to /dev/null to ignore messages when linking directories.
483
+ cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp %(copy_archive_args)s "$<" "$@")
484
+
485
+ quiet_cmd_symlink = SYMLINK $@
486
+ cmd_symlink = ln -sf "$<" "$@"
487
+
488
+ %(link_commands)s
489
+ """ # noqa: E501
490
+ r"""
491
+ # Define an escape_quotes function to escape single quotes.
492
+ # This allows us to handle quotes properly as long as we always use
493
+ # use single quotes and escape_quotes.
494
+ escape_quotes = $(subst ','\'',$(1))
495
+ # This comment is here just to include a ' to unconfuse syntax highlighting.
496
+ # Define an escape_vars function to escape '$' variable syntax.
497
+ # This allows us to read/write command lines with shell variables (e.g.
498
+ # $LD_LIBRARY_PATH), without triggering make substitution.
499
+ escape_vars = $(subst $$,$$$$,$(1))
500
+ # Helper that expands to a shell command to echo a string exactly as it is in
501
+ # make. This uses printf instead of echo because printf's behaviour with respect
502
+ # to escape sequences is more portable than echo's across different shells
503
+ # (e.g., dash, bash).
504
+ exact_echo = printf '%%s\n' '$(call escape_quotes,$(1))'
505
+ """
506
+ """
507
+ # Helper to compare the command we're about to run against the command
508
+ # we logged the last time we ran the command. Produces an empty
509
+ # string (false) when the commands match.
510
+ # Tricky point: Make has no string-equality test function.
511
+ # The kernel uses the following, but it seems like it would have false
512
+ # positives, where one string reordered its arguments.
513
+ # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \\
514
+ # $(filter-out $(cmd_$@), $(cmd_$(1))))
515
+ # We instead substitute each for the empty string into the other, and
516
+ # say they're equal if both substitutions produce the empty string.
517
+ # .d files contain """
518
+ + SPACE_REPLACEMENT
519
+ + """ instead of spaces, take that into account.
520
+ command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\\
521
+ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
522
+
523
+ # Helper that is non-empty when a prerequisite changes.
524
+ # Normally make does this implicitly, but we force rules to always run
525
+ # so we can check their command lines.
526
+ # $? -- new prerequisites
527
+ # $| -- order-only dependencies
528
+ prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
529
+
530
+ # Helper that executes all postbuilds until one fails.
531
+ define do_postbuilds
532
+ @E=0;\\
533
+ for p in $(POSTBUILDS); do\\
534
+ eval $$p;\\
535
+ E=$$?;\\
536
+ if [ $$E -ne 0 ]; then\\
537
+ break;\\
538
+ fi;\\
539
+ done;\\
540
+ if [ $$E -ne 0 ]; then\\
541
+ rm -rf "$@";\\
542
+ exit $$E;\\
543
+ fi
544
+ endef
545
+
546
+ # do_cmd: run a command via the above cmd_foo names, if necessary.
547
+ # Should always run for a given target to handle command-line changes.
548
+ # Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
549
+ # Third argument, if non-zero, makes it do POSTBUILDS processing.
550
+ # Note: We intentionally do NOT call dirx for depfile, since it contains """
551
+ + SPACE_REPLACEMENT
552
+ + """ for
553
+ # spaces already and dirx strips the """
554
+ + SPACE_REPLACEMENT
555
+ + """ characters.
556
+ define do_cmd
557
+ $(if $(or $(command_changed),$(prereq_changed)),
558
+ @$(call exact_echo, $($(quiet)cmd_$(1)))
559
+ @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
560
+ $(if $(findstring flock,$(word %(flock_index)d,$(cmd_$1))),
561
+ @$(cmd_$(1))
562
+ @echo " $(quiet_cmd_$(1)): Finished",
563
+ @$(cmd_$(1))
564
+ )
565
+ @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
566
+ @$(if $(2),$(fixup_dep))
567
+ $(if $(and $(3), $(POSTBUILDS)),
568
+ $(call do_postbuilds)
569
+ )
570
+ )
571
+ endef
572
+
573
+ # Declare the "%(default_target)s" target first so it is the default,
574
+ # even though we don't have the deps yet.
575
+ .PHONY: %(default_target)s
576
+ %(default_target)s:
577
+
578
+ # make looks for ways to re-generate included makefiles, but in our case, we
579
+ # don't have a direct way. Explicitly telling make that it has nothing to do
580
+ # for them makes it go faster.
581
+ %%.d: ;
582
+
583
+ # Use FORCE_DO_CMD to force a target to run. Should be coupled with
584
+ # do_cmd.
585
+ .PHONY: FORCE_DO_CMD
586
+ FORCE_DO_CMD:
587
+
588
+ """ # noqa: E501
589
+ )
590
+
591
+ SHARED_HEADER_MAC_COMMANDS = """
592
+ quiet_cmd_objc = CXX($(TOOLSET)) $@
593
+ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
594
+
595
+ quiet_cmd_objcxx = CXX($(TOOLSET)) $@
596
+ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
597
+
598
+ # Commands for precompiled header files.
599
+ quiet_cmd_pch_c = CXX($(TOOLSET)) $@
600
+ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
601
+ quiet_cmd_pch_cc = CXX($(TOOLSET)) $@
602
+ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
603
+ quiet_cmd_pch_m = CXX($(TOOLSET)) $@
604
+ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
605
+ quiet_cmd_pch_mm = CXX($(TOOLSET)) $@
606
+ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
607
+
608
+ # gyp-mac-tool is written next to the root Makefile by gyp.
609
+ # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
610
+ # already.
611
+ quiet_cmd_mac_tool = MACTOOL $(4) $<
612
+ cmd_mac_tool = %(python)s gyp-mac-tool $(4) $< "$@"
613
+
614
+ quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
615
+ cmd_mac_package_framework = %(python)s gyp-mac-tool package-framework "$@" $(4)
616
+
617
+ quiet_cmd_infoplist = INFOPLIST $@
618
+ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
619
+ """ % {'python': sys.executable} # noqa: E501
620
+
621
+
622
+ def WriteRootHeaderSuffixRules(writer):
623
+ extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower)
624
+
625
+ writer.write("# Suffix rules, putting all outputs into $(obj).\n")
626
+ for ext in extensions:
627
+ writer.write("$(obj).$(TOOLSET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD\n" % ext)
628
+ writer.write("\t@$(call do_cmd,%s,1)\n" % COMPILABLE_EXTENSIONS[ext])
629
+
630
+ writer.write("\n# Try building from generated source, too.\n")
631
+ for ext in extensions:
632
+ writer.write(
633
+ "$(obj).$(TOOLSET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD\n" % ext
634
+ )
635
+ writer.write("\t@$(call do_cmd,%s,1)\n" % COMPILABLE_EXTENSIONS[ext])
636
+ writer.write("\n")
637
+ for ext in extensions:
638
+ writer.write("$(obj).$(TOOLSET)/%%.o: $(obj)/%%%s FORCE_DO_CMD\n" % ext)
639
+ writer.write("\t@$(call do_cmd,%s,1)\n" % COMPILABLE_EXTENSIONS[ext])
640
+ writer.write("\n")
641
+
642
+
643
+ SHARED_HEADER_OS390_COMMANDS = """
644
+ PLIFLAGS.target ?= -qlp=64 -qlimits=extname=31 $(PLIFLAGS)
645
+ PLIFLAGS.host ?= -qlp=64 -qlimits=extname=31 $(PLIFLAGS)
646
+
647
+ quiet_cmd_pli = PLI($(TOOLSET)) $@
648
+ cmd_pli = $(PLI.$(TOOLSET)) $(GYP_PLIFLAGS) $(PLIFLAGS.$(TOOLSET)) -c $< && \
649
+ if [ -f $(notdir $@) ]; then /bin/cp $(notdir $@) $@; else true; fi
650
+ """
651
+
652
+ SHARED_HEADER_SUFFIX_RULES_COMMENT1 = """\
653
+ # Suffix rules, putting all outputs into $(obj).
654
+ """
655
+
656
+
657
+ SHARED_HEADER_SUFFIX_RULES_COMMENT2 = """\
658
+ # Try building from generated source, too.
659
+ """
660
+
661
+
662
+ SHARED_FOOTER = """\
663
+ # "all" is a concatenation of the "all" targets from all the included
664
+ # sub-makefiles. This is just here to clarify.
665
+ all:
666
+
667
+ # Add in dependency-tracking rules. $(all_deps) is the list of every single
668
+ # target in our tree. Only consider the ones with .d (dependency) info:
669
+ d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
670
+ ifneq ($(d_files),)
671
+ include $(d_files)
672
+ endif
673
+ """
674
+
675
+ header = """\
676
+ # This file is generated by gyp; do not edit.
677
+
678
+ """
679
+
680
+ # Maps every compilable file extension to the do_cmd that compiles it.
681
+ COMPILABLE_EXTENSIONS = {
682
+ ".c": "cc",
683
+ ".cc": "cxx",
684
+ ".cpp": "cxx",
685
+ ".cxx": "cxx",
686
+ ".s": "cc",
687
+ ".S": "cc",
688
+ }
689
+
690
+
691
+ def Compilable(filename):
692
+ """Return true if the file is compilable (should be in OBJS)."""
693
+ return any(res for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS))
694
+
695
+
696
+ def Linkable(filename):
697
+ """Return true if the file is linkable (should be on the link line)."""
698
+ return filename.endswith(".o")
699
+
700
+
701
+ def Target(filename):
702
+ """Translate a compilable filename to its .o target."""
703
+ return os.path.splitext(filename)[0] + ".o"
704
+
705
+
706
+ def EscapeShellArgument(s):
707
+ """Quotes an argument so that it will be interpreted literally by a POSIX
708
+ shell. Taken from
709
+ http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
710
+ """
711
+ return "'" + s.replace("'", "'\\''") + "'"
712
+
713
+
714
+ def EscapeMakeVariableExpansion(s):
715
+ """Make has its own variable expansion syntax using $. We must escape it for
716
+ string to be interpreted literally."""
717
+ return s.replace("$", "$$")
718
+
719
+
720
+ def EscapeCppDefine(s):
721
+ """Escapes a CPP define so that it will reach the compiler unaltered."""
722
+ s = EscapeShellArgument(s)
723
+ s = EscapeMakeVariableExpansion(s)
724
+ # '#' characters must be escaped even embedded in a string, else Make will
725
+ # treat it as the start of a comment.
726
+ return s.replace("#", r"\#")
727
+
728
+
729
+ def QuoteIfNecessary(string):
730
+ """TODO: Should this ideally be replaced with one or more of the above
731
+ functions?"""
732
+ if '"' in string:
733
+ string = '"' + string.replace('"', '\\"') + '"'
734
+ return string
735
+
736
+ def replace_sep(string):
737
+ if sys.platform == 'win32':
738
+ string = string.replace('\\\\', '/').replace('\\', '/')
739
+ return string
740
+
741
+ def StringToMakefileVariable(string):
742
+ """Convert a string to a value that is acceptable as a make variable name."""
743
+ return re.sub("[^a-zA-Z0-9_]", "_", string)
744
+
745
+
746
+ srcdir_prefix = ""
747
+
748
+
749
+ def Sourceify(path):
750
+ """Convert a path to its source directory form."""
751
+ if "$(" in path:
752
+ return path
753
+ if os.path.isabs(path):
754
+ return path
755
+ return srcdir_prefix + path
756
+
757
+
758
+ def QuoteSpaces(s, quote=r"\ "):
759
+ return s.replace(" ", quote)
760
+
761
+
762
+ def SourceifyAndQuoteSpaces(path):
763
+ """Convert a path to its source directory form and quote spaces."""
764
+ return QuoteSpaces(Sourceify(path))
765
+
766
+
767
+ # Map from qualified target to path to output.
768
+ target_outputs = {}
769
+ # Map from qualified target to any linkable output. A subset
770
+ # of target_outputs. E.g. when mybinary depends on liba, we want to
771
+ # include liba in the linker line; when otherbinary depends on
772
+ # mybinary, we just want to build mybinary first.
773
+ target_link_deps = {}
774
+
775
+
776
+ class MakefileWriter:
777
+ """MakefileWriter packages up the writing of one target-specific foobar.mk.
778
+
779
+ Its only real entry point is Write(), and is mostly used for namespacing.
780
+ """
781
+
782
+ def __init__(self, generator_flags, flavor):
783
+ self.generator_flags = generator_flags
784
+ self.flavor = flavor
785
+
786
+ self.suffix_rules_srcdir = {}
787
+ self.suffix_rules_objdir1 = {}
788
+ self.suffix_rules_objdir2 = {}
789
+
790
+ # Generate suffix rules for all compilable extensions.
791
+ for ext, value in COMPILABLE_EXTENSIONS.items():
792
+ # Suffix rules for source folder.
793
+ self.suffix_rules_srcdir.update(
794
+ {
795
+ ext: (
796
+ """\
797
+ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD
798
+ \t@$(call do_cmd,%s,1)
799
+ """
800
+ % (ext, value)
801
+ )
802
+ }
803
+ )
804
+
805
+ # Suffix rules for generated source files.
806
+ self.suffix_rules_objdir1.update(
807
+ {
808
+ ext: (
809
+ """\
810
+ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD
811
+ \t@$(call do_cmd,%s,1)
812
+ """
813
+ % (ext, value)
814
+ )
815
+ }
816
+ )
817
+ self.suffix_rules_objdir2.update(
818
+ {
819
+ ext: (
820
+ """\
821
+ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD
822
+ \t@$(call do_cmd,%s,1)
823
+ """
824
+ % (ext, value)
825
+ )
826
+ }
827
+ )
828
+
829
+ def Write(
830
+ self, qualified_target, base_path, output_filename, spec, configs, part_of_all
831
+ ):
832
+ """The main entry point: writes a .mk file for a single target.
833
+
834
+ Arguments:
835
+ qualified_target: target we're generating
836
+ base_path: path relative to source root we're building in, used to resolve
837
+ target-relative paths
838
+ output_filename: output .mk file name to write
839
+ spec, configs: gyp info
840
+ part_of_all: flag indicating this target is part of 'all'
841
+ """
842
+ gyp.common.EnsureDirExists(output_filename)
843
+
844
+ self.fp = open(output_filename, "w")
845
+
846
+ self.fp.write(header)
847
+
848
+ self.qualified_target = qualified_target
849
+ self.path = base_path
850
+ self.target = spec["target_name"]
851
+ self.type = spec["type"]
852
+ self.toolset = spec["toolset"]
853
+
854
+ self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec)
855
+ if self.flavor == "mac":
856
+ self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec)
857
+ else:
858
+ self.xcode_settings = None
859
+
860
+ deps, link_deps = self.ComputeDeps(spec)
861
+
862
+ # Some of the generation below can add extra output, sources, or
863
+ # link dependencies. All of the out params of the functions that
864
+ # follow use names like extra_foo.
865
+ extra_outputs = []
866
+ extra_sources = []
867
+ extra_link_deps = []
868
+ extra_mac_bundle_resources = []
869
+ mac_bundle_deps = []
870
+
871
+ if self.is_mac_bundle:
872
+ self.output = self.ComputeMacBundleOutput(spec)
873
+ self.output_binary = self.ComputeMacBundleBinaryOutput(spec)
874
+ else:
875
+ self.output = self.output_binary = replace_sep(self.ComputeOutput(spec))
876
+
877
+ self.is_standalone_static_library = bool(
878
+ spec.get("standalone_static_library", 0)
879
+ )
880
+ self._INSTALLABLE_TARGETS = ("executable", "loadable_module", "shared_library")
881
+ if self.is_standalone_static_library or self.type in self._INSTALLABLE_TARGETS:
882
+ self.alias = os.path.basename(self.output)
883
+ install_path = self._InstallableTargetInstallPath()
884
+ else:
885
+ self.alias = self.output
886
+ install_path = self.output
887
+
888
+ self.WriteLn("TOOLSET := " + self.toolset)
889
+ self.WriteLn("TARGET := " + self.target)
890
+
891
+ # Actions must come first, since they can generate more OBJs for use below.
892
+ if "actions" in spec:
893
+ self.WriteActions(
894
+ spec["actions"],
895
+ extra_sources,
896
+ extra_outputs,
897
+ extra_mac_bundle_resources,
898
+ part_of_all,
899
+ )
900
+
901
+ # Rules must be early like actions.
902
+ if "rules" in spec:
903
+ self.WriteRules(
904
+ spec["rules"],
905
+ extra_sources,
906
+ extra_outputs,
907
+ extra_mac_bundle_resources,
908
+ part_of_all,
909
+ )
910
+
911
+ if "copies" in spec:
912
+ self.WriteCopies(spec["copies"], extra_outputs, part_of_all)
913
+
914
+ # Bundle resources.
915
+ if self.is_mac_bundle:
916
+ all_mac_bundle_resources = (
917
+ spec.get("mac_bundle_resources", []) + extra_mac_bundle_resources
918
+ )
919
+ self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps)
920
+ self.WriteMacInfoPlist(mac_bundle_deps)
921
+
922
+ # Sources.
923
+ all_sources = spec.get("sources", []) + extra_sources
924
+ if all_sources:
925
+ self.WriteSources(
926
+ configs,
927
+ deps,
928
+ all_sources,
929
+ extra_outputs,
930
+ extra_link_deps,
931
+ part_of_all,
932
+ gyp.xcode_emulation.MacPrefixHeader(
933
+ self.xcode_settings,
934
+ lambda p: Sourceify(self.Absolutify(p)),
935
+ self.Pchify,
936
+ ),
937
+ )
938
+ sources = [x for x in all_sources if Compilable(x)]
939
+ if sources:
940
+ self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1)
941
+ extensions = {os.path.splitext(s)[1] for s in sources}
942
+ for ext in extensions:
943
+ if ext in self.suffix_rules_srcdir:
944
+ self.WriteLn(self.suffix_rules_srcdir[ext])
945
+ self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2)
946
+ for ext in extensions:
947
+ if ext in self.suffix_rules_objdir1:
948
+ self.WriteLn(self.suffix_rules_objdir1[ext])
949
+ for ext in extensions:
950
+ if ext in self.suffix_rules_objdir2:
951
+ self.WriteLn(self.suffix_rules_objdir2[ext])
952
+ self.WriteLn("# End of this set of suffix rules")
953
+
954
+ # Add dependency from bundle to bundle binary.
955
+ if self.is_mac_bundle:
956
+ mac_bundle_deps.append(self.output_binary)
957
+
958
+ self.WriteTarget(
959
+ spec,
960
+ configs,
961
+ deps,
962
+ extra_link_deps + link_deps,
963
+ mac_bundle_deps,
964
+ extra_outputs,
965
+ part_of_all,
966
+ )
967
+
968
+ # Update global list of target outputs, used in dependency tracking.
969
+ target_outputs[qualified_target] = install_path
970
+
971
+ # Update global list of link dependencies.
972
+ if self.type in ("static_library", "shared_library"):
973
+ target_link_deps[qualified_target] = self.output_binary
974
+
975
+ # Currently any versions have the same effect, but in future the behavior
976
+ # could be different.
977
+ if self.generator_flags.get("android_ndk_version", None):
978
+ self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps)
979
+
980
+ self.fp.close()
981
+
982
+ def WriteSubMake(self, output_filename, makefile_path, targets, build_dir):
983
+ """Write a "sub-project" Makefile.
984
+
985
+ This is a small, wrapper Makefile that calls the top-level Makefile to build
986
+ the targets from a single gyp file (i.e. a sub-project).
987
+
988
+ Arguments:
989
+ output_filename: sub-project Makefile name to write
990
+ makefile_path: path to the top-level Makefile
991
+ targets: list of "all" targets for this sub-project
992
+ build_dir: build output directory, relative to the sub-project
993
+ """
994
+ gyp.common.EnsureDirExists(output_filename)
995
+ self.fp = open(output_filename, "w")
996
+ self.fp.write(header)
997
+ # For consistency with other builders, put sub-project build output in the
998
+ # sub-project dir (see test/subdirectory/gyptest-subdir-all.py).
999
+ self.WriteLn(
1000
+ "export builddir_name ?= %s"
1001
+ % replace_sep(os.path.join(os.path.dirname(output_filename), build_dir))
1002
+ )
1003
+ self.WriteLn(".PHONY: all")
1004
+ self.WriteLn("all:")
1005
+ if makefile_path:
1006
+ makefile_path = " -C " + makefile_path
1007
+ self.WriteLn("\t$(MAKE){} {}".format(makefile_path, " ".join(targets)))
1008
+ self.fp.close()
1009
+
1010
+ def WriteActions(
1011
+ self,
1012
+ actions,
1013
+ extra_sources,
1014
+ extra_outputs,
1015
+ extra_mac_bundle_resources,
1016
+ part_of_all,
1017
+ ):
1018
+ """Write Makefile code for any 'actions' from the gyp input.
1019
+
1020
+ extra_sources: a list that will be filled in with newly generated source
1021
+ files, if any
1022
+ extra_outputs: a list that will be filled in with any outputs of these
1023
+ actions (used to make other pieces dependent on these
1024
+ actions)
1025
+ part_of_all: flag indicating this target is part of 'all'
1026
+ """
1027
+ env = self.GetSortedXcodeEnv()
1028
+ for action in actions:
1029
+ name = StringToMakefileVariable(
1030
+ "{}_{}".format(self.qualified_target, action["action_name"])
1031
+ )
1032
+ self.WriteLn('### Rules for action "%s":' % action["action_name"])
1033
+ inputs = action["inputs"]
1034
+ outputs = action["outputs"]
1035
+
1036
+ # Build up a list of outputs.
1037
+ # Collect the output dirs we'll need.
1038
+ dirs = set()
1039
+ for out in outputs:
1040
+ dir = os.path.split(out)[0]
1041
+ if dir:
1042
+ dirs.add(dir)
1043
+ if int(action.get("process_outputs_as_sources", False)):
1044
+ extra_sources += outputs
1045
+ if int(action.get("process_outputs_as_mac_bundle_resources", False)):
1046
+ extra_mac_bundle_resources += outputs
1047
+
1048
+ # Write the actual command.
1049
+ action_commands = action["action"]
1050
+ if self.flavor == "mac":
1051
+ action_commands = [
1052
+ gyp.xcode_emulation.ExpandEnvVars(command, env)
1053
+ for command in action_commands
1054
+ ]
1055
+ command = gyp.common.EncodePOSIXShellList(action_commands)
1056
+ if "message" in action:
1057
+ self.WriteLn(
1058
+ "quiet_cmd_{} = ACTION {} $@".format(name, action["message"])
1059
+ )
1060
+ else:
1061
+ self.WriteLn(f"quiet_cmd_{name} = ACTION {name} $@")
1062
+ if len(dirs) > 0:
1063
+ command = "mkdir -p %s" % " ".join(dirs) + "; " + command
1064
+
1065
+ cd_action = "cd %s; " % Sourceify(self.path or ".")
1066
+
1067
+ # command and cd_action get written to a toplevel variable called
1068
+ # cmd_foo. Toplevel variables can't handle things that change per
1069
+ # makefile like $(TARGET), so hardcode the target.
1070
+ command = command.replace("$(TARGET)", self.target)
1071
+ cd_action = cd_action.replace("$(TARGET)", self.target)
1072
+
1073
+ # Set LD_LIBRARY_PATH in case the action runs an executable from this
1074
+ # build which links to shared libs from this build.
1075
+ # actions run on the host, so they should in theory only use host
1076
+ # libraries, but until everything is made cross-compile safe, also use
1077
+ # target libraries.
1078
+ # TODO(piman): when everything is cross-compile safe, remove lib.target
1079
+ if self.flavor in {"zos", "aix"}:
1080
+ self.WriteLn(
1081
+ "cmd_%s = LIBPATH=$(builddir)/lib.host:"
1082
+ "$(builddir)/lib.target:$$LIBPATH; "
1083
+ "export LIBPATH; "
1084
+ "%s%s" % (name, cd_action, command)
1085
+ )
1086
+ else:
1087
+ self.WriteLn(
1088
+ "cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:"
1089
+ "$(builddir)/lib.target:$$LD_LIBRARY_PATH; "
1090
+ "export LD_LIBRARY_PATH; "
1091
+ "%s%s" % (name, cd_action, command)
1092
+ )
1093
+ self.WriteLn()
1094
+ outputs = [self.Absolutify(o) for o in outputs]
1095
+ # The makefile rules are all relative to the top dir, but the gyp actions
1096
+ # are defined relative to their containing dir. This replaces the obj
1097
+ # variable for the action rule with an absolute version so that the output
1098
+ # goes in the right place.
1099
+ # Only write the 'obj' and 'builddir' rules for the "primary" output (:1);
1100
+ # it's superfluous for the "extra outputs", and this avoids accidentally
1101
+ # writing duplicate dummy rules for those outputs.
1102
+ # Same for environment.
1103
+ self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0]))
1104
+ self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0]))
1105
+ self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv())
1106
+
1107
+ for input in inputs:
1108
+ assert " " not in input, (
1109
+ "Spaces in action input filenames not supported (%s)" % input
1110
+ )
1111
+ for output in outputs:
1112
+ assert " " not in output, (
1113
+ "Spaces in action output filenames not supported (%s)" % output
1114
+ )
1115
+
1116
+ # See the comment in WriteCopies about expanding env vars.
1117
+ outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs]
1118
+ inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs]
1119
+
1120
+ self.WriteDoCmd(
1121
+ outputs,
1122
+ [Sourceify(self.Absolutify(i)) for i in inputs],
1123
+ part_of_all=part_of_all,
1124
+ command=name,
1125
+ )
1126
+
1127
+ # Stuff the outputs in a variable so we can refer to them later.
1128
+ outputs_variable = "action_%s_outputs" % name
1129
+ self.WriteLn("{} := {}".format(outputs_variable, " ".join(outputs)))
1130
+ extra_outputs.append("$(%s)" % outputs_variable)
1131
+ self.WriteLn()
1132
+
1133
+ self.WriteLn()
1134
+
1135
+ def WriteRules(
1136
+ self,
1137
+ rules,
1138
+ extra_sources,
1139
+ extra_outputs,
1140
+ extra_mac_bundle_resources,
1141
+ part_of_all,
1142
+ ):
1143
+ """Write Makefile code for any 'rules' from the gyp input.
1144
+
1145
+ extra_sources: a list that will be filled in with newly generated source
1146
+ files, if any
1147
+ extra_outputs: a list that will be filled in with any outputs of these
1148
+ rules (used to make other pieces dependent on these rules)
1149
+ part_of_all: flag indicating this target is part of 'all'
1150
+ """
1151
+ env = self.GetSortedXcodeEnv()
1152
+ for rule in rules:
1153
+ name = StringToMakefileVariable(
1154
+ "{}_{}".format(self.qualified_target, rule["rule_name"])
1155
+ )
1156
+ count = 0
1157
+ self.WriteLn("### Generated for rule %s:" % name)
1158
+
1159
+ all_outputs = []
1160
+
1161
+ for rule_source in rule.get("rule_sources", []):
1162
+ dirs = set()
1163
+ (rule_source_dirname, rule_source_basename) = os.path.split(rule_source)
1164
+ (rule_source_root, rule_source_ext) = os.path.splitext(
1165
+ rule_source_basename
1166
+ )
1167
+
1168
+ outputs = [
1169
+ self.ExpandInputRoot(out, rule_source_root, rule_source_dirname)
1170
+ for out in rule["outputs"]
1171
+ ]
1172
+
1173
+ for out in outputs:
1174
+ dir = os.path.dirname(out)
1175
+ if dir:
1176
+ dirs.add(dir)
1177
+ if int(rule.get("process_outputs_as_sources", False)):
1178
+ extra_sources += outputs
1179
+ if int(rule.get("process_outputs_as_mac_bundle_resources", False)):
1180
+ extra_mac_bundle_resources += outputs
1181
+ inputs = [
1182
+ Sourceify(self.Absolutify(i))
1183
+ for i in [rule_source] + rule.get("inputs", [])
1184
+ ]
1185
+ actions = ["$(call do_cmd,%s_%d)" % (name, count)]
1186
+
1187
+ if name == "resources_grit":
1188
+ # HACK: This is ugly. Grit intentionally doesn't touch the
1189
+ # timestamp of its output file when the file doesn't change,
1190
+ # which is fine in hash-based dependency systems like scons
1191
+ # and forge, but not kosher in the make world. After some
1192
+ # discussion, hacking around it here seems like the least
1193
+ # amount of pain.
1194
+ actions += ["@touch --no-create $@"]
1195
+
1196
+ # See the comment in WriteCopies about expanding env vars.
1197
+ outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs]
1198
+ inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs]
1199
+
1200
+ outputs = [self.Absolutify(o) for o in outputs]
1201
+ all_outputs += outputs
1202
+ # Only write the 'obj' and 'builddir' rules for the "primary" output
1203
+ # (:1); it's superfluous for the "extra outputs", and this avoids
1204
+ # accidentally writing duplicate dummy rules for those outputs.
1205
+ self.WriteLn("%s: obj := $(abs_obj)" % outputs[0])
1206
+ self.WriteLn("%s: builddir := $(abs_builddir)" % outputs[0])
1207
+ self.WriteMakeRule(
1208
+ outputs, inputs, actions, command="%s_%d" % (name, count)
1209
+ )
1210
+ # Spaces in rule filenames are not supported, but rule variables have
1211
+ # spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)').
1212
+ # The spaces within the variables are valid, so remove the variables
1213
+ # before checking.
1214
+ variables_with_spaces = re.compile(r"\$\([^ ]* \$<\)")
1215
+ for output in outputs:
1216
+ output = re.sub(variables_with_spaces, "", output)
1217
+ assert " " not in output, (
1218
+ "Spaces in rule filenames not yet supported (%s)" % output
1219
+ )
1220
+ self.WriteLn("all_deps += %s" % " ".join(outputs))
1221
+
1222
+ action = [
1223
+ self.ExpandInputRoot(ac, rule_source_root, rule_source_dirname)
1224
+ for ac in rule["action"]
1225
+ ]
1226
+ mkdirs = ""
1227
+ if len(dirs) > 0:
1228
+ mkdirs = "mkdir -p %s; " % " ".join(dirs)
1229
+ cd_action = "cd %s; " % Sourceify(self.path or ".")
1230
+
1231
+ # action, cd_action, and mkdirs get written to a toplevel variable
1232
+ # called cmd_foo. Toplevel variables can't handle things that change
1233
+ # per makefile like $(TARGET), so hardcode the target.
1234
+ if self.flavor == "mac":
1235
+ action = [
1236
+ gyp.xcode_emulation.ExpandEnvVars(command, env)
1237
+ for command in action
1238
+ ]
1239
+ action = gyp.common.EncodePOSIXShellList(action)
1240
+ action = action.replace("$(TARGET)", self.target)
1241
+ cd_action = cd_action.replace("$(TARGET)", self.target)
1242
+ mkdirs = mkdirs.replace("$(TARGET)", self.target)
1243
+
1244
+ # Set LD_LIBRARY_PATH in case the rule runs an executable from this
1245
+ # build which links to shared libs from this build.
1246
+ # rules run on the host, so they should in theory only use host
1247
+ # libraries, but until everything is made cross-compile safe, also use
1248
+ # target libraries.
1249
+ # TODO(piman): when everything is cross-compile safe, remove lib.target
1250
+ self.WriteLn(
1251
+ "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH="
1252
+ "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; "
1253
+ "export LD_LIBRARY_PATH; "
1254
+ "%(cd_action)s%(mkdirs)s%(action)s"
1255
+ % {
1256
+ "action": action,
1257
+ "cd_action": cd_action,
1258
+ "count": count,
1259
+ "mkdirs": mkdirs,
1260
+ "name": name,
1261
+ }
1262
+ )
1263
+ self.WriteLn(
1264
+ "quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@"
1265
+ % {"count": count, "name": name}
1266
+ )
1267
+ self.WriteLn()
1268
+ count += 1
1269
+
1270
+ outputs_variable = "rule_%s_outputs" % name
1271
+ self.WriteList(all_outputs, outputs_variable)
1272
+ extra_outputs.append("$(%s)" % outputs_variable)
1273
+
1274
+ self.WriteLn("### Finished generating for rule: %s" % name)
1275
+ self.WriteLn()
1276
+ self.WriteLn("### Finished generating for all rules")
1277
+ self.WriteLn("")
1278
+
1279
+ def WriteCopies(self, copies, extra_outputs, part_of_all):
1280
+ """Write Makefile code for any 'copies' from the gyp input.
1281
+
1282
+ extra_outputs: a list that will be filled in with any outputs of this action
1283
+ (used to make other pieces dependent on this action)
1284
+ part_of_all: flag indicating this target is part of 'all'
1285
+ """
1286
+ self.WriteLn("### Generated for copy rule.")
1287
+
1288
+ variable = StringToMakefileVariable(self.qualified_target + "_copies")
1289
+ outputs = []
1290
+ for copy in copies:
1291
+ for path in copy["files"]:
1292
+ # Absolutify() may call normpath, and will strip trailing slashes.
1293
+ path = Sourceify(self.Absolutify(path))
1294
+ filename = os.path.split(path)[1]
1295
+ output = Sourceify(
1296
+ self.Absolutify(os.path.join(copy["destination"], filename))
1297
+ )
1298
+
1299
+ # If the output path has variables in it, which happens in practice for
1300
+ # 'copies', writing the environment as target-local doesn't work,
1301
+ # because the variables are already needed for the target name.
1302
+ # Copying the environment variables into global make variables doesn't
1303
+ # work either, because then the .d files will potentially contain spaces
1304
+ # after variable expansion, and .d file handling cannot handle spaces.
1305
+ # As a workaround, manually expand variables at gyp time. Since 'copies'
1306
+ # can't run scripts, there's no need to write the env then.
1307
+ # WriteDoCmd() will escape spaces for .d files.
1308
+ env = self.GetSortedXcodeEnv()
1309
+ output = gyp.xcode_emulation.ExpandEnvVars(output, env)
1310
+ path = gyp.xcode_emulation.ExpandEnvVars(path, env)
1311
+ self.WriteDoCmd([output], [path], "copy", part_of_all)
1312
+ outputs.append(output)
1313
+ self.WriteLn(
1314
+ "{} = {}".format(variable, " ".join(QuoteSpaces(o) for o in outputs))
1315
+ )
1316
+ extra_outputs.append("$(%s)" % variable)
1317
+ self.WriteLn()
1318
+
1319
+ def WriteMacBundleResources(self, resources, bundle_deps):
1320
+ """Writes Makefile code for 'mac_bundle_resources'."""
1321
+ self.WriteLn("### Generated for mac_bundle_resources")
1322
+
1323
+ for output, res in gyp.xcode_emulation.GetMacBundleResources(
1324
+ generator_default_variables["PRODUCT_DIR"],
1325
+ self.xcode_settings,
1326
+ [Sourceify(self.Absolutify(r)) for r in resources],
1327
+ ):
1328
+ _, ext = os.path.splitext(output)
1329
+ if ext != ".xcassets":
1330
+ # Make does not supports '.xcassets' emulation.
1331
+ self.WriteDoCmd(
1332
+ [output], [res], "mac_tool,,,copy-bundle-resource", part_of_all=True
1333
+ )
1334
+ bundle_deps.append(output)
1335
+
1336
+ def WriteMacInfoPlist(self, bundle_deps):
1337
+ """Write Makefile code for bundle Info.plist files."""
1338
+ info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist(
1339
+ generator_default_variables["PRODUCT_DIR"],
1340
+ self.xcode_settings,
1341
+ lambda p: Sourceify(self.Absolutify(p)),
1342
+ )
1343
+ if not info_plist:
1344
+ return
1345
+ if defines:
1346
+ # Create an intermediate file to store preprocessed results.
1347
+ intermediate_plist = "$(obj).$(TOOLSET)/$(TARGET)/" + os.path.basename(
1348
+ info_plist
1349
+ )
1350
+ self.WriteList(
1351
+ defines,
1352
+ intermediate_plist + ": INFOPLIST_DEFINES",
1353
+ "-D",
1354
+ quoter=EscapeCppDefine,
1355
+ )
1356
+ self.WriteMakeRule(
1357
+ [intermediate_plist],
1358
+ [info_plist],
1359
+ [
1360
+ "$(call do_cmd,infoplist)",
1361
+ # "Convert" the plist so that any weird whitespace changes from the
1362
+ # preprocessor do not affect the XML parser in mac_tool.
1363
+ "@plutil -convert xml1 $@ $@",
1364
+ ],
1365
+ )
1366
+ info_plist = intermediate_plist
1367
+ # plists can contain envvars and substitute them into the file.
1368
+ self.WriteSortedXcodeEnv(
1369
+ out, self.GetSortedXcodeEnv(additional_settings=extra_env)
1370
+ )
1371
+ self.WriteDoCmd(
1372
+ [out], [info_plist], "mac_tool,,,copy-info-plist", part_of_all=True
1373
+ )
1374
+ bundle_deps.append(out)
1375
+
1376
+ def WriteSources(
1377
+ self,
1378
+ configs,
1379
+ deps,
1380
+ sources,
1381
+ extra_outputs,
1382
+ extra_link_deps,
1383
+ part_of_all,
1384
+ precompiled_header,
1385
+ ):
1386
+ """Write Makefile code for any 'sources' from the gyp input.
1387
+ These are source files necessary to build the current target.
1388
+
1389
+ configs, deps, sources: input from gyp.
1390
+ extra_outputs: a list of extra outputs this action should be dependent on;
1391
+ used to serialize action/rules before compilation
1392
+ extra_link_deps: a list that will be filled in with any outputs of
1393
+ compilation (to be used in link lines)
1394
+ part_of_all: flag indicating this target is part of 'all'
1395
+ """
1396
+
1397
+ # Write configuration-specific variables for CFLAGS, etc.
1398
+ for configname in sorted(configs.keys()):
1399
+ config = configs[configname]
1400
+ self.WriteList(
1401
+ config.get("defines"),
1402
+ "DEFS_%s" % configname,
1403
+ prefix="-D",
1404
+ quoter=EscapeCppDefine,
1405
+ )
1406
+
1407
+ if self.flavor == "mac":
1408
+ cflags = self.xcode_settings.GetCflags(
1409
+ configname, arch=config.get("xcode_configuration_platform")
1410
+ )
1411
+ cflags_c = self.xcode_settings.GetCflagsC(configname)
1412
+ cflags_cc = self.xcode_settings.GetCflagsCC(configname)
1413
+ cflags_objc = self.xcode_settings.GetCflagsObjC(configname)
1414
+ cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname)
1415
+ else:
1416
+ cflags = config.get("cflags")
1417
+ cflags_c = config.get("cflags_c")
1418
+ cflags_cc = config.get("cflags_cc")
1419
+
1420
+ self.WriteLn("# Flags passed to all source files.")
1421
+ self.WriteList(cflags, "CFLAGS_%s" % configname)
1422
+ self.WriteLn("# Flags passed to only C files.")
1423
+ self.WriteList(cflags_c, "CFLAGS_C_%s" % configname)
1424
+ self.WriteLn("# Flags passed to only C++ files.")
1425
+ self.WriteList(cflags_cc, "CFLAGS_CC_%s" % configname)
1426
+ if self.flavor == "mac":
1427
+ self.WriteLn("# Flags passed to only ObjC files.")
1428
+ self.WriteList(cflags_objc, "CFLAGS_OBJC_%s" % configname)
1429
+ self.WriteLn("# Flags passed to only ObjC++ files.")
1430
+ self.WriteList(cflags_objcc, "CFLAGS_OBJCC_%s" % configname)
1431
+ includes = config.get("include_dirs")
1432
+ if includes:
1433
+ includes = [Sourceify(self.Absolutify(i)) for i in includes]
1434
+ self.WriteList(includes, "INCS_%s" % configname, prefix="-I")
1435
+
1436
+ compilable = list(filter(Compilable, sources))
1437
+ objs = [self.Objectify(self.Absolutify(Target(c))) for c in compilable]
1438
+ self.WriteList(objs, "OBJS")
1439
+
1440
+ for obj in objs:
1441
+ assert " " not in obj, "Spaces in object filenames not supported (%s)" % obj
1442
+ self.WriteLn(
1443
+ "# Add to the list of files we specially track dependencies for."
1444
+ )
1445
+ self.WriteLn("all_deps += $(OBJS)")
1446
+ self.WriteLn()
1447
+
1448
+ # Make sure our dependencies are built first.
1449
+ if deps:
1450
+ self.WriteMakeRule(
1451
+ ["$(OBJS)"],
1452
+ deps,
1453
+ comment="Make sure our dependencies are built before any of us.",
1454
+ order_only=True,
1455
+ )
1456
+
1457
+ # Make sure the actions and rules run first.
1458
+ # If they generate any extra headers etc., the per-.o file dep tracking
1459
+ # will catch the proper rebuilds, so order only is still ok here.
1460
+ if extra_outputs:
1461
+ self.WriteMakeRule(
1462
+ ["$(OBJS)"],
1463
+ extra_outputs,
1464
+ comment="Make sure our actions/rules run before any of us.",
1465
+ order_only=True,
1466
+ )
1467
+
1468
+ pchdeps = precompiled_header.GetObjDependencies(compilable, objs)
1469
+ if pchdeps:
1470
+ self.WriteLn("# Dependencies from obj files to their precompiled headers")
1471
+ for source, obj, gch in pchdeps:
1472
+ self.WriteLn(f"{obj}: {gch}")
1473
+ self.WriteLn("# End precompiled header dependencies")
1474
+
1475
+ if objs:
1476
+ extra_link_deps.append("$(OBJS)")
1477
+ self.WriteLn(
1478
+ """\
1479
+ # CFLAGS et al overrides must be target-local.
1480
+ # See "Target-specific Variable Values" in the GNU Make manual."""
1481
+ )
1482
+ self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)")
1483
+ self.WriteLn(
1484
+ "$(OBJS): GYP_CFLAGS := "
1485
+ "$(DEFS_$(BUILDTYPE)) "
1486
+ "$(INCS_$(BUILDTYPE)) "
1487
+ "%s " % precompiled_header.GetInclude("c") + "$(CFLAGS_$(BUILDTYPE)) "
1488
+ "$(CFLAGS_C_$(BUILDTYPE))"
1489
+ )
1490
+ self.WriteLn(
1491
+ "$(OBJS): GYP_CXXFLAGS := "
1492
+ "$(DEFS_$(BUILDTYPE)) "
1493
+ "$(INCS_$(BUILDTYPE)) "
1494
+ "%s " % precompiled_header.GetInclude("cc") + "$(CFLAGS_$(BUILDTYPE)) "
1495
+ "$(CFLAGS_CC_$(BUILDTYPE))"
1496
+ )
1497
+ if self.flavor == "mac":
1498
+ self.WriteLn(
1499
+ "$(OBJS): GYP_OBJCFLAGS := "
1500
+ "$(DEFS_$(BUILDTYPE)) "
1501
+ "$(INCS_$(BUILDTYPE)) "
1502
+ "%s " % precompiled_header.GetInclude("m")
1503
+ + "$(CFLAGS_$(BUILDTYPE)) "
1504
+ "$(CFLAGS_C_$(BUILDTYPE)) "
1505
+ "$(CFLAGS_OBJC_$(BUILDTYPE))"
1506
+ )
1507
+ self.WriteLn(
1508
+ "$(OBJS): GYP_OBJCXXFLAGS := "
1509
+ "$(DEFS_$(BUILDTYPE)) "
1510
+ "$(INCS_$(BUILDTYPE)) "
1511
+ "%s " % precompiled_header.GetInclude("mm")
1512
+ + "$(CFLAGS_$(BUILDTYPE)) "
1513
+ "$(CFLAGS_CC_$(BUILDTYPE)) "
1514
+ "$(CFLAGS_OBJCC_$(BUILDTYPE))"
1515
+ )
1516
+
1517
+ self.WritePchTargets(precompiled_header.GetPchBuildCommands())
1518
+
1519
+ # If there are any object files in our input file list, link them into our
1520
+ # output.
1521
+ extra_link_deps += [source for source in sources if Linkable(source)]
1522
+
1523
+ self.WriteLn()
1524
+
1525
+ def WritePchTargets(self, pch_commands):
1526
+ """Writes make rules to compile prefix headers."""
1527
+ if not pch_commands:
1528
+ return
1529
+
1530
+ for gch, lang_flag, lang, input in pch_commands:
1531
+ extra_flags = {
1532
+ "c": "$(CFLAGS_C_$(BUILDTYPE))",
1533
+ "cc": "$(CFLAGS_CC_$(BUILDTYPE))",
1534
+ "m": "$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))",
1535
+ "mm": "$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))",
1536
+ }[lang]
1537
+ var_name = {
1538
+ "c": "GYP_PCH_CFLAGS",
1539
+ "cc": "GYP_PCH_CXXFLAGS",
1540
+ "m": "GYP_PCH_OBJCFLAGS",
1541
+ "mm": "GYP_PCH_OBJCXXFLAGS",
1542
+ }[lang]
1543
+ self.WriteLn(
1544
+ f"{gch}: {var_name} := {lang_flag} " + "$(DEFS_$(BUILDTYPE)) "
1545
+ "$(INCS_$(BUILDTYPE)) "
1546
+ "$(CFLAGS_$(BUILDTYPE)) " + extra_flags
1547
+ )
1548
+
1549
+ self.WriteLn(f"{gch}: {input} FORCE_DO_CMD")
1550
+ self.WriteLn("\t@$(call do_cmd,pch_%s,1)" % lang)
1551
+ self.WriteLn("")
1552
+ assert " " not in gch, "Spaces in gch filenames not supported (%s)" % gch
1553
+ self.WriteLn("all_deps += %s" % gch)
1554
+ self.WriteLn("")
1555
+
1556
+ def ComputeOutputBasename(self, spec):
1557
+ """Return the 'output basename' of a gyp spec.
1558
+
1559
+ E.g., the loadable module 'foobar' in directory 'baz' will produce
1560
+ 'libfoobar.so'
1561
+ """
1562
+ assert not self.is_mac_bundle
1563
+
1564
+ if self.flavor == "mac" and self.type in (
1565
+ "static_library",
1566
+ "executable",
1567
+ "shared_library",
1568
+ "loadable_module",
1569
+ ):
1570
+ return self.xcode_settings.GetExecutablePath()
1571
+
1572
+ target = spec["target_name"]
1573
+ target_prefix = ""
1574
+ target_ext = ""
1575
+ if self.type == "static_library":
1576
+ if target[:3] == "lib":
1577
+ target = target[3:]
1578
+ target_prefix = "lib"
1579
+ target_ext = ".a"
1580
+ elif self.type in ("loadable_module", "shared_library"):
1581
+ if target[:3] == "lib":
1582
+ target = target[3:]
1583
+ target_prefix = "lib"
1584
+ if self.flavor == "aix":
1585
+ target_ext = ".a"
1586
+ elif self.flavor == "zos":
1587
+ target_ext = ".x"
1588
+ else:
1589
+ target_ext = ".so"
1590
+ elif self.type == "none":
1591
+ target = "%s.stamp" % target
1592
+ elif self.type != "executable":
1593
+ print(
1594
+ "ERROR: What output file should be generated?",
1595
+ "type",
1596
+ self.type,
1597
+ "target",
1598
+ target,
1599
+ )
1600
+
1601
+ target_prefix = spec.get("product_prefix", target_prefix)
1602
+ target = spec.get("product_name", target)
1603
+ product_ext = spec.get("product_extension")
1604
+ if product_ext:
1605
+ target_ext = "." + product_ext
1606
+
1607
+ return target_prefix + target + target_ext
1608
+
1609
+ def _InstallImmediately(self):
1610
+ return (
1611
+ self.toolset == "target"
1612
+ and self.flavor == "mac"
1613
+ and self.type
1614
+ in ("static_library", "executable", "shared_library", "loadable_module")
1615
+ )
1616
+
1617
+ def ComputeOutput(self, spec):
1618
+ """Return the 'output' (full output path) of a gyp spec.
1619
+
1620
+ E.g., the loadable module 'foobar' in directory 'baz' will produce
1621
+ '$(obj)/baz/libfoobar.so'
1622
+ """
1623
+ assert not self.is_mac_bundle
1624
+
1625
+ path = os.path.join("$(obj)." + self.toolset, self.path)
1626
+ if self.type == "executable" or self._InstallImmediately():
1627
+ path = "$(builddir)"
1628
+ path = spec.get("product_dir", path)
1629
+ return os.path.join(path, self.ComputeOutputBasename(spec))
1630
+
1631
+ def ComputeMacBundleOutput(self, spec):
1632
+ """Return the 'output' (full output path) to a bundle output directory."""
1633
+ assert self.is_mac_bundle
1634
+ path = generator_default_variables["PRODUCT_DIR"]
1635
+ return os.path.join(path, self.xcode_settings.GetWrapperName())
1636
+
1637
+ def ComputeMacBundleBinaryOutput(self, spec):
1638
+ """Return the 'output' (full output path) to the binary in a bundle."""
1639
+ path = generator_default_variables["PRODUCT_DIR"]
1640
+ return os.path.join(path, self.xcode_settings.GetExecutablePath())
1641
+
1642
+ def ComputeDeps(self, spec):
1643
+ """Compute the dependencies of a gyp spec.
1644
+
1645
+ Returns a tuple (deps, link_deps), where each is a list of
1646
+ filenames that will need to be put in front of make for either
1647
+ building (deps) or linking (link_deps).
1648
+ """
1649
+ deps = []
1650
+ link_deps = []
1651
+ if "dependencies" in spec:
1652
+ deps.extend(
1653
+ [
1654
+ target_outputs[dep]
1655
+ for dep in spec["dependencies"]
1656
+ if target_outputs[dep]
1657
+ ]
1658
+ )
1659
+ for dep in spec["dependencies"]:
1660
+ if dep in target_link_deps:
1661
+ link_deps.append(target_link_deps[dep])
1662
+ deps.extend(link_deps)
1663
+ # TODO: It seems we need to transitively link in libraries (e.g. -lfoo)?
1664
+ # This hack makes it work:
1665
+ # link_deps.extend(spec.get('libraries', []))
1666
+ return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps))
1667
+
1668
+ def GetSharedObjectFromSidedeck(self, sidedeck):
1669
+ """Return the shared object files based on sidedeck"""
1670
+ return re.sub(r"\.x$", ".so", sidedeck)
1671
+
1672
+ def GetUnversionedSidedeckFromSidedeck(self, sidedeck):
1673
+ """Return the shared object files based on sidedeck"""
1674
+ return re.sub(r"\.\d+\.x$", ".x", sidedeck)
1675
+
1676
+ def WriteDependencyOnExtraOutputs(self, target, extra_outputs):
1677
+ self.WriteMakeRule(
1678
+ [self.output_binary],
1679
+ extra_outputs,
1680
+ comment="Build our special outputs first.",
1681
+ order_only=True,
1682
+ )
1683
+
1684
+ def WriteTarget(
1685
+ self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all
1686
+ ):
1687
+ """Write Makefile code to produce the final target of the gyp spec.
1688
+
1689
+ spec, configs: input from gyp.
1690
+ deps, link_deps: dependency lists; see ComputeDeps()
1691
+ extra_outputs: any extra outputs that our target should depend on
1692
+ part_of_all: flag indicating this target is part of 'all'
1693
+ """
1694
+
1695
+ self.WriteLn("### Rules for final target.")
1696
+
1697
+ if extra_outputs:
1698
+ self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs)
1699
+ self.WriteMakeRule(
1700
+ extra_outputs,
1701
+ deps,
1702
+ comment=("Preserve order dependency of special output on deps."),
1703
+ order_only=True,
1704
+ )
1705
+
1706
+ target_postbuilds = {}
1707
+ if self.type != "none":
1708
+ for configname in sorted(configs.keys()):
1709
+ config = configs[configname]
1710
+ if self.flavor == "mac":
1711
+ ldflags = self.xcode_settings.GetLdflags(
1712
+ configname,
1713
+ generator_default_variables["PRODUCT_DIR"],
1714
+ lambda p: Sourceify(self.Absolutify(p)),
1715
+ arch=config.get("xcode_configuration_platform"),
1716
+ )
1717
+
1718
+ # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on.
1719
+ gyp_to_build = gyp.common.InvertRelativePath(self.path)
1720
+ target_postbuild = self.xcode_settings.AddImplicitPostbuilds(
1721
+ configname,
1722
+ QuoteSpaces(
1723
+ os.path.normpath(os.path.join(gyp_to_build, self.output))
1724
+ ),
1725
+ QuoteSpaces(
1726
+ os.path.normpath(
1727
+ os.path.join(gyp_to_build, self.output_binary)
1728
+ )
1729
+ ),
1730
+ )
1731
+ if target_postbuild:
1732
+ target_postbuilds[configname] = target_postbuild
1733
+ else:
1734
+ ldflags = config.get("ldflags", [])
1735
+ # Compute an rpath for this output if needed.
1736
+ if any(dep.endswith(".so") or ".so." in dep for dep in deps):
1737
+ # We want to get the literal string "$ORIGIN"
1738
+ # into the link command, so we need lots of escaping.
1739
+ ldflags.append(r"-Wl,-rpath=\$$ORIGIN/")
1740
+ ldflags.append(r"-Wl,-rpath-link=\$(builddir)/")
1741
+ if library_dirs := config.get("library_dirs", []):
1742
+ library_dirs = [Sourceify(self.Absolutify(i)) for i in library_dirs]
1743
+ ldflags += [("-L%s" % library_dir) for library_dir in library_dirs]
1744
+ self.WriteList(ldflags, "LDFLAGS_%s" % configname)
1745
+ if self.flavor == "mac":
1746
+ self.WriteList(
1747
+ self.xcode_settings.GetLibtoolflags(configname),
1748
+ "LIBTOOLFLAGS_%s" % configname,
1749
+ )
1750
+ libraries = spec.get("libraries")
1751
+ if libraries:
1752
+ # Remove duplicate entries
1753
+ libraries = gyp.common.uniquer(libraries)
1754
+ if self.flavor == "mac":
1755
+ libraries = self.xcode_settings.AdjustLibraries(libraries)
1756
+ self.WriteList(libraries, "LIBS")
1757
+ self.WriteLn(
1758
+ "%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))"
1759
+ % QuoteSpaces(self.output_binary)
1760
+ )
1761
+ self.WriteLn("%s: LIBS := $(LIBS)" % QuoteSpaces(self.output_binary))
1762
+
1763
+ if self.flavor == "mac":
1764
+ self.WriteLn(
1765
+ "%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))"
1766
+ % QuoteSpaces(self.output_binary)
1767
+ )
1768
+
1769
+ # Postbuild actions. Like actions, but implicitly depend on the target's
1770
+ # output.
1771
+ postbuilds = []
1772
+ if self.flavor == "mac":
1773
+ if target_postbuilds:
1774
+ postbuilds.append("$(TARGET_POSTBUILDS_$(BUILDTYPE))")
1775
+ postbuilds.extend(gyp.xcode_emulation.GetSpecPostbuildCommands(spec))
1776
+
1777
+ if postbuilds:
1778
+ # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE),
1779
+ # so we must output its definition first, since we declare variables
1780
+ # using ":=".
1781
+ self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv())
1782
+
1783
+ for configname, value in target_postbuilds.items():
1784
+ self.WriteLn(
1785
+ "%s: TARGET_POSTBUILDS_%s := %s"
1786
+ % (
1787
+ QuoteSpaces(self.output),
1788
+ configname,
1789
+ gyp.common.EncodePOSIXShellList(value),
1790
+ )
1791
+ )
1792
+
1793
+ # Postbuilds expect to be run in the gyp file's directory, so insert an
1794
+ # implicit postbuild to cd to there.
1795
+ postbuilds.insert(0, gyp.common.EncodePOSIXShellList(["cd", self.path]))
1796
+ for i, postbuild in enumerate(postbuilds):
1797
+ if not postbuild.startswith("$"):
1798
+ postbuilds[i] = EscapeShellArgument(postbuild)
1799
+ self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(self.output))
1800
+ self.WriteLn(
1801
+ "%s: POSTBUILDS := %s"
1802
+ % (QuoteSpaces(self.output), " ".join(postbuilds))
1803
+ )
1804
+
1805
+ # A bundle directory depends on its dependencies such as bundle resources
1806
+ # and bundle binary. When all dependencies have been built, the bundle
1807
+ # needs to be packaged.
1808
+ if self.is_mac_bundle:
1809
+ # If the framework doesn't contain a binary, then nothing depends
1810
+ # on the actions -- make the framework depend on them directly too.
1811
+ self.WriteDependencyOnExtraOutputs(self.output, extra_outputs)
1812
+
1813
+ # Bundle dependencies. Note that the code below adds actions to this
1814
+ # target, so if you move these two lines, move the lines below as well.
1815
+ self.WriteList([QuoteSpaces(dep) for dep in bundle_deps], "BUNDLE_DEPS")
1816
+ self.WriteLn("%s: $(BUNDLE_DEPS)" % QuoteSpaces(self.output))
1817
+
1818
+ # After the framework is built, package it. Needs to happen before
1819
+ # postbuilds, since postbuilds depend on this.
1820
+ if self.type in ("shared_library", "loadable_module"):
1821
+ self.WriteLn(
1822
+ "\t@$(call do_cmd,mac_package_framework,,,%s)"
1823
+ % self.xcode_settings.GetFrameworkVersion()
1824
+ )
1825
+
1826
+ # Bundle postbuilds can depend on the whole bundle, so run them after
1827
+ # the bundle is packaged, not already after the bundle binary is done.
1828
+ if postbuilds:
1829
+ self.WriteLn("\t@$(call do_postbuilds)")
1830
+ postbuilds = [] # Don't write postbuilds for target's output.
1831
+
1832
+ # Needed by test/mac/gyptest-rebuild.py.
1833
+ self.WriteLn("\t@true # No-op, used by tests")
1834
+
1835
+ # Since this target depends on binary and resources which are in
1836
+ # nested subfolders, the framework directory will be older than
1837
+ # its dependencies usually. To prevent this rule from executing
1838
+ # on every build (expensive, especially with postbuilds), explicitly
1839
+ # update the time on the framework directory.
1840
+ self.WriteLn("\t@touch -c %s" % QuoteSpaces(self.output))
1841
+
1842
+ if postbuilds:
1843
+ assert not self.is_mac_bundle, (
1844
+ "Postbuilds for bundles should be done "
1845
+ "on the bundle, not the binary (target '%s')" % self.target
1846
+ )
1847
+ assert "product_dir" not in spec, (
1848
+ "Postbuilds do not work with custom product_dir"
1849
+ )
1850
+
1851
+ if self.type == "executable":
1852
+ self.WriteLn(
1853
+ "%s: LD_INPUTS := %s"
1854
+ % (
1855
+ QuoteSpaces(self.output_binary),
1856
+ " ".join(QuoteSpaces(dep) for dep in link_deps),
1857
+ )
1858
+ )
1859
+ if self.toolset == "host" and self.flavor == "android":
1860
+ self.WriteDoCmd(
1861
+ [self.output_binary],
1862
+ link_deps,
1863
+ "link_host",
1864
+ part_of_all,
1865
+ postbuilds=postbuilds,
1866
+ )
1867
+ else:
1868
+ self.WriteDoCmd(
1869
+ [self.output_binary],
1870
+ link_deps,
1871
+ "link",
1872
+ part_of_all,
1873
+ postbuilds=postbuilds,
1874
+ )
1875
+
1876
+ elif self.type == "static_library":
1877
+ for link_dep in link_deps:
1878
+ assert " " not in link_dep, (
1879
+ "Spaces in alink input filenames not supported (%s)" % link_dep
1880
+ )
1881
+ if (
1882
+ self.flavor not in ("mac", "openbsd", "netbsd", "win")
1883
+ and not self.is_standalone_static_library
1884
+ ):
1885
+ if self.flavor in ("linux", "android"):
1886
+ self.WriteMakeRule(
1887
+ [self.output_binary],
1888
+ link_deps,
1889
+ actions=["$(call create_thin_archive,$@,$^)"],
1890
+ )
1891
+ else:
1892
+ self.WriteDoCmd(
1893
+ [self.output_binary],
1894
+ link_deps,
1895
+ "alink_thin",
1896
+ part_of_all,
1897
+ postbuilds=postbuilds,
1898
+ )
1899
+ elif self.flavor in ("linux", "android"):
1900
+ self.WriteMakeRule(
1901
+ [self.output_binary],
1902
+ link_deps,
1903
+ actions=["$(call create_archive,$@,$^)"],
1904
+ )
1905
+ else:
1906
+ self.WriteDoCmd(
1907
+ [self.output_binary],
1908
+ link_deps,
1909
+ "alink",
1910
+ part_of_all,
1911
+ postbuilds=postbuilds,
1912
+ )
1913
+ elif self.type == "shared_library":
1914
+ self.WriteLn(
1915
+ "%s: LD_INPUTS := %s"
1916
+ % (
1917
+ QuoteSpaces(self.output_binary),
1918
+ " ".join(QuoteSpaces(dep) for dep in link_deps),
1919
+ )
1920
+ )
1921
+ self.WriteDoCmd(
1922
+ [self.output_binary],
1923
+ link_deps,
1924
+ "solink",
1925
+ part_of_all,
1926
+ postbuilds=postbuilds,
1927
+ )
1928
+ # z/OS has a .so target as well as a sidedeck .x target
1929
+ if self.flavor == "zos":
1930
+ self.WriteLn(
1931
+ "%s: %s"
1932
+ % (
1933
+ QuoteSpaces(
1934
+ self.GetSharedObjectFromSidedeck(self.output_binary)
1935
+ ),
1936
+ QuoteSpaces(self.output_binary),
1937
+ )
1938
+ )
1939
+ elif self.type == "loadable_module":
1940
+ for link_dep in link_deps:
1941
+ assert " " not in link_dep, (
1942
+ "Spaces in module input filenames not supported (%s)" % link_dep
1943
+ )
1944
+ if self.toolset == "host" and self.flavor == "android":
1945
+ self.WriteDoCmd(
1946
+ [self.output_binary],
1947
+ link_deps,
1948
+ "solink_module_host",
1949
+ part_of_all,
1950
+ postbuilds=postbuilds,
1951
+ )
1952
+ else:
1953
+ self.WriteDoCmd(
1954
+ [self.output_binary],
1955
+ link_deps,
1956
+ "solink_module",
1957
+ part_of_all,
1958
+ postbuilds=postbuilds,
1959
+ )
1960
+ elif self.type == "none":
1961
+ # Write a stamp line.
1962
+ self.WriteDoCmd(
1963
+ [self.output_binary], deps, "touch", part_of_all, postbuilds=postbuilds
1964
+ )
1965
+ else:
1966
+ print("WARNING: no output for", self.type, self.target)
1967
+
1968
+ # Add an alias for each target (if there are any outputs).
1969
+ # Installable target aliases are created below.
1970
+ if (self.output and self.output != self.target) and (
1971
+ self.type not in self._INSTALLABLE_TARGETS
1972
+ ):
1973
+ self.WriteMakeRule(
1974
+ [self.target], [self.output], comment="Add target alias", phony=True
1975
+ )
1976
+ if part_of_all:
1977
+ self.WriteMakeRule(
1978
+ ["all"],
1979
+ [self.target],
1980
+ comment='Add target alias to "all" target.',
1981
+ phony=True,
1982
+ )
1983
+
1984
+ # Add special-case rules for our installable targets.
1985
+ # 1) They need to install to the build dir or "product" dir.
1986
+ # 2) They get shortcuts for building (e.g. "make chrome").
1987
+ # 3) They are part of "make all".
1988
+ if self.type in self._INSTALLABLE_TARGETS or self.is_standalone_static_library:
1989
+ if self.type == "shared_library":
1990
+ file_desc = "shared library"
1991
+ elif self.type == "static_library":
1992
+ file_desc = "static library"
1993
+ else:
1994
+ file_desc = "executable"
1995
+ install_path = self._InstallableTargetInstallPath()
1996
+ installable_deps = []
1997
+ if self.flavor != "zos":
1998
+ installable_deps.append(self.output)
1999
+ if (
2000
+ self.flavor == "mac"
2001
+ and "product_dir" not in spec
2002
+ and self.toolset == "target"
2003
+ ):
2004
+ # On mac, products are created in install_path immediately.
2005
+ assert install_path == self.output, f"{install_path} != {self.output}"
2006
+
2007
+ # Point the target alias to the final binary output.
2008
+ self.WriteMakeRule(
2009
+ [self.target], [install_path], comment="Add target alias", phony=True
2010
+ )
2011
+ if install_path != self.output:
2012
+ assert not self.is_mac_bundle # See comment a few lines above.
2013
+ self.WriteDoCmd(
2014
+ [install_path],
2015
+ [self.output],
2016
+ "copy",
2017
+ comment="Copy this to the %s output path." % file_desc,
2018
+ part_of_all=part_of_all,
2019
+ )
2020
+ if self.flavor != "zos":
2021
+ installable_deps.append(install_path)
2022
+ if self.flavor == "zos" and self.type == "shared_library":
2023
+ # lib.target/libnode.so has a dependency on $(obj).target/libnode.so
2024
+ self.WriteDoCmd(
2025
+ [self.GetSharedObjectFromSidedeck(install_path)],
2026
+ [self.GetSharedObjectFromSidedeck(self.output)],
2027
+ "copy",
2028
+ comment="Copy this to the %s output path." % file_desc,
2029
+ part_of_all=part_of_all,
2030
+ )
2031
+ # Create a symlink of libnode.x to libnode.version.x
2032
+ self.WriteDoCmd(
2033
+ [self.GetUnversionedSidedeckFromSidedeck(install_path)],
2034
+ [install_path],
2035
+ "symlink",
2036
+ comment="Symlnk this to the %s output path." % file_desc,
2037
+ part_of_all=part_of_all,
2038
+ )
2039
+ # Place libnode.version.so and libnode.x symlink in lib.target dir
2040
+ installable_deps.append(self.GetSharedObjectFromSidedeck(install_path))
2041
+ installable_deps.append(
2042
+ self.GetUnversionedSidedeckFromSidedeck(install_path)
2043
+ )
2044
+ if self.alias not in (self.output, self.target):
2045
+ self.WriteMakeRule(
2046
+ [self.alias],
2047
+ installable_deps,
2048
+ comment="Short alias for building this %s." % file_desc,
2049
+ phony=True,
2050
+ )
2051
+ if self.flavor == "zos" and self.type == "shared_library":
2052
+ # Make sure that .x symlink target is run
2053
+ self.WriteMakeRule(
2054
+ ["all"],
2055
+ [
2056
+ self.GetUnversionedSidedeckFromSidedeck(install_path),
2057
+ self.GetSharedObjectFromSidedeck(install_path),
2058
+ ],
2059
+ comment='Add %s to "all" target.' % file_desc,
2060
+ phony=True,
2061
+ )
2062
+ elif part_of_all:
2063
+ self.WriteMakeRule(
2064
+ ["all"],
2065
+ [install_path],
2066
+ comment='Add %s to "all" target.' % file_desc,
2067
+ phony=True,
2068
+ )
2069
+
2070
+ def WriteList(self, value_list, variable=None, prefix="", quoter=QuoteIfNecessary):
2071
+ """Write a variable definition that is a list of values.
2072
+
2073
+ E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out
2074
+ foo = blaha blahb
2075
+ but in a pretty-printed style.
2076
+ """
2077
+ values = ""
2078
+ if value_list:
2079
+ value_list = [replace_sep(quoter(prefix + value)) for value in value_list]
2080
+ values = " \\\n\t" + " \\\n\t".join(value_list)
2081
+ self.fp.write(f"{variable} :={values}\n\n")
2082
+
2083
+ def WriteDoCmd(
2084
+ self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False
2085
+ ):
2086
+ """Write a Makefile rule that uses do_cmd.
2087
+
2088
+ This makes the outputs dependent on the command line that was run,
2089
+ as well as support the V= make command line flag.
2090
+ """
2091
+ suffix = ""
2092
+ if postbuilds:
2093
+ assert "," not in command
2094
+ suffix = ",,1" # Tell do_cmd to honor $POSTBUILDS
2095
+ self.WriteMakeRule(
2096
+ outputs,
2097
+ inputs,
2098
+ actions=[f"$(call do_cmd,{command}{suffix})"],
2099
+ comment=comment,
2100
+ command=command,
2101
+ force=True,
2102
+ )
2103
+ # Add our outputs to the list of targets we read depfiles from.
2104
+ # all_deps is only used for deps file reading, and for deps files we replace
2105
+ # spaces with ? because escaping doesn't work with make's $(sort) and
2106
+ # other functions.
2107
+ outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs]
2108
+ self.WriteLn("all_deps += %s" % " ".join(outputs))
2109
+
2110
+ def WriteMakeRule(
2111
+ self,
2112
+ outputs,
2113
+ inputs,
2114
+ actions=None,
2115
+ comment=None,
2116
+ order_only=False,
2117
+ force=False,
2118
+ phony=False,
2119
+ command=None,
2120
+ ):
2121
+ """Write a Makefile rule, with some extra tricks.
2122
+
2123
+ outputs: a list of outputs for the rule (note: this is not directly
2124
+ supported by make; see comments below)
2125
+ inputs: a list of inputs for the rule
2126
+ actions: a list of shell commands to run for the rule
2127
+ comment: a comment to put in the Makefile above the rule (also useful
2128
+ for making this Python script's code self-documenting)
2129
+ order_only: if true, makes the dependency order-only
2130
+ force: if true, include FORCE_DO_CMD as an order-only dep
2131
+ phony: if true, the rule does not actually generate the named output, the
2132
+ output is just a name to run the rule
2133
+ command: (optional) command name to generate unambiguous labels
2134
+ """
2135
+ outputs = [QuoteSpaces(o) for o in outputs]
2136
+ inputs = [QuoteSpaces(i) for i in inputs]
2137
+
2138
+ if comment:
2139
+ self.WriteLn("# " + comment)
2140
+ if phony:
2141
+ self.WriteLn(".PHONY: " + " ".join(outputs))
2142
+ if actions:
2143
+ self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0])
2144
+ force_append = " FORCE_DO_CMD" if force else ""
2145
+
2146
+ if order_only:
2147
+ # Order only rule: Just write a simple rule.
2148
+ # TODO(evanm): just make order_only a list of deps instead of this hack.
2149
+ self.WriteLn(
2150
+ "{}: | {}{}".format(" ".join(outputs), " ".join(inputs), force_append)
2151
+ )
2152
+ elif len(outputs) == 1:
2153
+ # Regular rule, one output: Just write a simple rule.
2154
+ self.WriteLn("{}: {}{}".format(outputs[0], " ".join(inputs), force_append))
2155
+ else:
2156
+ # Regular rule, more than one output: Multiple outputs are tricky in
2157
+ # make. We will write three rules:
2158
+ # - All outputs depend on an intermediate file.
2159
+ # - Make .INTERMEDIATE depend on the intermediate.
2160
+ # - The intermediate file depends on the inputs and executes the
2161
+ # actual command.
2162
+ # - The intermediate recipe will 'touch' the intermediate file.
2163
+ # - The multi-output rule will have an do-nothing recipe.
2164
+
2165
+ # Hash the target name to avoid generating overlong filenames.
2166
+ cmddigest = hashlib.sha1(
2167
+ (command or self.target).encode("utf-8")
2168
+ ).hexdigest()
2169
+ intermediate = "%s.intermediate" % cmddigest
2170
+ self.WriteLn("{}: {}".format(" ".join(outputs), intermediate))
2171
+ self.WriteLn("\t%s" % "@:")
2172
+ self.WriteLn("{}: {}".format(".INTERMEDIATE", intermediate))
2173
+ self.WriteLn(
2174
+ "{}: {}{}".format(intermediate, " ".join(inputs), force_append)
2175
+ )
2176
+ actions.insert(0, "$(call do_cmd,touch)")
2177
+
2178
+ if actions:
2179
+ for action in actions:
2180
+ self.WriteLn("\t%s" % action)
2181
+ self.WriteLn()
2182
+
2183
+ def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps):
2184
+ """Write a set of LOCAL_XXX definitions for Android NDK.
2185
+
2186
+ These variable definitions will be used by Android NDK but do nothing for
2187
+ non-Android applications.
2188
+
2189
+ Arguments:
2190
+ module_name: Android NDK module name, which must be unique among all
2191
+ module names.
2192
+ all_sources: A list of source files (will be filtered by Compilable).
2193
+ link_deps: A list of link dependencies, which must be sorted in
2194
+ the order from dependencies to dependents.
2195
+ """
2196
+ if self.type not in ("executable", "shared_library", "static_library"):
2197
+ return
2198
+
2199
+ self.WriteLn("# Variable definitions for Android applications")
2200
+ self.WriteLn("include $(CLEAR_VARS)")
2201
+ self.WriteLn("LOCAL_MODULE := " + module_name)
2202
+ self.WriteLn(
2203
+ "LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) "
2204
+ "$(DEFS_$(BUILDTYPE)) "
2205
+ # LOCAL_CFLAGS is applied to both of C and C++. There is
2206
+ # no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C
2207
+ # sources.
2208
+ "$(CFLAGS_C_$(BUILDTYPE)) "
2209
+ # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while
2210
+ # LOCAL_C_INCLUDES does not expect it. So put it in
2211
+ # LOCAL_CFLAGS.
2212
+ "$(INCS_$(BUILDTYPE))"
2213
+ )
2214
+ # LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred.
2215
+ self.WriteLn("LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))")
2216
+ self.WriteLn("LOCAL_C_INCLUDES :=")
2217
+ self.WriteLn("LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)")
2218
+
2219
+ # Detect the C++ extension.
2220
+ cpp_ext = {".cc": 0, ".cpp": 0, ".cxx": 0}
2221
+ default_cpp_ext = ".cpp"
2222
+ for filename in all_sources:
2223
+ ext = os.path.splitext(filename)[1]
2224
+ if ext in cpp_ext:
2225
+ cpp_ext[ext] += 1
2226
+ if cpp_ext[ext] > cpp_ext[default_cpp_ext]:
2227
+ default_cpp_ext = ext
2228
+ self.WriteLn("LOCAL_CPP_EXTENSION := " + default_cpp_ext)
2229
+
2230
+ self.WriteList(
2231
+ list(map(self.Absolutify, filter(Compilable, all_sources))),
2232
+ "LOCAL_SRC_FILES",
2233
+ )
2234
+
2235
+ # Filter out those which do not match prefix and suffix and produce
2236
+ # the resulting list without prefix and suffix.
2237
+ def DepsToModules(deps, prefix, suffix):
2238
+ modules = []
2239
+ for filepath in deps:
2240
+ filename = os.path.basename(filepath)
2241
+ if filename.startswith(prefix) and filename.endswith(suffix):
2242
+ modules.append(filename[len(prefix) : -len(suffix)])
2243
+ return modules
2244
+
2245
+ # Retrieve the default value of 'SHARED_LIB_SUFFIX'
2246
+ params = {"flavor": "linux"}
2247
+ default_variables = {}
2248
+ CalculateVariables(default_variables, params)
2249
+
2250
+ self.WriteList(
2251
+ DepsToModules(
2252
+ link_deps,
2253
+ generator_default_variables["SHARED_LIB_PREFIX"],
2254
+ default_variables["SHARED_LIB_SUFFIX"],
2255
+ ),
2256
+ "LOCAL_SHARED_LIBRARIES",
2257
+ )
2258
+ self.WriteList(
2259
+ DepsToModules(
2260
+ link_deps,
2261
+ generator_default_variables["STATIC_LIB_PREFIX"],
2262
+ generator_default_variables["STATIC_LIB_SUFFIX"],
2263
+ ),
2264
+ "LOCAL_STATIC_LIBRARIES",
2265
+ )
2266
+
2267
+ if self.type == "executable":
2268
+ self.WriteLn("include $(BUILD_EXECUTABLE)")
2269
+ elif self.type == "shared_library":
2270
+ self.WriteLn("include $(BUILD_SHARED_LIBRARY)")
2271
+ elif self.type == "static_library":
2272
+ self.WriteLn("include $(BUILD_STATIC_LIBRARY)")
2273
+ self.WriteLn()
2274
+
2275
+ def WriteLn(self, text=""):
2276
+ self.fp.write(text + "\n")
2277
+
2278
+ def GetSortedXcodeEnv(self, additional_settings=None):
2279
+ return gyp.xcode_emulation.GetSortedXcodeEnv(
2280
+ self.xcode_settings,
2281
+ "$(abs_builddir)",
2282
+ os.path.join("$(abs_srcdir)", self.path),
2283
+ "$(BUILDTYPE)",
2284
+ additional_settings,
2285
+ )
2286
+
2287
+ def GetSortedXcodePostbuildEnv(self):
2288
+ # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack.
2289
+ # TODO(thakis): It would be nice to have some general mechanism instead.
2290
+ strip_save_file = self.xcode_settings.GetPerTargetSetting(
2291
+ "CHROMIUM_STRIP_SAVE_FILE", ""
2292
+ )
2293
+ # Even if strip_save_file is empty, explicitly write it. Else a postbuild
2294
+ # might pick up an export from an earlier target.
2295
+ return self.GetSortedXcodeEnv(
2296
+ additional_settings={"CHROMIUM_STRIP_SAVE_FILE": strip_save_file}
2297
+ )
2298
+
2299
+ def WriteSortedXcodeEnv(self, target, env):
2300
+ for k, v in env:
2301
+ # For
2302
+ # foo := a\ b
2303
+ # the escaped space does the right thing. For
2304
+ # export foo := a\ b
2305
+ # it does not -- the backslash is written to the env as literal character.
2306
+ # So don't escape spaces in |env[k]|.
2307
+ self.WriteLn(f"{QuoteSpaces(target)}: export {k} := {v}")
2308
+
2309
+ def Objectify(self, path):
2310
+ """Convert a path to its output directory form."""
2311
+ if "$(" in path:
2312
+ path = path.replace("$(obj)/", "$(obj).%s/$(TARGET)/" % self.toolset)
2313
+ if "$(obj)" not in path:
2314
+ path = f"$(obj).{self.toolset}/$(TARGET)/{path}"
2315
+ return path
2316
+
2317
+ def Pchify(self, path, lang):
2318
+ """Convert a prefix header path to its output directory form."""
2319
+ path = self.Absolutify(path)
2320
+ if "$(" in path:
2321
+ path = path.replace(
2322
+ "$(obj)/", f"$(obj).{self.toolset}/$(TARGET)/pch-{lang}"
2323
+ )
2324
+ return path
2325
+ return f"$(obj).{self.toolset}/$(TARGET)/pch-{lang}/{path}"
2326
+
2327
+ def Absolutify(self, path):
2328
+ """Convert a subdirectory-relative path into a base-relative path.
2329
+ Skips over paths that contain variables."""
2330
+ if "$(" in path:
2331
+ # Don't call normpath in this case, as it might collapse the
2332
+ # path too aggressively if it features '..'. However it's still
2333
+ # important to strip trailing slashes.
2334
+ return path.rstrip("/")
2335
+ return os.path.normpath(os.path.join(self.path, path))
2336
+
2337
+ def ExpandInputRoot(self, template, expansion, dirname):
2338
+ if "%(INPUT_ROOT)s" not in template and "%(INPUT_DIRNAME)s" not in template:
2339
+ return template
2340
+ path = template % {
2341
+ "INPUT_ROOT": expansion,
2342
+ "INPUT_DIRNAME": dirname,
2343
+ }
2344
+ return path
2345
+
2346
+ def _InstallableTargetInstallPath(self):
2347
+ """Returns the location of the final output for an installable target."""
2348
+ # Functionality removed for all platforms to match Xcode and hoist
2349
+ # shared libraries into PRODUCT_DIR for users:
2350
+ # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files
2351
+ # rely on this. Emulate this behavior for mac.
2352
+ # if self.type == "shared_library" and (
2353
+ # self.flavor != "mac" or self.toolset != "target"
2354
+ # ):
2355
+ # # Install all shared libs into a common directory (per toolset) for
2356
+ # # convenient access with LD_LIBRARY_PATH.
2357
+ # return "$(builddir)/lib.%s/%s" % (self.toolset, self.alias)
2358
+ if self.flavor == "zos" and self.type == "shared_library":
2359
+ return "$(builddir)/lib.%s/%s" % (self.toolset, self.alias)
2360
+
2361
+ return "$(builddir)/" + self.alias
2362
+
2363
+
2364
+ def WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files):
2365
+ """Write the target to regenerate the Makefile."""
2366
+ options = params["options"]
2367
+ build_files_args = [
2368
+ gyp.common.RelativePath(filename, options.toplevel_dir)
2369
+ for filename in params["build_files_arg"]
2370
+ ]
2371
+
2372
+ gyp_binary = gyp.common.FixIfRelativePath(
2373
+ params["gyp_binary"], options.toplevel_dir
2374
+ )
2375
+ if not gyp_binary.startswith(os.sep):
2376
+ gyp_binary = os.path.join(".", gyp_binary)
2377
+
2378
+ root_makefile.write(
2379
+ "quiet_cmd_regen_makefile = ACTION Regenerating $@\n"
2380
+ "cmd_regen_makefile = cd $(srcdir); %(cmd)s\n"
2381
+ "%(makefile_name)s: %(deps)s\n"
2382
+ "\t$(call do_cmd,regen_makefile)\n\n"
2383
+ % {
2384
+ "makefile_name": makefile_name,
2385
+ "deps": replace_sep(
2386
+ " ".join(SourceifyAndQuoteSpaces(bf) for bf in build_files)
2387
+ ),
2388
+ "cmd": replace_sep(gyp.common.EncodePOSIXShellList(
2389
+ [gyp_binary, "-fmake"] + gyp.RegenerateFlags(options) + build_files_args
2390
+ )),
2391
+ }
2392
+ )
2393
+
2394
+
2395
+ def PerformBuild(data, configurations, params):
2396
+ options = params["options"]
2397
+ for config in configurations:
2398
+ arguments = ["make"]
2399
+ if options.toplevel_dir and options.toplevel_dir != ".":
2400
+ arguments += "-C", options.toplevel_dir
2401
+ arguments.append("BUILDTYPE=" + config)
2402
+ print(f"Building [{config}]: {arguments}")
2403
+ subprocess.check_call(arguments)
2404
+
2405
+
2406
+ def GenerateOutput(target_list, target_dicts, data, params):
2407
+ options = params["options"]
2408
+ flavor = gyp.common.GetFlavor(params)
2409
+ generator_flags = params.get("generator_flags", {})
2410
+ builddir_name = generator_flags.get("output_dir", "out")
2411
+ android_ndk_version = generator_flags.get("android_ndk_version", None)
2412
+ default_target = generator_flags.get("default_target", "all")
2413
+
2414
+ def CalculateMakefilePath(build_file, base_name):
2415
+ """Determine where to write a Makefile for a given gyp file."""
2416
+ # Paths in gyp files are relative to the .gyp file, but we want
2417
+ # paths relative to the source root for the master makefile. Grab
2418
+ # the path of the .gyp file as the base to relativize against.
2419
+ # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp".
2420
+ base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.depth)
2421
+ # We write the file in the base_path directory.
2422
+ output_file = os.path.join(options.depth, base_path, base_name)
2423
+ if options.generator_output:
2424
+ output_file = os.path.join(
2425
+ options.depth, options.generator_output, base_path, base_name
2426
+ )
2427
+ base_path = gyp.common.RelativePath(
2428
+ os.path.dirname(build_file), options.toplevel_dir
2429
+ )
2430
+ return base_path, output_file
2431
+
2432
+ # TODO: search for the first non-'Default' target. This can go
2433
+ # away when we add verification that all targets have the
2434
+ # necessary configurations.
2435
+ default_configuration = None
2436
+ toolsets = {target_dicts[target]["toolset"] for target in target_list}
2437
+ for target in target_list:
2438
+ spec = target_dicts[target]
2439
+ if spec["default_configuration"] != "Default":
2440
+ default_configuration = spec["default_configuration"]
2441
+ break
2442
+ if not default_configuration:
2443
+ default_configuration = "Default"
2444
+
2445
+ srcdir = "."
2446
+ makefile_name = "Makefile" + options.suffix
2447
+ makefile_path = os.path.join(options.toplevel_dir, makefile_name)
2448
+ if options.generator_output:
2449
+ global srcdir_prefix
2450
+ makefile_path = os.path.join(
2451
+ options.toplevel_dir, options.generator_output, makefile_name
2452
+ )
2453
+ srcdir = replace_sep(gyp.common.RelativePath(srcdir, options.generator_output))
2454
+ srcdir_prefix = "$(srcdir)/"
2455
+
2456
+ flock_command = "flock"
2457
+ copy_archive_arguments = "-af"
2458
+ makedep_arguments = "-MMD"
2459
+
2460
+ # wasm-ld doesn't support --start-group/--end-group
2461
+ link_commands = LINK_COMMANDS_LINUX
2462
+ if flavor in ["wasi", "wasm"]:
2463
+ link_commands = link_commands.replace(' -Wl,--start-group', '').replace(
2464
+ ' -Wl,--end-group', ''
2465
+ )
2466
+
2467
+ CC_target = replace_sep(GetEnvironFallback(("CC_target", "CC"), "$(CC)"))
2468
+ AR_target = replace_sep(GetEnvironFallback(("AR_target", "AR"), "$(AR)"))
2469
+ CXX_target = replace_sep(GetEnvironFallback(("CXX_target", "CXX"), "$(CXX)"))
2470
+ LINK_target = replace_sep(GetEnvironFallback(("LINK_target", "LINK"), "$(LINK)"))
2471
+ PLI_target = replace_sep(GetEnvironFallback(("PLI_target", "PLI"), "pli"))
2472
+ CC_host = replace_sep(GetEnvironFallback(("CC_host", "CC"), "gcc"))
2473
+ AR_host = replace_sep(GetEnvironFallback(("AR_host", "AR"), "ar"))
2474
+ CXX_host = replace_sep(GetEnvironFallback(("CXX_host", "CXX"), "g++"))
2475
+ LINK_host = replace_sep(GetEnvironFallback(("LINK_host", "LINK"), "$(CXX.host)"))
2476
+ PLI_host = replace_sep(GetEnvironFallback(("PLI_host", "PLI"), "pli"))
2477
+
2478
+ header_params = {
2479
+ "default_target": default_target,
2480
+ "builddir": builddir_name,
2481
+ "default_configuration": default_configuration,
2482
+ "flock": flock_command,
2483
+ "flock_index": 1,
2484
+ "link_commands": link_commands,
2485
+ "extra_commands": "",
2486
+ "srcdir": srcdir,
2487
+ "copy_archive_args": copy_archive_arguments,
2488
+ "makedep_args": makedep_arguments,
2489
+ "CC.target": CC_target,
2490
+ "AR.target": AR_target,
2491
+ "CXX.target": CXX_target,
2492
+ "LINK.target": LINK_target,
2493
+ "PLI.target": PLI_target,
2494
+ "CC.host": CC_host,
2495
+ "AR.host": AR_host,
2496
+ "CXX.host": CXX_host,
2497
+ "LINK.host": LINK_host,
2498
+ "PLI.host": PLI_host,
2499
+ }
2500
+ if flavor == "mac":
2501
+ flock_command = "%s gyp-mac-tool flock" % sys.executable
2502
+ header_params.update(
2503
+ {
2504
+ "flock": flock_command,
2505
+ "flock_index": 2,
2506
+ "link_commands": LINK_COMMANDS_MAC,
2507
+ "extra_commands": SHARED_HEADER_MAC_COMMANDS,
2508
+ }
2509
+ )
2510
+ elif flavor == "android":
2511
+ header_params.update({"link_commands": LINK_COMMANDS_ANDROID})
2512
+ elif flavor == "zos":
2513
+ copy_archive_arguments = "-fPR"
2514
+ CC_target = GetEnvironFallback(("CC_target", "CC"), "njsc")
2515
+ makedep_arguments = "-MMD"
2516
+ if CC_target == "clang":
2517
+ CC_host = GetEnvironFallback(("CC_host", "CC"), "clang")
2518
+ CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "clang++")
2519
+ CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "clang++")
2520
+ elif CC_target == "ibm-clang64":
2521
+ CC_host = GetEnvironFallback(("CC_host", "CC"), "ibm-clang64")
2522
+ CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "ibm-clang++64")
2523
+ CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "ibm-clang++64")
2524
+ elif CC_target == "ibm-clang":
2525
+ CC_host = GetEnvironFallback(("CC_host", "CC"), "ibm-clang")
2526
+ CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "ibm-clang++")
2527
+ CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "ibm-clang++")
2528
+ else:
2529
+ # Node.js versions prior to v18:
2530
+ makedep_arguments = "-qmakedep=gcc"
2531
+ CC_host = GetEnvironFallback(("CC_host", "CC"), "njsc")
2532
+ CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "njsc++")
2533
+ CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "njsc++")
2534
+ header_params.update(
2535
+ {
2536
+ "copy_archive_args": copy_archive_arguments,
2537
+ "makedep_args": makedep_arguments,
2538
+ "link_commands": LINK_COMMANDS_OS390,
2539
+ "extra_commands": SHARED_HEADER_OS390_COMMANDS,
2540
+ "CC.target": CC_target,
2541
+ "CXX.target": CXX_target,
2542
+ "CC.host": CC_host,
2543
+ "CXX.host": CXX_host,
2544
+ }
2545
+ )
2546
+ elif flavor == "solaris":
2547
+ copy_archive_arguments = "-pPRf@"
2548
+ header_params.update(
2549
+ {
2550
+ "copy_archive_args": copy_archive_arguments,
2551
+ "flock": "%s gyp-flock-tool flock" % sys.executable,
2552
+ "flock_index": 2,
2553
+ }
2554
+ )
2555
+ elif flavor == "freebsd":
2556
+ # Note: OpenBSD has sysutils/flock. lockf seems to be FreeBSD specific.
2557
+ header_params.update({"flock": "lockf"})
2558
+ elif flavor == "openbsd":
2559
+ copy_archive_arguments = "-pPRf"
2560
+ header_params.update({"copy_archive_args": copy_archive_arguments})
2561
+ elif flavor == "aix":
2562
+ copy_archive_arguments = "-pPRf"
2563
+ header_params.update(
2564
+ {
2565
+ "copy_archive_args": copy_archive_arguments,
2566
+ "link_commands": LINK_COMMANDS_AIX,
2567
+ "flock": "%s gyp-flock-tool flock" % sys.executable,
2568
+ "flock_index": 2,
2569
+ }
2570
+ )
2571
+ elif flavor == "os400":
2572
+ copy_archive_arguments = "-pPRf"
2573
+ header_params.update(
2574
+ {
2575
+ "copy_archive_args": copy_archive_arguments,
2576
+ "link_commands": LINK_COMMANDS_OS400,
2577
+ "flock": "%s gyp-flock-tool flock" % sys.executable,
2578
+ "flock_index": 2,
2579
+ }
2580
+ )
2581
+
2582
+ build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0])
2583
+ make_global_settings_array = data[build_file].get("make_global_settings", [])
2584
+ wrappers = {}
2585
+ for key, value in make_global_settings_array:
2586
+ if key.endswith("_wrapper"):
2587
+ wrappers[key[: -len("_wrapper")]] = "$(abspath %s)" % value
2588
+ make_global_settings = ""
2589
+ for key, value in make_global_settings_array:
2590
+ if re.match(".*_wrapper", key):
2591
+ continue
2592
+ if value[0] != "$":
2593
+ value = "$(abspath %s)" % value
2594
+ wrapper = wrappers.get(key)
2595
+ if wrapper:
2596
+ value = f"{wrapper} {value}"
2597
+ del wrappers[key]
2598
+ if key in ("CC", "CC.host", "CXX", "CXX.host"):
2599
+ make_global_settings += (
2600
+ "ifneq (,$(filter $(origin %s), undefined default))\n" % key
2601
+ )
2602
+ # Let gyp-time envvars win over global settings.
2603
+ env_key = key.replace(".", "_") # CC.host -> CC_host
2604
+ if env_key in os.environ:
2605
+ value = os.environ[env_key]
2606
+ make_global_settings += f" {key} = {value}\n"
2607
+ make_global_settings += "endif\n"
2608
+ else:
2609
+ make_global_settings += f"{key} ?= {value}\n"
2610
+ # TODO(ukai): define cmd when only wrapper is specified in
2611
+ # make_global_settings.
2612
+
2613
+ header_params["make_global_settings"] = make_global_settings
2614
+
2615
+ gyp.common.EnsureDirExists(makefile_path)
2616
+ root_makefile = open(makefile_path, "w")
2617
+ root_makefile.write(SHARED_HEADER % header_params)
2618
+ # Currently any versions have the same effect, but in future the behavior
2619
+ # could be different.
2620
+ if android_ndk_version:
2621
+ root_makefile.write(
2622
+ "# Define LOCAL_PATH for build of Android applications.\n"
2623
+ "LOCAL_PATH := $(call my-dir)\n"
2624
+ "\n"
2625
+ )
2626
+ for toolset in toolsets:
2627
+ root_makefile.write("TOOLSET := %s\n" % toolset)
2628
+ WriteRootHeaderSuffixRules(root_makefile)
2629
+
2630
+ # Put build-time support tools next to the root Makefile.
2631
+ dest_path = os.path.dirname(makefile_path)
2632
+ gyp.common.CopyTool(flavor, dest_path)
2633
+
2634
+ # Find the list of targets that derive from the gyp file(s) being built.
2635
+ needed_targets = set()
2636
+ for build_file in params["build_files"]:
2637
+ for target in gyp.common.AllTargets(target_list, target_dicts, build_file):
2638
+ needed_targets.add(target)
2639
+
2640
+ build_files = set()
2641
+ include_list = set()
2642
+ for qualified_target in target_list:
2643
+ build_file, target, toolset = gyp.common.ParseQualifiedTarget(qualified_target)
2644
+
2645
+ this_make_global_settings = data[build_file].get("make_global_settings", [])
2646
+ assert make_global_settings_array == this_make_global_settings, (
2647
+ "make_global_settings needs to be the same for all targets "
2648
+ f"{this_make_global_settings} vs. {make_global_settings}"
2649
+ )
2650
+
2651
+ build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir))
2652
+ included_files = data[build_file]["included_files"]
2653
+ for included_file in included_files:
2654
+ # The included_files entries are relative to the dir of the build file
2655
+ # that included them, so we have to undo that and then make them relative
2656
+ # to the root dir.
2657
+ relative_include_file = gyp.common.RelativePath(
2658
+ gyp.common.UnrelativePath(included_file, build_file),
2659
+ options.toplevel_dir,
2660
+ )
2661
+ abs_include_file = os.path.abspath(relative_include_file)
2662
+ # If the include file is from the ~/.gyp dir, we should use absolute path
2663
+ # so that relocating the src dir doesn't break the path.
2664
+ if params["home_dot_gyp"] and abs_include_file.startswith(
2665
+ params["home_dot_gyp"]
2666
+ ):
2667
+ build_files.add(abs_include_file)
2668
+ else:
2669
+ build_files.add(relative_include_file)
2670
+
2671
+ base_path, output_file = CalculateMakefilePath(
2672
+ build_file, target + "." + toolset + options.suffix + ".mk"
2673
+ )
2674
+
2675
+ spec = target_dicts[qualified_target]
2676
+ configs = spec["configurations"]
2677
+
2678
+ if flavor == "mac":
2679
+ gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec)
2680
+
2681
+ writer = MakefileWriter(generator_flags, flavor)
2682
+ writer.Write(
2683
+ qualified_target,
2684
+ base_path,
2685
+ output_file,
2686
+ spec,
2687
+ configs,
2688
+ part_of_all=qualified_target in needed_targets,
2689
+ )
2690
+
2691
+ # Our root_makefile lives at the source root. Compute the relative path
2692
+ # from there to the output_file for including.
2693
+ mkfile_rel_path = gyp.common.RelativePath(
2694
+ output_file, os.path.dirname(makefile_path)
2695
+ )
2696
+ include_list.add(mkfile_rel_path)
2697
+
2698
+ # Write out per-gyp (sub-project) Makefiles.
2699
+ depth_rel_path = gyp.common.RelativePath(options.depth, os.getcwd())
2700
+ for build_file in build_files:
2701
+ # The paths in build_files were relativized above, so undo that before
2702
+ # testing against the non-relativized items in target_list and before
2703
+ # calculating the Makefile path.
2704
+ build_file = os.path.join(depth_rel_path, build_file)
2705
+ gyp_targets = [
2706
+ target_dicts[qualified_target]["target_name"]
2707
+ for qualified_target in target_list
2708
+ if qualified_target.startswith(build_file)
2709
+ and qualified_target in needed_targets
2710
+ ]
2711
+ # Only generate Makefiles for gyp files with targets.
2712
+ if not gyp_targets:
2713
+ continue
2714
+ base_path, output_file = CalculateMakefilePath(
2715
+ build_file, os.path.splitext(os.path.basename(build_file))[0] + ".Makefile"
2716
+ )
2717
+ makefile_rel_path = gyp.common.RelativePath(
2718
+ os.path.dirname(makefile_path), os.path.dirname(output_file)
2719
+ )
2720
+ writer.WriteSubMake(output_file, makefile_rel_path, gyp_targets, builddir_name)
2721
+
2722
+ # Write out the sorted list of includes.
2723
+ root_makefile.write("\n")
2724
+ for include_file in sorted(include_list):
2725
+ # We wrap each .mk include in an if statement so users can tell make to
2726
+ # not load a file by setting NO_LOAD. The below make code says, only
2727
+ # load the .mk file if the .mk filename doesn't start with a token in
2728
+ # NO_LOAD.
2729
+ root_makefile.write(
2730
+ "ifeq ($(strip $(foreach prefix,$(NO_LOAD),\\\n"
2731
+ " $(findstring $(join ^,$(prefix)),\\\n"
2732
+ " $(join ^," + include_file + ")))),)\n"
2733
+ )
2734
+ root_makefile.write(" include " + include_file + "\n")
2735
+ root_makefile.write("endif\n")
2736
+ root_makefile.write("\n")
2737
+
2738
+ if not generator_flags.get("standalone") and generator_flags.get(
2739
+ "auto_regeneration", True
2740
+ ):
2741
+ WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files)
2742
+
2743
+ root_makefile.write(SHARED_FOOTER)
2744
+
2745
+ root_makefile.close()