Skip to content

Commit

Permalink
refactor(embedded): Centralize package name rules
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Jun 13, 2023
1 parent dc13c89 commit 03f66cf
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 20 deletions.
24 changes: 24 additions & 0 deletions src/cargo/util/restricted_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
22 changes: 2 additions & 20 deletions src/cargo/util/toml/embedded.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use anyhow::Context as _;

use crate::core::Workspace;
use crate::util::restricted_names;
use crate::CargoResult;
use crate::Config;

Expand Down Expand Up @@ -207,26 +208,7 @@ fn expand_manifest_(script: &RawScript, config: &Config) -> CargoResult<toml::Ta
}

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
restricted_names::sanitize_package_name(name, placeholder)
}

fn hash(script: &RawScript) -> blake3::Hash {
Expand Down

0 comments on commit 03f66cf

Please sign in to comment.