Skip to content

Commit 6766c24

Browse files
authored
Correct CARGO_MANIFEST_DIR values for Bazel <3.7.0 (#469)
Bazel 3.7.0 introduced a change (301b96b223b0c0) in the way it reports file paths for external packages. This ensures that rules_rust sets the right value for CARGO_MANIFEST_DIR both for Bazel < 3.7.0 and >= 3.7.0. Note that if this changed once, it might change again, so the right thing to do is to use a bazel API to do that work once it's available.
1 parent 224fe6a commit 6766c24

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

rust/private/rustc.bzl

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,21 @@ def collect_inputs(
386386
)
387387
return _process_build_scripts(ctx, file, crate_info, build_info, dep_info, compile_inputs)
388388

389+
def _exec_root_relative_path(ctx, filepath):
390+
# Bazel 3.7.0 (commit 301b96b223b0c0) changed how file paths are returned for external packages.
391+
# TODO: use a proper Bazel API to determine exec-root-relative paths.
392+
if len(ctx.label.workspace_root) > 0 and \
393+
(len(BAZEL_VERSION) == 0 or versions.is_at_least("3.7.0", BAZEL_VERSION)):
394+
workspace_root_items = ctx.label.workspace_root.split("/")
395+
if (len(workspace_root_items) >= 2 and
396+
workspace_root_items[0] == "external" and
397+
workspace_root_items[-1] == filepath.split("/")[0]):
398+
workspace_root_items = workspace_root_items[:-1]
399+
400+
return "/".join(workspace_root_items + filepath.split("/"))
401+
else:
402+
return filepath
403+
389404
def construct_arguments(
390405
ctx,
391406
file,
@@ -452,16 +467,11 @@ def construct_arguments(
452467
# and use `${pwd}` which resolves the `exec_root` at action execution time.
453468
#
454469
# Unfortunately, ctx.build_file_path isn't relative to the exec_root for external repositories in
455-
# which case we use ctx.label.workspace_root to complete the path.
470+
# which case we use ctx.label.workspace_root to complete the path in `_exec_root_relative_path()`.
456471
args.add("--subst", "pwd=${pwd}")
457472

458-
workspace_root_items = ctx.label.workspace_root.split("/")
459-
if (len(workspace_root_items) >= 2 and
460-
workspace_root_items[0] == "external" and
461-
workspace_root_items[-1] == ctx.build_file_path.split("/")[0]):
462-
workspace_root_items = workspace_root_items[:-1]
463-
464-
env["CARGO_MANIFEST_DIR"] = "${pwd}/" + "/".join(workspace_root_items + ctx.build_file_path.split("/")[:-1])
473+
relative_build_file_path = _exec_root_relative_path(ctx, ctx.build_file_path)
474+
env["CARGO_MANIFEST_DIR"] = "${pwd}/" + relative_build_file_path[:relative_build_file_path.rfind("/")]
465475

466476
if out_dir != None:
467477
env["OUT_DIR"] = "${pwd}/" + out_dir

0 commit comments

Comments
 (0)