How to locate the Cargo.lock from build.rs

257 Views Asked by At

I want to be able to read the Cargo.lock file from build.rs without resorting to literal paths.

In build.rs, std::env::var("CARGO_MANIFEST_DIR").unwrap(); can be used to find the Cargo.toml, and traditionally the Cargo.lock was in this directory, however with the introduction of workspaces that is no longer always true.

1

There are 1 best solutions below

1
On

https://crates.io/crates/project-root can be used to find the nearest Cargo.lock up the directory structure from the current directory.

In Cargo.toml add

[build-dependencies]
project-root = "*"

And in build.rs use project_root::get_project_root().unwrap() to obtain the directory where Cargo.lock is.

(It would be nice to find a solution which doesn't need additional dependencies)