Skip to content

Commit

Permalink
fix(embedded): Extend sanitization rules to cover cargo-add validation
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Jun 13, 2023
1 parent 3e540b2 commit 570c5df
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
1 change: 1 addition & 0 deletions src/cargo/ops/cargo_new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ fn get_name<'a>(path: &'a Path, opts: &'a NewOptions) -> CargoResult<&'a str> {
})
}

/// See also `util::toml::embedded::sanitize_name`
fn check_name(
name: &str,
show_name_help: bool,
Expand Down
33 changes: 28 additions & 5 deletions src/cargo/util/toml/embedded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ impl RawScript {
// more common convention for CLIs
'-'
};
let name = restricted_names::sanitize_package_name(&file_name, separator);
let name = sanitize_name(&file_name, separator);
let hash = self.hash();
let bin_name = format!("{name}{separator}{hash}");
package
Expand Down Expand Up @@ -200,6 +200,29 @@ impl RawScript {
}
}

/// Ensure the package name matches the validation from `opt::cargo_new::check_name`
fn sanitize_name(name: &str, placeholder: char) -> String {
let mut name = restricted_names::sanitize_package_name(name, placeholder);

loop {
if restricted_names::is_keyword(&name) {
name.push(placeholder);
} else if restricted_names::is_conflicting_artifact_name(&name) {
// Being an embedded manifest, we always assume it is a `[[bin]]`
name.push(placeholder);
} else if name == "test" {
name.push(placeholder);
} else if restricted_names::is_windows_reserved(&name) {
// Go ahead and be consistent across platforms
name.push(placeholder);
} else {
break;
}
}

name
}

fn default_target_dir() -> CargoResult<std::path::PathBuf> {
let mut cargo_home = home::cargo_home()?;
cargo_home.push("eval");
Expand Down Expand Up @@ -428,12 +451,12 @@ mod test_expand {
fn test_default() {
snapbox::assert_eq(
r#"[[bin]]
name = "test-a472c7a31645d310613df407eab80844346938a3b8fe4f392cae059cb181aa85"
name = "test--a472c7a31645d310613df407eab80844346938a3b8fe4f392cae059cb181aa85"
path = "/home/me/test.rs"
[package]
edition = "2021"
name = "test"
name = "test-"
publish = false
version = "0.0.0"
Expand All @@ -450,15 +473,15 @@ strip = true
fn test_dependencies() {
snapbox::assert_eq(
r#"[[bin]]
name = "test-3a1fa07700654ea2e893f70bb422efa7884eb1021ccacabc5466efe545da8a0b"
name = "test--3a1fa07700654ea2e893f70bb422efa7884eb1021ccacabc5466efe545da8a0b"
path = "/home/me/test.rs"
[dependencies]
time = "0.1.25"
[package]
edition = "2021"
name = "test"
name = "test-"
publish = false
version = "0.0.0"
Expand Down

0 comments on commit 570c5df

Please sign in to comment.