-
Notifications
You must be signed in to change notification settings - Fork 74
/
ninja.py
2964 lines (2679 loc) · 117 KB
/
ninja.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import copy
import hashlib
import json
import multiprocessing
import os.path
import re
import signal
import shutil
import subprocess
import sys
import gyp
import gyp.common
import gyp.msvs_emulation
import gyp.MSVSUtil as MSVSUtil
import gyp.xcode_emulation
from io import StringIO
from gyp.common import GetEnvironFallback
import gyp.ninja_syntax as ninja_syntax
generator_default_variables = {
"EXECUTABLE_PREFIX": "",
"EXECUTABLE_SUFFIX": "",
"STATIC_LIB_PREFIX": "lib",
"STATIC_LIB_SUFFIX": ".a",
"SHARED_LIB_PREFIX": "lib",
# Gyp expects the following variables to be expandable by the build
# system to the appropriate locations. Ninja prefers paths to be
# known at gyp time. To resolve this, introduce special
# variables starting with $! and $| (which begin with a $ so gyp knows it
# should be treated specially, but is otherwise an invalid
# ninja/shell variable) that are passed to gyp here but expanded
# before writing out into the target .ninja files; see
# ExpandSpecial.
# $! is used for variables that represent a path and that can only appear at
# the start of a string, while $| is used for variables that can appear
# anywhere in a string.
"INTERMEDIATE_DIR": "$!INTERMEDIATE_DIR",
"SHARED_INTERMEDIATE_DIR": "$!PRODUCT_DIR/gen",
"PRODUCT_DIR": "$!PRODUCT_DIR",
"CONFIGURATION_NAME": "$|CONFIGURATION_NAME",
# Special variables that may be used by gyp 'rule' targets.
# We generate definitions for these variables on the fly when processing a
# rule.
"RULE_INPUT_ROOT": "${root}",
"RULE_INPUT_DIRNAME": "${dirname}",
"RULE_INPUT_PATH": "${source}",
"RULE_INPUT_EXT": "${ext}",
"RULE_INPUT_NAME": "${name}",
}
# Placates pylint.
generator_additional_non_configuration_keys = []
generator_additional_path_sections = []
generator_extra_sources_for_rules = []
generator_filelist_paths = None
generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested()
def StripPrefix(arg, prefix):
if arg.startswith(prefix):
return arg[len(prefix) :]
return arg
def QuoteShellArgument(arg, flavor):
"""Quote a string such that it will be interpreted as a single argument
by the shell."""
# Rather than attempting to enumerate the bad shell characters, just
# allow common OK ones and quote anything else.
if re.match(r"^[a-zA-Z0-9_=.\\/-]+$", arg):
return arg # No quoting necessary.
if flavor == "win":
return gyp.msvs_emulation.QuoteForRspFile(arg)
return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"
def Define(d, flavor):
"""Takes a preprocessor define and returns a -D parameter that's ninja- and
shell-escaped."""
if flavor == "win":
# cl.exe replaces literal # characters with = in preprocessor definitions for
# some reason. Octal-encode to work around that.
d = d.replace("#", "\\%03o" % ord("#"))
return QuoteShellArgument(ninja_syntax.escape("-D" + d), flavor)
def AddArch(output, arch):
"""Adds an arch string to an output path."""
output, extension = os.path.splitext(output)
return f"{output}.{arch}{extension}"
class Target:
"""Target represents the paths used within a single gyp target.
Conceptually, building a single target A is a series of steps:
1) actions/rules/copies generates source/resources/etc.
2) compiles generates .o files
3) link generates a binary (library/executable)
4) bundle merges the above in a mac bundle
(Any of these steps can be optional.)
From a build ordering perspective, a dependent target B could just
depend on the last output of this series of steps.
But some dependent commands sometimes need to reach inside the box.
For example, when linking B it needs to get the path to the static
library generated by A.
This object stores those paths. To keep things simple, member
variables only store concrete paths to single files, while methods
compute derived values like "the last output of the target".
"""
def __init__(self, type):
# Gyp type ("static_library", etc.) of this target.
self.type = type
# File representing whether any input dependencies necessary for
# dependent actions have completed.
self.preaction_stamp = None
# File representing whether any input dependencies necessary for
# dependent compiles have completed.
self.precompile_stamp = None
# File representing the completion of actions/rules/copies, if any.
self.actions_stamp = None
# Path to the output of the link step, if any.
self.binary = None
# Path to the file representing the completion of building the bundle,
# if any.
self.bundle = None
# On Windows, incremental linking requires linking against all the .objs
# that compose a .lib (rather than the .lib itself). That list is stored
# here. In this case, we also need to save the compile_deps for the target,
# so that the target that directly depends on the .objs can also depend
# on those.
self.component_objs = None
self.compile_deps = None
# Windows only. The import .lib is the output of a build step, but
# because dependents only link against the lib (not both the lib and the
# dll) we keep track of the import library here.
self.import_lib = None
# Track if this target contains any C++ files, to decide if gcc or g++
# should be used for linking.
self.uses_cpp = False
def Linkable(self):
"""Return true if this is a target that can be linked against."""
return self.type in ("static_library", "shared_library")
def UsesToc(self, flavor):
"""Return true if the target should produce a restat rule based on a TOC
file."""
# For bundles, the .TOC should be produced for the binary, not for
# FinalOutput(). But the naive approach would put the TOC file into the
# bundle, so don't do this for bundles for now.
if flavor == "win" or self.bundle:
return False
return self.type in ("shared_library", "loadable_module")
def PreActionInput(self, flavor):
"""Return the path, if any, that should be used as a dependency of
any dependent action step."""
if self.UsesToc(flavor):
return self.FinalOutput() + ".TOC"
return self.FinalOutput() or self.preaction_stamp
def PreCompileInput(self):
"""Return the path, if any, that should be used as a dependency of
any dependent compile step."""
return self.actions_stamp or self.precompile_stamp
def FinalOutput(self):
"""Return the last output of the target, which depends on all prior
steps."""
return self.bundle or self.binary or self.actions_stamp
# A small discourse on paths as used within the Ninja build:
# All files we produce (both at gyp and at build time) appear in the
# build directory (e.g. out/Debug).
#
# Paths within a given .gyp file are always relative to the directory
# containing the .gyp file. Call these "gyp paths". This includes
# sources as well as the starting directory a given gyp rule/action
# expects to be run from. We call the path from the source root to
# the gyp file the "base directory" within the per-.gyp-file
# NinjaWriter code.
#
# All paths as written into the .ninja files are relative to the build
# directory. Call these paths "ninja paths".
#
# We translate between these two notions of paths with two helper
# functions:
#
# - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file)
# into the equivalent ninja path.
#
# - GypPathToUniqueOutput translates a gyp path into a ninja path to write
# an output file; the result can be namespaced such that it is unique
# to the input file name as well as the output target name.
class NinjaWriter:
def __init__(
self,
hash_for_rules,
target_outputs,
base_dir,
build_dir,
output_file,
toplevel_build,
output_file_name,
flavor,
toplevel_dir=None,
):
"""
base_dir: path from source root to directory containing this gyp file,
by gyp semantics, all input paths are relative to this
build_dir: path from source root to build output
toplevel_dir: path to the toplevel directory
"""
self.hash_for_rules = hash_for_rules
self.target_outputs = target_outputs
self.base_dir = base_dir
self.build_dir = build_dir
self.ninja = ninja_syntax.Writer(output_file)
self.toplevel_build = toplevel_build
self.output_file_name = output_file_name
self.flavor = flavor
self.abs_build_dir = None
if toplevel_dir is not None:
self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir))
self.obj_ext = ".obj" if flavor == "win" else ".o"
if flavor == "win":
# See docstring of msvs_emulation.GenerateEnvironmentFiles().
self.win_env = {}
for arch in ("x86", "x64"):
self.win_env[arch] = "environment." + arch
# Relative path from build output dir to base dir.
build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir)
self.build_to_base = os.path.join(build_to_top, base_dir)
# Relative path from base dir to build dir.
base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir)
self.base_to_build = os.path.join(base_to_top, build_dir)
def ExpandSpecial(self, path, product_dir=None):
"""Expand specials like $!PRODUCT_DIR in |path|.
If |product_dir| is None, assumes the cwd is already the product
dir. Otherwise, |product_dir| is the relative path to the product
dir.
"""
PRODUCT_DIR = "$!PRODUCT_DIR"
if PRODUCT_DIR in path:
if product_dir:
path = path.replace(PRODUCT_DIR, product_dir)
else:
path = path.replace(PRODUCT_DIR + "/", "")
path = path.replace(PRODUCT_DIR + "\\", "")
path = path.replace(PRODUCT_DIR, ".")
INTERMEDIATE_DIR = "$!INTERMEDIATE_DIR"
if INTERMEDIATE_DIR in path:
int_dir = self.GypPathToUniqueOutput("gen")
# GypPathToUniqueOutput generates a path relative to the product dir,
# so insert product_dir in front if it is provided.
path = path.replace(
INTERMEDIATE_DIR, os.path.join(product_dir or "", int_dir)
)
CONFIGURATION_NAME = "$|CONFIGURATION_NAME"
path = path.replace(CONFIGURATION_NAME, self.config_name)
return path
def ExpandRuleVariables(self, path, root, dirname, source, ext, name):
if self.flavor == "win":
path = self.msvs_settings.ConvertVSMacros(path, config=self.config_name)
path = path.replace(generator_default_variables["RULE_INPUT_ROOT"], root)
path = path.replace(generator_default_variables["RULE_INPUT_DIRNAME"], dirname)
path = path.replace(generator_default_variables["RULE_INPUT_PATH"], source)
path = path.replace(generator_default_variables["RULE_INPUT_EXT"], ext)
path = path.replace(generator_default_variables["RULE_INPUT_NAME"], name)
return path
def GypPathToNinja(self, path, env=None):
"""Translate a gyp path to a ninja path, optionally expanding environment
variable references in |path| with |env|.
See the above discourse on path conversions."""
if env:
if self.flavor == "mac":
path = gyp.xcode_emulation.ExpandEnvVars(path, env)
elif self.flavor == "win":
path = gyp.msvs_emulation.ExpandMacros(path, env)
if path.startswith("$!"):
expanded = self.ExpandSpecial(path)
if self.flavor == "win":
expanded = os.path.normpath(expanded)
return expanded
if "$|" in path:
path = self.ExpandSpecial(path)
assert "$" not in path, path
return os.path.normpath(os.path.join(self.build_to_base, path))
def GypPathToUniqueOutput(self, path, qualified=True):
"""Translate a gyp path to a ninja path for writing output.
If qualified is True, qualify the resulting filename with the name
of the target. This is necessary when e.g. compiling the same
path twice for two separate output targets.
See the above discourse on path conversions."""
path = self.ExpandSpecial(path)
assert not path.startswith("$"), path
# Translate the path following this scheme:
# Input: foo/bar.gyp, target targ, references baz/out.o
# Output: obj/foo/baz/targ.out.o (if qualified)
# obj/foo/baz/out.o (otherwise)
# (and obj.host instead of obj for cross-compiles)
#
# Why this scheme and not some other one?
# 1) for a given input, you can compute all derived outputs by matching
# its path, even if the input is brought via a gyp file with '..'.
# 2) simple files like libraries and stamps have a simple filename.
obj = "obj"
if self.toolset != "target":
obj += "." + self.toolset
path_dir, path_basename = os.path.split(path)
assert not os.path.isabs(path_dir), (
"'%s' can not be absolute path (see crbug.com/462153)." % path_dir
)
if qualified:
path_basename = self.name + "." + path_basename
return os.path.normpath(
os.path.join(obj, self.base_dir, path_dir, path_basename)
)
def WriteCollapsedDependencies(self, name, targets, order_only=None):
"""Given a list of targets, return a path for a single file
representing the result of building all the targets or None.
Uses a stamp file if necessary."""
assert targets == [item for item in targets if item], targets
if len(targets) == 0:
assert not order_only
return None
if len(targets) > 1 or order_only:
stamp = self.GypPathToUniqueOutput(name + ".stamp")
targets = self.ninja.build(stamp, "stamp", targets, order_only=order_only)
self.ninja.newline()
return targets[0]
def _SubninjaNameForArch(self, arch):
output_file_base = os.path.splitext(self.output_file_name)[0]
return f"{output_file_base}.{arch}.ninja"
def WriteSpec(self, spec, config_name, generator_flags):
"""The main entry point for NinjaWriter: write the build rules for a spec.
Returns a Target object, which represents the output paths for this spec.
Returns None if there are no outputs (e.g. a settings-only 'none' type
target)."""
self.config_name = config_name
self.name = spec["target_name"]
self.toolset = spec["toolset"]
config = spec["configurations"][config_name]
self.target = Target(spec["type"])
self.is_standalone_static_library = bool(
spec.get("standalone_static_library", 0)
)
self.target_rpath = generator_flags.get("target_rpath", r"\$$ORIGIN/lib/")
self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec)
self.xcode_settings = self.msvs_settings = None
if self.flavor == "mac":
self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec)
mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None)
if mac_toolchain_dir:
self.xcode_settings.mac_toolchain_dir = mac_toolchain_dir
if self.flavor == "win":
self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, generator_flags)
arch = self.msvs_settings.GetArch(config_name)
self.ninja.variable("arch", self.win_env[arch])
self.ninja.variable("cc", "$cl_" + arch)
self.ninja.variable("cxx", "$cl_" + arch)
self.ninja.variable("cc_host", "$cl_" + arch)
self.ninja.variable("cxx_host", "$cl_" + arch)
self.ninja.variable("asm", "$ml_" + arch)
if self.flavor == "mac":
self.archs = self.xcode_settings.GetActiveArchs(config_name)
if len(self.archs) > 1:
self.arch_subninjas = {
arch: ninja_syntax.Writer(
OpenOutput(
os.path.join(
self.toplevel_build, self._SubninjaNameForArch(arch)
),
"w",
)
)
for arch in self.archs
}
# Compute predepends for all rules.
# actions_depends is the dependencies this target depends on before running
# any of its action/rule/copy steps.
# compile_depends is the dependencies this target depends on before running
# any of its compile steps.
actions_depends = []
compile_depends = []
# TODO(evan): it is rather confusing which things are lists and which
# are strings. Fix these.
if "dependencies" in spec:
for dep in spec["dependencies"]:
if dep in self.target_outputs:
target = self.target_outputs[dep]
actions_depends.append(target.PreActionInput(self.flavor))
compile_depends.append(target.PreCompileInput())
if target.uses_cpp:
self.target.uses_cpp = True
actions_depends = [item for item in actions_depends if item]
compile_depends = [item for item in compile_depends if item]
actions_depends = self.WriteCollapsedDependencies(
"actions_depends", actions_depends
)
compile_depends = self.WriteCollapsedDependencies(
"compile_depends", compile_depends
)
self.target.preaction_stamp = actions_depends
self.target.precompile_stamp = compile_depends
# Write out actions, rules, and copies. These must happen before we
# compile any sources, so compute a list of predependencies for sources
# while we do it.
extra_sources = []
mac_bundle_depends = []
self.target.actions_stamp = self.WriteActionsRulesCopies(
spec, extra_sources, actions_depends, mac_bundle_depends
)
# If we have actions/rules/copies, we depend directly on those, but
# otherwise we depend on dependent target's actions/rules/copies etc.
# We never need to explicitly depend on previous target's link steps,
# because no compile ever depends on them.
compile_depends_stamp = self.target.actions_stamp or compile_depends
# Write out the compilation steps, if any.
link_deps = []
try:
sources = extra_sources + spec.get("sources", [])
except TypeError:
print("extra_sources: ", str(extra_sources))
print('spec.get("sources"): ', str(spec.get("sources")))
raise
if sources:
if self.flavor == "mac" and len(self.archs) > 1:
# Write subninja file containing compile and link commands scoped to
# a single arch if a fat binary is being built.
for arch in self.archs:
self.ninja.subninja(self._SubninjaNameForArch(arch))
pch = None
if self.flavor == "win":
gyp.msvs_emulation.VerifyMissingSources(
sources, self.abs_build_dir, generator_flags, self.GypPathToNinja
)
pch = gyp.msvs_emulation.PrecompiledHeader(
self.msvs_settings,
config_name,
self.GypPathToNinja,
self.GypPathToUniqueOutput,
self.obj_ext,
)
else:
pch = gyp.xcode_emulation.MacPrefixHeader(
self.xcode_settings,
self.GypPathToNinja,
lambda path, lang: self.GypPathToUniqueOutput(path + "-" + lang),
)
link_deps = self.WriteSources(
self.ninja,
config_name,
config,
sources,
compile_depends_stamp,
pch,
spec,
)
# Some actions/rules output 'sources' that are already object files.
obj_outputs = [f for f in sources if f.endswith(self.obj_ext)]
if obj_outputs:
if self.flavor != "mac" or len(self.archs) == 1:
link_deps += [self.GypPathToNinja(o) for o in obj_outputs]
else:
print(
"Warning: Actions/rules writing object files don't work with "
"multiarch targets, dropping. (target %s)" % spec["target_name"]
)
elif self.flavor == "mac" and len(self.archs) > 1:
link_deps = collections.defaultdict(list)
compile_deps = self.target.actions_stamp or actions_depends
if self.flavor == "win" and self.target.type == "static_library":
self.target.component_objs = link_deps
self.target.compile_deps = compile_deps
# Write out a link step, if needed.
output = None
is_empty_bundle = not link_deps and not mac_bundle_depends
if link_deps or self.target.actions_stamp or actions_depends:
output = self.WriteTarget(
spec, config_name, config, link_deps, compile_deps
)
if self.is_mac_bundle:
mac_bundle_depends.append(output)
# Bundle all of the above together, if needed.
if self.is_mac_bundle:
output = self.WriteMacBundle(spec, mac_bundle_depends, is_empty_bundle)
if not output:
return None
assert self.target.FinalOutput(), output
return self.target
def _WinIdlRule(self, source, prebuild, outputs):
"""Handle the implicit VS .idl rule for one source file. Fills |outputs|
with files that are generated."""
outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData(
source, self.config_name
)
outdir = self.GypPathToNinja(outdir)
def fix_path(path, rel=None):
path = os.path.join(outdir, path)
dirname, basename = os.path.split(source)
root, ext = os.path.splitext(basename)
path = self.ExpandRuleVariables(path, root, dirname, source, ext, basename)
if rel:
path = os.path.relpath(path, rel)
return path
vars = [(name, fix_path(value, outdir)) for name, value in vars]
output = [fix_path(p) for p in output]
vars.append(("outdir", outdir))
vars.append(("idlflags", flags))
input = self.GypPathToNinja(source)
self.ninja.build(output, "idl", input, variables=vars, order_only=prebuild)
outputs.extend(output)
def WriteWinIdlFiles(self, spec, prebuild):
"""Writes rules to match MSVS's implicit idl handling."""
assert self.flavor == "win"
if self.msvs_settings.HasExplicitIdlRulesOrActions(spec):
return []
outputs = []
for source in filter(lambda x: x.endswith(".idl"), spec["sources"]):
self._WinIdlRule(source, prebuild, outputs)
return outputs
def WriteActionsRulesCopies(
self, spec, extra_sources, prebuild, mac_bundle_depends
):
"""Write out the Actions, Rules, and Copies steps. Return a path
representing the outputs of these steps."""
outputs = []
if self.is_mac_bundle:
mac_bundle_resources = spec.get("mac_bundle_resources", [])[:]
else:
mac_bundle_resources = []
extra_mac_bundle_resources = []
if "actions" in spec:
outputs += self.WriteActions(
spec["actions"], extra_sources, prebuild, extra_mac_bundle_resources
)
if "rules" in spec:
outputs += self.WriteRules(
spec["rules"],
extra_sources,
prebuild,
mac_bundle_resources,
extra_mac_bundle_resources,
)
if "copies" in spec:
outputs += self.WriteCopies(spec["copies"], prebuild, mac_bundle_depends)
if "sources" in spec and self.flavor == "win":
outputs += self.WriteWinIdlFiles(spec, prebuild)
if self.xcode_settings and self.xcode_settings.IsIosFramework():
self.WriteiOSFrameworkHeaders(spec, outputs, prebuild)
stamp = self.WriteCollapsedDependencies("actions_rules_copies", outputs)
if self.is_mac_bundle:
xcassets = self.WriteMacBundleResources(
extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends
)
partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends)
self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends)
return stamp
def GenerateDescription(self, verb, message, fallback):
"""Generate and return a description of a build step.
|verb| is the short summary, e.g. ACTION or RULE.
|message| is a hand-written description, or None if not available.
|fallback| is the gyp-level name of the step, usable as a fallback.
"""
if self.toolset != "target":
verb += "(%s)" % self.toolset
if message:
return f"{verb} {self.ExpandSpecial(message)}"
else:
return f"{verb} {self.name}: {fallback}"
def WriteActions(
self, actions, extra_sources, prebuild, extra_mac_bundle_resources
):
# Actions cd into the base directory.
env = self.GetToolchainEnv()
all_outputs = []
for action in actions:
# First write out a rule for the action.
name = "{}_{}".format(action["action_name"], self.hash_for_rules)
description = self.GenerateDescription(
"ACTION", action.get("message", None), name
)
win_shell_flags = (
self.msvs_settings.GetRuleShellFlags(action)
if self.flavor == "win"
else None
)
args = action["action"]
depfile = action.get("depfile", None)
if depfile:
depfile = self.ExpandSpecial(depfile, self.base_to_build)
pool = "console" if int(action.get("ninja_use_console", 0)) else None
rule_name, _ = self.WriteNewNinjaRule(
name, args, description, win_shell_flags, env, pool, depfile=depfile
)
inputs = [self.GypPathToNinja(i, env) for i in action["inputs"]]
if int(action.get("process_outputs_as_sources", False)):
extra_sources += action["outputs"]
if int(action.get("process_outputs_as_mac_bundle_resources", False)):
extra_mac_bundle_resources += action["outputs"]
outputs = [self.GypPathToNinja(o, env) for o in action["outputs"]]
# Then write out an edge using the rule.
self.ninja.build(outputs, rule_name, inputs, order_only=prebuild)
all_outputs += outputs
self.ninja.newline()
return all_outputs
def WriteRules(
self,
rules,
extra_sources,
prebuild,
mac_bundle_resources,
extra_mac_bundle_resources,
):
env = self.GetToolchainEnv()
all_outputs = []
for rule in rules:
# Skip a rule with no action and no inputs.
if "action" not in rule and not rule.get("rule_sources", []):
continue
# First write out a rule for the rule action.
name = "{}_{}".format(rule["rule_name"], self.hash_for_rules)
args = rule["action"]
description = self.GenerateDescription(
"RULE",
rule.get("message", None),
("%s " + generator_default_variables["RULE_INPUT_PATH"]) % name,
)
win_shell_flags = (
self.msvs_settings.GetRuleShellFlags(rule)
if self.flavor == "win"
else None
)
pool = "console" if int(rule.get("ninja_use_console", 0)) else None
rule_name, args = self.WriteNewNinjaRule(
name, args, description, win_shell_flags, env, pool
)
# TODO: if the command references the outputs directly, we should
# simplify it to just use $out.
# Rules can potentially make use of some special variables which
# must vary per source file.
# Compute the list of variables we'll need to provide.
special_locals = ("source", "root", "dirname", "ext", "name")
needed_variables = {"source"}
for argument in args:
for var in special_locals:
if "${%s}" % var in argument:
needed_variables.add(var)
needed_variables = sorted(needed_variables)
def cygwin_munge(path):
# pylint: disable=cell-var-from-loop
if win_shell_flags and win_shell_flags.cygwin:
return path.replace("\\", "/")
return path
inputs = [self.GypPathToNinja(i, env) for i in rule.get("inputs", [])]
# If there are n source files matching the rule, and m additional rule
# inputs, then adding 'inputs' to each build edge written below will
# write m * n inputs. Collapsing reduces this to m + n.
sources = rule.get("rule_sources", [])
num_inputs = len(inputs)
if prebuild:
num_inputs += 1
if num_inputs > 2 and len(sources) > 2:
inputs = [
self.WriteCollapsedDependencies(
rule["rule_name"], inputs, order_only=prebuild
)
]
prebuild = []
# For each source file, write an edge that generates all the outputs.
for source in sources:
source = os.path.normpath(source)
dirname, basename = os.path.split(source)
root, ext = os.path.splitext(basename)
# Gather the list of inputs and outputs, expanding $vars if possible.
outputs = [
self.ExpandRuleVariables(o, root, dirname, source, ext, basename)
for o in rule["outputs"]
]
if int(rule.get("process_outputs_as_sources", False)):
extra_sources += outputs
was_mac_bundle_resource = source in mac_bundle_resources
if was_mac_bundle_resource or int(
rule.get("process_outputs_as_mac_bundle_resources", False)
):
extra_mac_bundle_resources += outputs
# Note: This is n_resources * n_outputs_in_rule.
# Put to-be-removed items in a set and
# remove them all in a single pass
# if this becomes a performance issue.
if was_mac_bundle_resource:
mac_bundle_resources.remove(source)
extra_bindings = []
for var in needed_variables:
if var == "root":
extra_bindings.append(("root", cygwin_munge(root)))
elif var == "dirname":
# '$dirname' is a parameter to the rule action, which means
# it shouldn't be converted to a Ninja path. But we don't
# want $!PRODUCT_DIR in there either.
dirname_expanded = self.ExpandSpecial(
dirname, self.base_to_build
)
extra_bindings.append(
("dirname", cygwin_munge(dirname_expanded))
)
elif var == "source":
# '$source' is a parameter to the rule action, which means
# it shouldn't be converted to a Ninja path. But we don't
# want $!PRODUCT_DIR in there either.
source_expanded = self.ExpandSpecial(source, self.base_to_build)
extra_bindings.append(("source", cygwin_munge(source_expanded)))
elif var == "ext":
extra_bindings.append(("ext", ext))
elif var == "name":
extra_bindings.append(("name", cygwin_munge(basename)))
else:
assert var is None, repr(var)
outputs = [self.GypPathToNinja(o, env) for o in outputs]
if self.flavor == "win":
# WriteNewNinjaRule uses unique_name to create a rsp file on win.
extra_bindings.append(
("unique_name", hashlib.md5(outputs[0]).hexdigest())
)
self.ninja.build(
outputs,
rule_name,
self.GypPathToNinja(source),
implicit=inputs,
order_only=prebuild,
variables=extra_bindings,
)
all_outputs.extend(outputs)
return all_outputs
def WriteCopies(self, copies, prebuild, mac_bundle_depends):
outputs = []
if self.xcode_settings:
extra_env = self.xcode_settings.GetPerTargetSettings()
env = self.GetToolchainEnv(additional_settings=extra_env)
else:
env = self.GetToolchainEnv()
for to_copy in copies:
for path in to_copy["files"]:
# Normalize the path so trailing slashes don't confuse us.
path = os.path.normpath(path)
basename = os.path.split(path)[1]
src = self.GypPathToNinja(path, env)
dst = self.GypPathToNinja(
os.path.join(to_copy["destination"], basename), env
)
outputs += self.ninja.build(dst, "copy", src, order_only=prebuild)
if self.is_mac_bundle:
# gyp has mac_bundle_resources to copy things into a bundle's
# Resources folder, but there's no built-in way to copy files
# to other places in the bundle.
# Hence, some targets use copies for this.
# Check if this file is copied into the current bundle,
# and if so add it to the bundle depends so
# that dependent targets get rebuilt if the copy input changes.
if dst.startswith(
self.xcode_settings.GetBundleContentsFolderPath()
):
mac_bundle_depends.append(dst)
return outputs
def WriteiOSFrameworkHeaders(self, spec, outputs, prebuild):
"""Prebuild steps to generate hmap files and copy headers to destination."""
framework = self.ComputeMacBundleOutput()
all_sources = spec["sources"]
copy_headers = spec["mac_framework_headers"]
output = self.GypPathToUniqueOutput("headers.hmap")
self.xcode_settings.header_map_path = output
all_headers = map(
self.GypPathToNinja, filter(lambda x: x.endswith(".h"), all_sources)
)
variables = [
("framework", framework),
("copy_headers", map(self.GypPathToNinja, copy_headers)),
]
outputs.extend(
self.ninja.build(
output,
"compile_ios_framework_headers",
all_headers,
variables=variables,
order_only=prebuild,
)
)
def WriteMacBundleResources(self, resources, bundle_depends):
"""Writes ninja edges for 'mac_bundle_resources'."""
xcassets = []
extra_env = self.xcode_settings.GetPerTargetSettings()
env = self.GetSortedXcodeEnv(additional_settings=extra_env)
env = self.ComputeExportEnvString(env)
isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)
for output, res in gyp.xcode_emulation.GetMacBundleResources(
generator_default_variables["PRODUCT_DIR"],
self.xcode_settings,
map(self.GypPathToNinja, resources),
):
output = self.ExpandSpecial(output)
if os.path.splitext(output)[-1] != ".xcassets":
self.ninja.build(
output,
"mac_tool",
res,
variables=[
("mactool_cmd", "copy-bundle-resource"),
("env", env),
("binary", isBinary),
],
)
bundle_depends.append(output)
else:
xcassets.append(res)
return xcassets
def WriteMacXCassets(self, xcassets, bundle_depends):
"""Writes ninja edges for 'mac_bundle_resources' .xcassets files.
This add an invocation of 'actool' via the 'mac_tool.py' helper script.
It assumes that the assets catalogs define at least one imageset and
thus an Assets.car file will be generated in the application resources
directory. If this is not the case, then the build will probably be done
at each invocation of ninja."""
if not xcassets:
return
extra_arguments = {}
settings_to_arg = {
"XCASSETS_APP_ICON": "app-icon",
"XCASSETS_LAUNCH_IMAGE": "launch-image",
}
settings = self.xcode_settings.xcode_settings[self.config_name]
for settings_key, arg_name in settings_to_arg.items():
value = settings.get(settings_key)
if value:
extra_arguments[arg_name] = value
partial_info_plist = None
if extra_arguments:
partial_info_plist = self.GypPathToUniqueOutput(
"assetcatalog_generated_info.plist"
)
extra_arguments["output-partial-info-plist"] = partial_info_plist
outputs = []
outputs.append(
os.path.join(self.xcode_settings.GetBundleResourceFolder(), "Assets.car")
)
if partial_info_plist:
outputs.append(partial_info_plist)
keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor)
extra_env = self.xcode_settings.GetPerTargetSettings()
env = self.GetSortedXcodeEnv(additional_settings=extra_env)
env = self.ComputeExportEnvString(env)
bundle_depends.extend(
self.ninja.build(
outputs,
"compile_xcassets",
xcassets,
variables=[("env", env), ("keys", keys)],
)
)
return partial_info_plist
def WriteMacInfoPlist(self, partial_info_plist, bundle_depends):
"""Write build rules for bundle Info.plist files."""
info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist(
generator_default_variables["PRODUCT_DIR"],
self.xcode_settings,
self.GypPathToNinja,
)
if not info_plist:
return
out = self.ExpandSpecial(out)
if defines:
# Create an intermediate file to store preprocessed results.
intermediate_plist = self.GypPathToUniqueOutput(
os.path.basename(info_plist)
)
defines = " ".join([Define(d, self.flavor) for d in defines])
info_plist = self.ninja.build(
intermediate_plist,
"preprocess_infoplist",
info_plist,
variables=[("defines", defines)],
)
env = self.GetSortedXcodeEnv(additional_settings=extra_env)
env = self.ComputeExportEnvString(env)
if partial_info_plist:
intermediate_plist = self.GypPathToUniqueOutput("merged_info.plist")
info_plist = self.ninja.build(
intermediate_plist, "merge_infoplist", [partial_info_plist, info_plist]
)