Entry point's crate directory

I've found out I can do one of the following to get the directory of the entry point crate being compiled:

// Option 1
let project_directory = std::env::current_dir().unwrap();

// Option 2
let project_directory = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());

But neither are perfect. I want to be able to get the entry point's directory (not the workspace unless it's a workspace+package) from a third-party crate, and I want to support Cargo -p... --manifest-path...

A library shouldn't depend on the entry point — doing so would potentially make it unusable by one of its dependents that is not the entry point. Also, more than one binary crate in a workspace might be built simultaneously, so there is no unique such crate.

1 Like

My SDK though will only try to build one crate per time through its build-related subcommands.

It ends up I'll need to rely on the entry point for my specific case, which is a framework making some stuff under the hood.

In that case, don't attempt to obtain the information you need through Cargo; have your “SDK” build tool set an environment variable specifically for this purpose.

If you’re using it from a build script, don’t forget to emit cargo::rerun-if-env-changed to register your dependency on the value of that variable.

1 Like

That rerun indicator isn't needed as long as I use env! or option_env! in the build script, right?

That’s true, but your original code sample used std::env::var(). Also, if you can use std::env::var() instead of env!(), you should, because using env!() will cause the build script itself to be rebuilt when the value changes, which is unnecessary.

1 Like

Thanks! It's quite cheap though to run my build script. It'll only copy (a possibly large amount of) files when building for packaging (not when running an app in development phase which under the hood uses cargo run).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.