'How to use local project files in build.rs script?
How do I use local files without including their absolute paths in build.rs
? I have, for example let proto_file_glob_paths: Paths = glob("../proto/**/*.proto").unwrap();
.
I am using relative paths in my build.rs
, because I don't want to hardcode the absolute path of files, so that it works on other developer machines. The build works fine with cargo build
and cargo run
, but not cargo publish
. This is because the working directory/path is different when cargo publish
is run.
In cargo build
, the env::current_dir()
is:
project_name/target/debug/build/project_name-70e21ac88134b5a1/build-script-build
In cargo publish
, the env::current_dir()
is:
project_name/target/package/project_name-x.y.z/target/debug/build/project_name-xxxxxxx/build-script-build
I don't know of any environment variables I can use to access the directory of build.rs
, or src/
, so that I can create a relative/absolute path dynamically. Even CARGO_MANIFEST_DIR
is different for build
and publish
.
Project specifics: I've got other lines of code to generate the rust code using other packages, and this works fine in cargo build
and cargo run
.
Solution 1:[1]
After some very helpful prompting from @Cerberus and then from @ColonelThirtyTwo, I just:
- copied the local files into the crate root. I wrote a script to do this before running
cargo build
. Of course, I needed to update the relative path to useproto/
instead of../proto/
. - added the
proto
directory to thegitignore
file - and added the
proto
directory topackage.include
inCargo.toml
because it would not be included as it is gitignored:
[package]
...
include = ["**/*.rs", "Cargo.toml", "Cargo.lock", "config.json", "proto"]
My mistakes were that:
- I assumed
../proto
should work, but as Cerberus explained, it won't. Since the files would be missing for the users of the crate. - I didn't add the
proto
file toinclude
inCargo.toml
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |