From 6b7976e4fd583ff4a2d6fe8590486672c6a5b519 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Tue, 6 May 2025 20:03:07 +0000 Subject: [PATCH] fix(rustc): Don't panic on unknown bins (#15497) ### What does this PR try to resolve? Fixes #15493 ### How should we test and review this PR? This takes the most surgical, direct route to addressing the problem. Alternatively, we could look into why `cargo rustc` and `cargo check` are different. ### Additional information --- src/cargo/ops/cargo_compile/unit_generator.rs | 19 ++++++--------- tests/testsuite/rustc.rs | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/cargo/ops/cargo_compile/unit_generator.rs b/src/cargo/ops/cargo_compile/unit_generator.rs index 588581457b2..3c984f4767b 100644 --- a/src/cargo/ops/cargo_compile/unit_generator.rs +++ b/src/cargo/ops/cargo_compile/unit_generator.rs @@ -294,18 +294,13 @@ impl<'a> UnitGenerator<'a, '_> { let unmatched_packages = match self.spec { Packages::Default | Packages::OptOut(_) | Packages::All(_) => { - "default-run packages".to_owned() - } - Packages::Packages(packages) => { - let first = packages - .first() - .expect("The number of packages must be at least 1"); - if packages.len() == 1 { - format!("`{}` package", first) - } else { - format!("`{}`, ... packages", first) - } + " in default-run packages".to_owned() } + Packages::Packages(packages) => match packages.len() { + 0 => String::new(), + 1 => format!(" in `{}` package", packages[0]), + _ => format!(" in `{}`, ... packages", packages[0]), + }, }; let named = if is_glob { "matches pattern" } else { "named" }; @@ -313,7 +308,7 @@ impl<'a> UnitGenerator<'a, '_> { let mut msg = String::new(); write!( msg, - "no {target_desc} target {named} `{target_name}` in {unmatched_packages}{suggestion}", + "no {target_desc} target {named} `{target_name}`{unmatched_packages}{suggestion}", )?; if !targets_elsewhere.is_empty() { append_targets_elsewhere(&mut msg)?; diff --git a/tests/testsuite/rustc.rs b/tests/testsuite/rustc.rs index 6e9b5b22844..da32f20ac1a 100644 --- a/tests/testsuite/rustc.rs +++ b/tests/testsuite/rustc.rs @@ -533,6 +533,29 @@ fn fail_with_multiple_packages() { .run(); } +#[cargo_test] +fn fail_with_bad_bin_no_package() { + let p = project() + .file( + "src/main.rs", + r#" + fn main() { println!("hello a.rs"); } + "#, + ) + .build(); + + p.cargo("rustc --bin main") + .with_status(101) + .with_stderr_data(str![[r#" +[ERROR] no bin target named `main` +[HELP] available bin targets: + foo +... + +"#]]) + .run(); +} + #[cargo_test] fn fail_with_glob() { let p = project()