diff --git a/src/cargo/util/restricted_names.rs b/src/cargo/util/restricted_names.rs index 650ae233059c..6a666db99e15 100644 --- a/src/cargo/util/restricted_names.rs +++ b/src/cargo/util/restricted_names.rs @@ -83,6 +83,30 @@ pub fn validate_package_name(name: &str, what: &str, help: &str) -> CargoResult< Ok(()) } +/// Ensure a package name is [valid][validate_package_name] +pub fn sanitize_package_name(name: &str, placeholder: char) -> String { + let mut slug = String::new(); + for (i, c) in name.chars().enumerate() { + match (i, c) { + (0, '0'..='9') => { + slug.push(placeholder); + slug.push(c); + } + (_, '0'..='9') | (_, 'a'..='z') | (_, '_') | (_, '-') => { + slug.push(c); + } + (_, 'A'..='Z') => { + // Convert uppercase characters to lowercase to avoid `non_snake_case` warnings. + slug.push(c.to_ascii_lowercase()); + } + (_, _) => { + slug.push(placeholder); + } + } + } + slug +} + /// Check the entire path for names reserved in Windows. pub fn is_windows_reserved_path(path: &Path) -> bool { path.iter() diff --git a/src/cargo/util/toml/embedded.rs b/src/cargo/util/toml/embedded.rs index 23dcf363292a..08f81a49b654 100644 --- a/src/cargo/util/toml/embedded.rs +++ b/src/cargo/util/toml/embedded.rs @@ -1,6 +1,7 @@ use anyhow::Context as _; use crate::core::Workspace; +use crate::util::restricted_names; use crate::CargoResult; use crate::Config; @@ -207,26 +208,7 @@ fn expand_manifest_(script: &RawScript, config: &Config) -> CargoResult String { - let mut slug = String::new(); - for (i, c) in name.chars().enumerate() { - match (i, c) { - (0, '0'..='9') => { - slug.push(placeholder); - slug.push(c); - } - (_, '0'..='9') | (_, 'a'..='z') | (_, '_') | (_, '-') => { - slug.push(c); - } - (_, 'A'..='Z') => { - // Convert uppercase characters to lowercase to avoid `non_snake_case` warnings. - slug.push(c.to_ascii_lowercase()); - } - (_, _) => { - slug.push(placeholder); - } - } - } - slug + restricted_names::sanitize_package_name(name, placeholder) } fn hash(script: &RawScript) -> blake3::Hash {