Skip to content

Commit d28ca88

Browse files
committed
fix(new): Only suggest bin.name for valid crate names
Validate crate names are a superset of valid package names which also try to work for `--extern`. Fixes #16396
1 parent 1126b55 commit d28ca88

File tree

3 files changed

+21
-21
lines changed

3 files changed

+21
-21
lines changed

src/cargo/ops/cargo_new.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,8 @@ fn check_name(
181181
};
182182
let bin_help = || {
183183
let mut help = String::from(name_help);
184-
if has_bin && !name.is_empty() {
184+
// Only suggest `bin.name` for valid crate names because it is used for `--crate`
185+
if has_bin && validate_crate_name(name) {
185186
help.push_str(&format!(
186187
"\n\
187188
help: to name the binary \"{name}\", use a valid package \
@@ -274,6 +275,23 @@ fn check_name(
274275
Ok(())
275276
}
276277

278+
// Taken from <https://github.com/rust-lang/rust/blob/693f365667a97b24cb40173bc2801eb66ea53020/compiler/rustc_session/src/output.rs#L49-L79>
279+
fn validate_crate_name(name: &str) -> bool {
280+
if name.is_empty() {
281+
return false;
282+
}
283+
284+
for c in name.chars() {
285+
if c.is_alphanumeric() || c == '-' || c == '_' {
286+
continue;
287+
} else {
288+
return false;
289+
}
290+
}
291+
292+
true
293+
}
294+
277295
/// Checks if the path contains any invalid PATH env characters.
278296
fn check_path(path: &Path, shell: &mut Shell) -> CargoResult<()> {
279297
// warn if the path contains characters that will break `env::join_paths`

tests/testsuite/cargo_init/invalid_dir_name/stderr.term.svg

Lines changed: 2 additions & 14 deletions
Loading

tests/testsuite/new.rs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -170,12 +170,6 @@ fn invalid_characters() {
170170
[ERROR] invalid character `.` in package name: `foo.rs`, characters must be Unicode XID characters (numbers, `-`, `_`, or most letters)
171171
[NOTE] the directory name is used as the package name
172172
[HELP] to override the package name, pass `--name <pkgname>`
173-
[HELP] to name the binary "foo.rs", use a valid package name, and set the binary name to be different from the package. This can be done by setting the binary filename to `src/bin/foo.rs.rs` or change the name in Cargo.toml with:
174-
175-
[[bin]]
176-
name = "foo.rs"
177-
path = "src/main.rs"
178-
179173
180174
"#]])
181175
.run();

0 commit comments

Comments
 (0)