Why does cargo performs a rebuild and how to prevent it?

I am working on a project that calls cargo internally to perform a build, and then calls it again, with almost exactly the same parameters, but with the unstable option --build-plan, so that it can parse the JSON output and find the details about what has been built.

The problem I am having is that after calling cargo once with --build-plan, next cargo build rebuilds everything from scratch. Why is it doing it and how can I prevent it?

To reproduce it, just go to some rust project and run:

$ cargo +nightly build -Z unstable-options
$ cargo +nightly build -Z unstable-options --build-plan
$ cargo +nightly build -Z unstable-options

if, like me, you suffer from the problem, you will see the third call will rebuild everything.

Using a separate --target-dir for runs with --build-plan might help.

1 Like

the reason is --build-plan needs to re-calculate the entire building process of the crate, (e.g. possibly re-run the build scripts because scripts may output meta data to cargo and change the build plan). so essentially it runs a clean build, and thus touches and invalidates the the entire build cache.

its intended use is to integrate with other build systems, so this behavior is unavoidable to ensure it will give the correct output and won't miss anything.

the solution, as @manpacket suggested, is to use a separate target directory so your existing build cache won't be invalidated.

1 Like