Target directories in fetched crate source directories

When does cargo write artifacts to ~/.cargo/registry/src/$REGISTRY/$CRATE/target/ instead of $MY_RUST_PROJECT_DIR/target/?

There are multiple target directories in my ~/.cargo directory, for example ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/bevy-0.17.2/target.

They appear to be dependencies of my projects where I use the nightly toolchain and the Cranelift backend. Are they related?

the target directory is per workspace, not per package. if you only use them as dependencies, cargo should not put files there, unless you run cargo commands directly in the directory.

I think most likely, you might have accidentally opened the source code in your editor and rust-analyzer invoked commands like cargo metadata or cargo check.

1 Like

Another reason this typically happens is when a package runs cargo metadata in a build.rs.

1 Like

Is it possible to change those target directories to another directory, such as $XDG_CACHE_HOME/cargo/$REGISTRY/$CRATE/?