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
This commit is contained in:
Weihang Lo 2025-05-06 20:03:07 +00:00 committed by GitHub
commit 74c051fd83
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 12 deletions

View File

@ -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)?;

View File

@ -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()