diff --git a/src/cargo/util/restricted_names.rs b/src/cargo/util/restricted_names.rs index be1811a8878..2c3eaa9e1f8 100644 --- a/src/cargo/util/restricted_names.rs +++ b/src/cargo/util/restricted_names.rs @@ -87,23 +87,22 @@ pub fn validate_package_name(name: &str, what: &str, help: &str) -> CargoResult< pub fn sanitize_package_name(name: &str, placeholder: char) -> String { let mut slug = String::new(); let mut chars = name.chars(); - if let Some(ch) = chars.next() { - if ch.is_digit(10) { - slug.push(placeholder); - slug.push(ch); - } else if unicode_xid::UnicodeXID::is_xid_start(ch) || ch == '_' { + while let Some(ch) = chars.next() { + if (unicode_xid::UnicodeXID::is_xid_start(ch) || ch == '_') && !ch.is_digit(10) { slug.push(ch); - } else { - slug.push(placeholder); + break; } } - for ch in chars { + while let Some(ch) = chars.next() { if unicode_xid::UnicodeXID::is_xid_continue(ch) || ch == '-' { slug.push(ch); } else { slug.push(placeholder); } } + if slug.is_empty() { + slug.push_str("package"); + } slug } diff --git a/tests/testsuite/script.rs b/tests/testsuite/script.rs index 1065b3bc47e..893241761e9 100644 --- a/tests/testsuite/script.rs +++ b/tests/testsuite/script.rs @@ -543,6 +543,52 @@ args: [] .run(); } +#[cargo_test] +fn test_name_has_leading_number() { + let script = ECHO_SCRIPT; + let p = cargo_test_support::project() + .file("42answer.rs", script) + .build(); + + p.cargo("-Zscript -v 42answer.rs") + .masquerade_as_nightly_cargo(&["script"]) + .with_stdout( + r#"bin: [..]/debug/answer[EXE] +args: [] +"#, + ) + .with_stderr( + r#"[WARNING] `package.edition` is unspecifiead, defaulting to `2021` +[COMPILING] answer v0.0.0 ([ROOT]/foo) +[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]s +[RUNNING] `[..]/debug/answer[EXE]` +"#, + ) + .run(); +} + +#[cargo_test] +fn test_name_is_number() { + let script = ECHO_SCRIPT; + let p = cargo_test_support::project().file("42.rs", script).build(); + + p.cargo("-Zscript -v 42.rs") + .masquerade_as_nightly_cargo(&["script"]) + .with_stdout( + r#"bin: [..]/debug/package[EXE] +args: [] +"#, + ) + .with_stderr( + r#"[WARNING] `package.edition` is unspecifiead, defaulting to `2021` +[COMPILING] package v0.0.0 ([ROOT]/foo) +[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]s +[RUNNING] `[..]/debug/package[EXE]` +"#, + ) + .run(); +} + #[cargo_test] fn script_like_dir() { let p = cargo_test_support::project()