diff --git a/src/cargo/core/compiler/layout.rs b/src/cargo/core/compiler/layout.rs index 272e8198e27..e30d178eda4 100644 --- a/src/cargo/core/compiler/layout.rs +++ b/src/cargo/core/compiler/layout.rs @@ -151,7 +151,12 @@ impl Layout { // actual destination (sub)subdirectory. paths::create_dir_all(dest.as_path_unlocked())?; - let build_dir_lock = if root == build_root || is_on_nfs_mount(build_root.as_path_unlocked()) + // We always need to take the build-dir lock but if the build-dir == artifact-dir then we + // only take the artifact-dir. (locking both as they are the same dir) + // However we need to take into account that for some builds like `cargo check` we avoid + // locking the artifact-dir. We still need to lock the build-dir to avoid file corruption. + let build_dir_lock = if (must_take_artifact_dir_lock && root == build_root) + || is_on_nfs_mount(build_root.as_path_unlocked()) { None } else { diff --git a/tests/testsuite/check.rs b/tests/testsuite/check.rs index 470b18b0a31..21709c60f1d 100644 --- a/tests/testsuite/check.rs +++ b/tests/testsuite/check.rs @@ -1710,13 +1710,35 @@ fn check_build_should_not_output_files_to_artifact_dir() { } #[cargo_test] -fn check_build_should_not_lock_artifact_dir() { +fn check_build_should_lock_target_dir_when_artifact_dir_is_same_as_build_dir() { let p = project() .file("src/main.rs", r#"fn main() { println!("Hello, World!") }"#) .build(); p.cargo("check").enable_mac_dsym().run(); - assert!(!p.root().join("target/debug/.cargo-lock").exists()); + assert!(p.root().join("target/debug/.cargo-lock").exists()); +} + +#[cargo_test] +fn check_build_should_not_lock_artifact_dir_when_build_dir_is_not_same_dir() { + let p = project() + .file("src/main.rs", r#"fn main() { println!("Hello, World!") }"#) + .file( + ".cargo/config.toml", + r#" + [build] + target-dir = "target-dir" + build-dir = "build-dir" + "#, + ) + .build(); + + p.cargo("check").enable_mac_dsym().run(); + + // Verify we did NOT take the build-dir lock + assert!(!p.root().join("target-dir/debug/.cargo-lock").exists()); + // Verify we did take the build-dir lock + assert!(p.root().join("build-dir/debug/.cargo-lock").exists()); } // Regression test for #16305