diff --git a/test/test_env/BUILD b/test/test_env/BUILD index 5660f7b6a3..ba7ba26075 100644 --- a/test/test_env/BUILD +++ b/test/test_env/BUILD @@ -10,13 +10,22 @@ rust_binary( edition = "2018", ) +filegroup( + name = "hello_world_main", + srcs = ["src/main.rs"], +) + rust_test( name = "test", srcs = ["tests/run.rs"], - data = [":hello-world"], + data = [ + ":hello-world", + ":hello_world_main", + ], edition = "2018", env = { "FERRIS_SAYS": "Hello fellow Rustaceans!", - "HELLO_WORLD_BIN": "$(rootpath :hello-world)", + "HELLO_WORLD_BIN_ROOTPATH": "$(rootpath :hello-world)", + "HELLO_WORLD_SRC_EXECPATH": "$(execpath :hello_world_main)", }, ) diff --git a/test/test_env/tests/run.rs b/test/test_env/tests/run.rs index 9c1760e0c8..4353b728bd 100644 --- a/test/test_env/tests/run.rs +++ b/test/test_env/tests/run.rs @@ -6,5 +6,18 @@ fn run() { // Test the `env` attribute of `rust_test` at run time assert_eq!(std::env::var("FERRIS_SAYS").unwrap(), "Hello fellow Rustaceans!"); - assert_eq!(std::env::var("HELLO_WORLD_BIN").unwrap(), "test/test_env/hello-world"); + + // Test the behavior of `rootpath` and that a binary can be found relative to current_dir + let hello_world_bin = std::path::PathBuf::from(std::env::var_os("HELLO_WORLD_BIN_ROOTPATH").unwrap()); + assert_eq!( + hello_world_bin.as_path(), + std::path::Path::new("test/test_env/hello-world"), + ); + assert!(!hello_world_bin.is_absolute()); + assert!(hello_world_bin.exists()); + + // Ensure `execpath` expanded variables map to real files and have absolute paths + let hello_world_src = std::path::PathBuf::from(std::env::var("HELLO_WORLD_SRC_EXECPATH").unwrap()); + assert!(hello_world_src.is_absolute()); + assert!(hello_world_src.exists()); } diff --git a/util/launcher/launcher_main.rs b/util/launcher/launcher_main.rs index 168453a016..0fe27a47f1 100644 --- a/util/launcher/launcher_main.rs +++ b/util/launcher/launcher_main.rs @@ -21,6 +21,11 @@ fn environ() -> BTreeMap { let env_path = std::env::args().nth(0).expect("arg 0 was not set") + LAUNCHFILES_ENV_PATH; let file = File::open(env_path).expect("Failed to load the environment file"); + // Variables will have the `${pwd}` variable replaced which is rendered by + // `@rules_rust//rust/private:util.bzl::expand_locations` + let pwd = std::env::current_dir().expect("Failed to get current working directory"); + let pwd_str = pwd.to_string_lossy(); + // Find all environment variables by reading pairs of lines as key/value pairs for line in BufReader::new(file).lines() { if key.is_none() { @@ -29,8 +34,8 @@ fn environ() -> BTreeMap { } environ.insert( - key.expect("Key is not set"), - line.expect("Failed to read line"), + key.expect("Key is not set"), + line.expect("Failed to read line").replace("${pwd}", &pwd_str), ); key = None;