Get config file from a dependent crate

Let say there's a crate called foo-rs, and there's a config file called foo_config.xml in that crate, foo-rs use that XML to generate codes in build.rs.

My project bar-rs depends on foo-rs, and I want to generate extra codes from foo_config.xml, too. But I didn't know how to get the path of this file.

Is there anyway to do this?

Yes. foo-rs must add links to Cargo.toml, print cargo:config_file_path=… in their build.rs (with absolute/canonicalized path), and then your build.rs will have DEP_{name from links}_CARGO_CONFIG_FILE_PATH env variable to use.

2 Likes

What if I can't modify foo-rs? Is there some function like get_crate_path("foo-rs") -> Path I can call in build.rs?

There is no way without modifying the dependency. You can fork it, or use [patch.crates-io] in your workspace.

2 Likes

Thank you for pointing this out, I just learned something new!

As mentioned above in the output format, each build script can generate an arbitrary set of metadata in the form of key-value pairs. This metadata is passed to the build scripts of dependent packages. For example, if the package bar depends on foo , then if foo generates key=value as part of its build script metadata, then the build script of bar will have the environment variables DEP_FOO_KEY=value . See the "Using another sys crate" for an example of how this can be used.

Do you know if there is any way to find out what metadata a crate's build script exposes other than reading the source code or hoping it was mentioned in their README?

The impression that i have gotten, from e.g. https://github.com/rust-lang/cargo/issues/7614 is that there isn't currently any way.

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.