diff --git a/src/cargo/ops/cargo_clean.rs b/src/cargo/ops/cargo_clean.rs index 34c74afed5b..84970c90aee 100644 --- a/src/cargo/ops/cargo_clean.rs +++ b/src/cargo/ops/cargo_clean.rs @@ -73,8 +73,10 @@ pub fn clean(ws: &Workspace<'_>, opts: &CleanOptions<'_>) -> CargoResult<()> { if opts.explicit_target_dir_arg { let target_dir_path = target_dir.as_path_unlocked(); - // check if the target directory has a valid CACHEDIR.TAG - if let Err(err) = validate_target_dir_tag(target_dir_path) { + // perform validation on target_dir only if it exists and check if the target directory has a valid CACHEDIR.TAG + if target_dir_path.exists() + && let Err(err) = validate_target_dir_tag(target_dir_path) + { // if target_dir was passed explicitly via --target-dir, then hard error if validation fails let title = format!("cannot clean `{}`: {err}", target_dir_path.display()); let report = [Level::ERROR diff --git a/tests/testsuite/clean.rs b/tests/testsuite/clean.rs index 0ad0ed2869b..ccc294fe390 100644 --- a/tests/testsuite/clean.rs +++ b/tests/testsuite/clean.rs @@ -1450,3 +1450,19 @@ fn config_target_dir_tag_valid() { p.cargo("clean").run(); } + +#[cargo_test] +fn explicit_target_dir_not_exists() { + let p = project() + .file("Cargo.toml", &basic_bin_manifest("foo")) + .file("src/foo.rs", &main_file(r#""i am foo""#, &[])) + .build(); + + // should not error if target_dir does not exist + p.cargo("clean --target-dir bar") + .with_stderr_data(str![[r#" +[REMOVED] 0 files + +"#]]) + .run(); +} diff --git a/tests/testsuite/clean_new_layout.rs b/tests/testsuite/clean_new_layout.rs index 0dd9c0149e7..425d09224a8 100644 --- a/tests/testsuite/clean_new_layout.rs +++ b/tests/testsuite/clean_new_layout.rs @@ -1345,3 +1345,21 @@ fn config_target_dir_tag_valid() { .masquerade_as_nightly_cargo(&["new build-dir layout"]) .run(); } + +#[cargo_test] +fn explicit_target_dir_not_exists() { + let p = project() + .file("Cargo.toml", &basic_bin_manifest("foo")) + .file("src/foo.rs", &main_file(r#""i am foo""#, &[])) + .build(); + + // should not error if target_dir does not exist + p.cargo("clean --target-dir bar") + .arg("-Zbuild-dir-new-layout") + .masquerade_as_nightly_cargo(&["new build-dir layout"]) + .with_stderr_data(str![[r#" +[REMOVED] 0 files + +"#]]) + .run(); +}