Debian Codegraph @

gn/bazel_build.py

raw
1 #!/usr/bin/env python3
2 #
3 # Copyright 2023 Google LLC
4 #
5 # Use of this source code is governed by a BSD-style license that can be
6 # found in the LICENSE file.
7 #
8 # This script runs bazel build [target] [additional_arg] [additional_arg]
9 # and then copies each of the specified outputs from the bazel-bin output
10 # folder under the current working directory. This allows GN to shell out
11 # to Bazel to generate or compile files, but still have them show up where
12 # GN expects (in the output folder).
13 #
14 # The first argument passed in to this script is the Bazel target.
15 # subsequent arguments are treated either as Bazel flags (if they start with
16 # --) or output files to copy (if they do not).
17 #
18 # Output files may contain an equals sign (=), which means the first part is
19 # the Bazel file to copy and the second part is where to copy it. If omitted,
20 # the file will go immediately under the GN output directory.
21
22 import hashlib
23 import os
24 import shutil
25 import subprocess
26 import sys
27
28 # Separate targets (starting with // or @) from outputs and flags
29 targets = []
30 outputs = {}
31 bazel_args = []
32 for arg in sys.argv[1:]:
33 if arg.startswith("//") or arg.startswith("@"):
34 targets.append(arg)
35 elif arg.startswith("--"):
36 bazel_args.append(arg)
37 else:
38 if "=" in arg:
39 # "../../bazel-bin/src/ports/ffi.h=src/core/ffi.h" means to
40 # copy ../../bazel-bin/src/ports/ffi.h to
41 # $GN_OUTPUT/src/core/ffi.h
42 bazel_file, output_path = arg.split("=")
43 outputs[bazel_file] = output_path
44 else:
45 # "../../bazel-bin/src/ports/libstuff.a" means to copy
46 # ../../bazel-bin/src/ports/libstuff.a to
47 # $GN_OUTPUT/libstuff.a
48 outputs[arg] = os.path.basename(arg)
49
50 print("Invoking bazelisk from ", os.getcwd())
51 # Build all targets in a single invocation
52 subprocess.run(["bazelisk", "build"] + targets + bazel_args, check=True)
53
54 for bazel_file, output_path in outputs.items():
55 # GN expects files to be created underneath the output directory from which
56 # this script is invoked.
57 expected_output = os.path.join(os.getcwd(), output_path)
58 if not os.path.exists(expected_output):
59 shutil.copyfile(bazel_file, expected_output)
60 os.chmod(expected_output, 0o755)
61 else:
62 # GN uses timestamps to determine if it should re-build a file. If the
63 # two files match (via hash) we should not re-copy the output, which would
64 # re-trigger subsequent rebuilds.
65 created_hash = hashlib.sha256(open(bazel_file, 'rb').read()).hexdigest()
66 existing_hash = hashlib.sha256(open(expected_output, 'rb').read()).hexdigest()
67 if created_hash != existing_hash:
68 os.remove(expected_output)
69 shutil.copyfile(bazel_file, expected_output)
70 os.chmod(expected_output, 0o755)