Skip to content

Commit

Permalink
fix: support relative TARGET_DIR in near-test-contracts
Browse files Browse the repository at this point in the history
near-test-contracts builds some wasm contracts for use in testing. It
does so by recursively invoking `cargo` from `build.rs`. Before this
commit, we tried to re-use parent's `CARGO_TARGET_DIR` to figure out
where we should put the data. That was rather hacky, as cargo doesn't
expose that information to the build scripts in a reliable way:

rust-lang/cargo#9661 (comment)

Naturally, our hacks broken when when the `CARGO_TARGET_DIR` was set to
a relative path, because build.rs doesn't know where workspace root
lives.

The fix is to use `OUT_DIR` rather than `CARGO_TARGET_DIR`, which I
think is the supported way to this in the first place. Eg, the `cc`
crate uses `OUT_DIR` to store intermediate `.o` files, which I think
matches our use case pretty closely.
  • Loading branch information
matklad committed Jan 25, 2022
1 parent eff8a83 commit 59c7c06
Showing 1 changed file with 7 additions and 16 deletions.
23 changes: 7 additions & 16 deletions runtime/near-test-contracts/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,13 @@ fn try_main() -> Result<(), Error> {
}

fn build_contract(dir: &str, args: &[&str], output: &str) -> Result<(), Error> {
let mut cmd = cargo_build_cmd();
let target_dir = out_dir();

let mut cmd = cargo_build_cmd(&target_dir);
cmd.args(args);
cmd.current_dir(dir);
check_status(cmd)?;

let target_dir = shared_target_dir().unwrap_or_else(|| format!("./{}/target", dir).into());
let src =
target_dir.join(format!("wasm32-unknown-unknown/release/{}.wasm", dir.replace('-', "_")));
fs::copy(&src, format!("./res/{}.wasm", output))
Expand All @@ -44,14 +45,11 @@ fn build_contract(dir: &str, args: &[&str], output: &str) -> Result<(), Error> {
Ok(())
}

fn cargo_build_cmd() -> Command {
fn cargo_build_cmd(target_dir: &Path) -> Command {
let mut res = Command::new("cargo");
res.env("RUSTFLAGS", "-C link-arg=-s");
res.env_remove("CARGO_ENCODED_RUSTFLAGS");
if let Some(target_dir) = shared_target_dir() {
res.env("CARGO_TARGET_DIR", target_dir);
}

res.env("CARGO_TARGET_DIR", target_dir);
res.args(&["build", "--target=wasm32-unknown-unknown", "--release"]);
res
}
Expand All @@ -66,13 +64,6 @@ fn check_status(mut cmd: Command) -> Result<(), Error> {
Ok(())
}

fn shared_target_dir() -> Option<PathBuf> {
let target_dir = env::var("CARGO_TARGET_DIR").ok()?;
// Avoid sharing the same target directory with the patent Cargo
// invocation, to avoid deadlock on the target dir.
//
// That is, this logic is needed for the case like the following:
//
// CARGO_TARGET_DIR=/tmp cargo build -p near-test-contracts --release
Some(Path::new(&target_dir).join("near-test-contracts"))
fn out_dir() -> PathBuf {
env::var("OUT_DIR").unwrap().into()
}

0 comments on commit 59c7c06

Please sign in to comment.