Skip to content

Commit f41ec09

Browse files
authored
Merge pull request hedronvision#156 from kon72/support_bazel_5
Support Bazel 5
2 parents 5f9f8ba + fb91692 commit f41ec09

File tree

2 files changed

+60
-3
lines changed

2 files changed

+60
-3
lines changed

refresh.template.py

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,35 @@ def _print_header_finding_warning_once():
8989
_print_header_finding_warning_once.has_logged = False
9090

9191

92+
@functools.lru_cache
93+
def _get_bazel_version():
94+
"""Gets the Bazel version as a tuple of (major, minor, patch).
95+
96+
The rolling release and the release candidate are treated as the LTS release.
97+
E.g. both 7.0.0-pre.XXXXXXXX.X and 7.0.0rc1 are treated as 7.0.0.
98+
If the version can't be determined, returns (0, 0, 0).
99+
"""
100+
bazel_version_process = subprocess.run(
101+
['bazel', 'version'],
102+
capture_output=True,
103+
encoding=locale.getpreferredencoding(),
104+
check=True, # Should always succeed.
105+
)
106+
107+
version = ''
108+
for line in bazel_version_process.stdout.splitlines():
109+
line = line.strip()
110+
if line.startswith('Build label: '):
111+
version = line[len('Build label: '):]
112+
113+
match = re.search(r'^(\d+)\.(\d+)\.(\d+)', version)
114+
if not match:
115+
log_warning(f">>> Failed to get Bazel version.\nPlease file an issue with the following log:\n", bazel_version_process.stdout)
116+
return (0, 0, 0)
117+
118+
return tuple(int(match.group(i)) for i in range(1, 4))
119+
120+
92121
@functools.lru_cache
93122
def _get_bazel_cached_action_keys():
94123
"""Gets the set of actionKeys cached in bazel-out."""
@@ -727,6 +756,19 @@ def _apple_platform_patch(compile_args: list[str]):
727756
return compile_args
728757

729758

759+
def _get_sysroot(args: typing.List[str]):
760+
"""Get path to sysroot from command line arguments."""
761+
for idx, arg in enumerate(args):
762+
if arg == '--sysroot' or arg == '-isysroot':
763+
if idx + 1 < len(args):
764+
return pathlib.PurePath(args[idx + 1])
765+
elif arg.startswith('--sysroot='):
766+
return pathlib.PurePath(arg[len('--sysroot='):])
767+
elif arg.startswith('-isysroot'):
768+
return pathlib.PurePath(arg[len('-isysroot'):])
769+
return None
770+
771+
730772
def _emscripten_platform_patch(compile_action):
731773
"""De-Bazel the command into something clangd can parse.
732774
@@ -737,13 +779,24 @@ def _emscripten_platform_patch(compile_action):
737779
return compile_action.arguments
738780

739781
workspace_absolute = pathlib.PurePath(os.environ["BUILD_WORKSPACE_DIRECTORY"])
782+
sysroot = _get_sysroot(compile_action.arguments)
783+
assert sysroot, f'Emscripten sysroot not detected in CMD: {compile_action.arguments}'
784+
785+
def get_workspace_root(path_from_execroot: pathlib.PurePath):
786+
if path_from_execroot.parts[0] != 'external':
787+
return pathlib.PurePath('.')
788+
return pathlib.PurePath('external') / path_from_execroot.parts[1]
740789

741790
environment = compile_action.environmentVariables.copy()
742791
environment['EXT_BUILD_ROOT'] = str(workspace_absolute)
743792
environment['EMCC_SKIP_SANITY_CHECK'] = '1'
744793
environment['EM_COMPILER_WRAPPER'] = str(pathlib.PurePath({print_args_executable}))
745794
if 'PATH' not in environment:
746795
environment['PATH'] = os.environ['PATH']
796+
if 'EM_BIN_PATH' not in environment:
797+
environment['EM_BIN_PATH'] = str(get_workspace_root(sysroot))
798+
if 'EM_CONFIG_PATH' not in environment:
799+
environment['EM_CONFIG_PATH'] = str(get_workspace_root(emcc_driver) / 'emscripten_toolchain' / 'emscripten_config')
747800

748801
# We run the emcc process with the environment variable EM_COMPILER_WRAPPER to intercept the command line arguments passed to `clang`.
749802
emcc_process = subprocess.run(
@@ -1143,13 +1196,17 @@ def _get_commands(target: str, flags: str):
11431196
# That's all well and good, but param files would prevent us from seeing compile actions before the param files had been generated by compilation.
11441197
# Since clangd has no such length limit, we'll disable param files for our aquery run.
11451198
'--features=-compiler_param_file',
1146-
'--host_features=-compiler_param_file',
11471199
# Disable layering_check during, because it causes large-scale dependence on generated module map files that prevent header extraction before their generation
11481200
# For more context, see https://github.com/hedronvision/bazel-compile-commands-extractor/issues/83
11491201
# If https://github.com/clangd/clangd/issues/123 is resolved and we're not doing header extraction, we could try removing this, checking that there aren't erroneous red squigglies squigglies before the module maps are generated.
11501202
# If Bazel starts supporting modules (https://github.com/bazelbuild/bazel/issues/4005), we'll probably need to make changes that subsume this.
11511203
'--features=-layering_check',
1152-
] + additional_flags
1204+
]
1205+
1206+
if _get_bazel_version() >= (6, 1, 0):
1207+
aquery_args += ['--host_features=-compiler_param_file']
1208+
1209+
aquery_args += additional_flags
11531210

11541211
aquery_process = subprocess.run(
11551212
aquery_args,

refresh_compile_commands.bzl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def refresh_compile_commands(
8282

8383
# Make any package-relative labels absolute
8484
targets = {
85-
target if target.startswith("/") or target.startswith("@") else "@{}//{}:{}".format(native.repository_name(), native.package_name(), target.removeprefix(":")): flags for target, flags in targets.items()
85+
target if target.startswith("/") or target.startswith("@") else "{}//{}:{}".format(native.repository_name(), native.package_name(), target.removeprefix(":")): flags for target, flags in targets.items()
8686
}
8787

8888
# Generate the core, runnable python script from refresh.template.py

0 commit comments

Comments
 (0)