From d5a9d8c63faafcaf8639298c6ea379bae45e9a24 Mon Sep 17 00:00:00 2001 From: UebelAndre Date: Thu, 12 Aug 2021 10:09:45 -0700 Subject: [PATCH] Updated `//tools/rustfmt` to dynamically work within `rules_rust` itself (#883) --- tools/rustfmt/BUILD.bazel | 9 ++++++++- tools/rustfmt/rustfmt_utils.bzl | 18 ++++++++++++++++++ tools/rustfmt/srcs/main.rs | 9 ++++++--- 3 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 tools/rustfmt/rustfmt_utils.bzl diff --git a/tools/rustfmt/BUILD.bazel b/tools/rustfmt/BUILD.bazel index 93abad4398..135ec025d9 100644 --- a/tools/rustfmt/BUILD.bazel +++ b/tools/rustfmt/BUILD.bazel @@ -1,8 +1,12 @@ load("//rust:defs.bzl", "rust_binary", "rust_clippy", "rust_library") +load(":rustfmt_utils.bzl", "aspect_repository") package(default_visibility = ["//visibility:public"]) -exports_files(["rustfmt.toml"]) +exports_files([ + "rustfmt.toml", + "rustfmt_utils.bzl", +]) rust_library( name = "rustfmt_lib", @@ -30,6 +34,9 @@ rust_binary( "//:rustfmt.toml", ], edition = "2018", + rustc_env = { + "ASPECT_REPOSITORY": aspect_repository(), + }, deps = [ ":rustfmt_lib", "//util/label", diff --git a/tools/rustfmt/rustfmt_utils.bzl b/tools/rustfmt/rustfmt_utils.bzl new file mode 100644 index 0000000000..b1fb391058 --- /dev/null +++ b/tools/rustfmt/rustfmt_utils.bzl @@ -0,0 +1,18 @@ +"""A helper module for the `@rules_rust//tools/rustfmt` package""" + +def aspect_repository(): + """Determines the repository name to use for the `rustfmt_manifest` aspect in `rustfmt` binaries. + + The `//tools/rustfmt` target has a hard coded `--aspects` command built into it. + This function is designed to allow for this aspect to be updated to work within + the `rules_rust` repository itself since aspects do not work if the repository name + is explicitly set. + + https://github.com/bazelbuild/rules_rust/issues/749 + + Returns: + str: The string to use for the `rustfmt_aspect` repository + """ + if native.repository_name() == "@": + return "" + return native.repository_name() diff --git a/tools/rustfmt/srcs/main.rs b/tools/rustfmt/srcs/main.rs index f1d95c65b8..eb6d0b13f8 100644 --- a/tools/rustfmt/srcs/main.rs +++ b/tools/rustfmt/srcs/main.rs @@ -75,9 +75,12 @@ fn query_rustfmt_targets(options: &Config) -> Vec { /// arguments to use when formatting the sources of those targets. fn generate_rustfmt_target_manifests(options: &Config, targets: &[String]) { let build_args = vec![ - "build", - "--aspects=@rules_rust//rust:defs.bzl%rustfmt_aspect", - "--output_groups=rustfmt_manifest", + "build".to_owned(), + format!( + "--aspects={}//rust:defs.bzl%rustfmt_aspect", + env!("ASPECT_REPOSITORY") + ), + "--output_groups=rustfmt_manifest".to_owned(), ]; let child = Command::new(&options.bazel)