Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Input validation #464

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/bin/add/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ impl Args {
}

fn parse_single_dependency(&self, crate_name: &str) -> Result<Dependency> {
if crate_name == "." {
return Err(ErrorKind::AttemptedCreatingCircularDependency.into());
}

let crate_name = CrateName::new(crate_name);

if let Some(mut dependency) = crate_name.parse_as_version()? {
Expand All @@ -183,6 +187,7 @@ impl Args {

Ok(dependency)
} else if crate_name.is_url_or_path() {
println!("hello");
Ok(crate_name.parse_crate_name_from_uri()?)
} else {
assert_eq!(self.git.is_some() && self.vers.is_some(), false);
Expand All @@ -191,6 +196,7 @@ impl Args {
assert_eq!(self.path.is_some() && self.registry.is_some(), false);

let mut dependency = Dependency::new(crate_name.name());
dbg!(&dependency);

if let Some(repo) = &self.git {
dependency = dependency.set_git(repo, self.branch.clone());
Expand Down
4 changes: 4 additions & 0 deletions src/bin/add/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ mod args;
mod errors {
error_chain! {
errors {
/// Running `cargo-add .` would create a create circular dependency, this error prevents it
AttemptedCreatingCircularDependency {
description("Attempting to create circular dependency by specifying crate name `.`")
}
/// Specified a dependency with both a git URL and a version.
GitUrlWithVersion(git: String, version: String) {
description("Specified git URL with version")
Expand Down
41 changes: 41 additions & 0 deletions src/crate_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,45 @@ impl<'a> CrateName<'a> {
self.0.contains('.') || self.0.contains('/') || self.0.contains('\\')
}

/// Checks is the specified crate name is a valid, non-empty name for a crates.io crate,
/// meaning it contains only a-zA-Z, dashes, and underscores.
/// expected to be usually called as validate_name()?;
pub fn validate_name(&self) -> Result<()> {
if self.name().is_empty() {
return Err(ErrorKind::EmptyCrateName.into());
}


let contains_only_valid_characters: bool;
let mut invalid_char: char;

if self.name().chars().next().unwrap().is_alphabetic() {
invalid_char = 'a'; //placeholder value. Is always a valid character in a crate name.
contains_only_valid_characters = self.name().chars().all(|c| {
let is_valid = (c.is_alphanumeric() || c == '-' || c == '_') && c.is_ascii();

if !is_valid {
invalid_char = c;
}
is_valid
});
} else {
invalid_char = self.name().chars().next().unwrap();
contains_only_valid_characters = false;
}

if !contains_only_valid_characters {
assert_ne!(invalid_char, 'a'); //check if invalid_char still does not contains its initial placeholder value. That should never happen
return Err(ErrorKind::CrateNameContainsInvalidCharacter(
self.name().to_string(),
invalid_char,
)
.into());
}

Ok(())
}

/// If this crate specifier includes a version (e.g. `docopt@0.8`), extract the name and
/// version.
pub fn parse_as_version(&self) -> Result<Option<Dependency>> {
Expand All @@ -50,6 +89,8 @@ impl<'a> CrateName<'a> {
let (name, version) = (xs[0], xs[1]);
semver::VersionReq::parse(version).chain_err(|| "Invalid crate version requirement")?;

self.validate_name()?;

Ok(Some(Dependency::new(name).set_version(version)))
} else {
Ok(None)
Expand Down
5 changes: 5 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ error_chain! {
}

errors {
/// A crate contains invalid symbol
CrateNameContainsInvalidCharacter(crate_name: String, symbol: char) {
description("Specified crate name(s) contains invalid symbol(s)")
display("Crate name \"{}\" is invalid, contains symbol '{}' (byte values: {})", crate_name, &symbol, symbol.escape_unicode())
}
/// Failed to read home directory
ReadHomeDirFailure {
description("Failed to read home directory")
Expand Down
4 changes: 1 addition & 3 deletions src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ pub fn get_latest_dependency(
return Ok(Dependency::new(crate_name).set_version(&new_version));
}

if crate_name.is_empty() {
return Err(ErrorKind::EmptyCrateName.into());
}
crate::CrateName::new(crate_name).validate_name()?;

let registry_path = match registry {
Some(url) => registry_path_from_url(url)?,
Expand Down