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.
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.
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.
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).