From b56cbaa8465e74127f1ea216f813cd377295ad81 Mon Sep 17 00:00:00 2001 From: David Zbarsky Date: Wed, 28 Jan 2026 12:10:02 -0500 Subject: [PATCH] Add runfiles crate --- rust/runfiles/Cargo.lock | 7 +++++++ rust/runfiles/Cargo.toml | 10 ++++++++++ rust/runfiles/runfiles.rs | 19 ++++++++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 rust/runfiles/Cargo.lock create mode 100644 rust/runfiles/Cargo.toml diff --git a/rust/runfiles/Cargo.lock b/rust/runfiles/Cargo.lock new file mode 100644 index 0000000000..3db66fb683 --- /dev/null +++ b/rust/runfiles/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "runfiles" +version = "0.1.0" diff --git a/rust/runfiles/Cargo.toml b/rust/runfiles/Cargo.toml new file mode 100644 index 0000000000..dde46286ab --- /dev/null +++ b/rust/runfiles/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "runfiles" +version = "0.1.0" +edition = "2018" +license = "Apache-2.0" +description = "Runfiles lookup library for Bazel-built Rust binaries and tests." +repository = "https://github.com/bazelbuild/rules_rust" + +[lib] +path = "runfiles.rs" diff --git a/rust/runfiles/runfiles.rs b/rust/runfiles/runfiles.rs index c2c4efb581..3dbcd79774 100644 --- a/rust/runfiles/runfiles.rs +++ b/rust/runfiles/runfiles.rs @@ -44,10 +44,27 @@ const TEST_SRCDIR_ENV_VAR: &str = "TEST_SRCDIR"; #[macro_export] macro_rules! rlocation { ($r:expr, $path:expr) => { - $r.rlocation_from($path, env!("REPOSITORY_NAME")) + { + let repo = option_env!("REPOSITORY_NAME"); + $r.rlocation_from($path, $crate::repository_name(repo)) + } }; } +/// Return the build-time repository name. +/// +/// Bazel sets the `REPOSITORY_NAME` environment variable while compiling this crate. When +/// building via Cargo (e.g., from a git dependency), callers must either set the same +/// environment variable at compile time or call `rlocation_from` directly with an explicit +/// `source_repo`. This function panics if the value is not available. +pub fn repository_name(repo: Option<&'static str>) -> &'static str { + repo.unwrap_or_else(|| { + panic!( + "REPOSITORY_NAME was not set at compile time; set it or call rlocation_from directly" + ) + }) +} + /// The error type for [Runfiles] construction. #[derive(Debug)] pub enum RunfilesError {