2

As the title suggests, I'm trying to retrieve the target folder to hold some intermediate compilation products. I need the actual target folder as I would like to cache some values between compilations to speed them up significantly (otherwise I could just use a temporary directory).

My current approach is to parse the arguments of the rustc invocation (through std::env::args()) and find the --out-dir, the code looks something like this:

// First we get the arguments for the rustc invocation
let mut args = std::env::args();

// Then we loop through them all, and find the value of "out-dir"
let mut out_dir = None;
while let Some(arg) = args.next() {
    if arg == "--out-dir" {
        out_dir = args.next();
    }
}

// Finally we clean out_dir by removing all trailing directories, until it ends with target 
let mut out_dir = PathBuf::from(out_dir.expect("Failed to find out_dir"));
while !out_dir.ends_with("target") {
    if !out_dir.pop() {
        // We ran out of directories...
        panic!("Failed to find out_dir");
    }
}

out_dir

Normally I would use something like an environment variable (think of OUT_DIR), but I couldn't find anything that could help me.

So is there a proper way of doing this? Or should I file an issue to the rust dev team?

Davide Mor
  • 83
  • 7
  • [Cargo sets the environment variable `OUT_DIR` when running build scripts](https://doc.rust-lang.org/cargo/reference/environment-variables.html). I don't know if it is also set when running the compiler though… – Jmb Feb 18 '20 at 07:50

1 Answers1

1

Looking at OUT_DIR is the right way to go and I'm puzzled that it isn't always set. If you have control over the crates that use your macro, you can add a (trivial) build script, which leads to cargo setting the OUT_DIR variable.

I must admit that this is a bit hacky. I've created a feature request for cargo to always set OUT_DIR, which would make this question trivial.

Janonard
  • 45
  • 4