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

Use clap's validator instead. #1402

Merged
merged 4 commits into from
Jun 25, 2024
Merged
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
55 changes: 40 additions & 15 deletions cmd/soroban-cli/src/commands/contract/deploy/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub struct Cmd {
/// Whether to ignore safety checks when deploying contracts
pub ignore_checks: bool,
/// The alias that will be used to save the contract's id.
#[arg(long)]
#[arg(long, value_parser = clap::builder::ValueParser::new(alias_validator))]
pub alias: Option<String>,
}

Expand Down Expand Up @@ -114,8 +114,6 @@ pub enum Error {

impl Cmd {
pub async fn run(&self) -> Result<(), Error> {
self.validate_alias()?;

let res = self.run_against_rpc_server(None, None).await?.to_envelope();
match res {
TxnEnvelopeResult::TxnEnvelope(tx) => println!("{}", tx.to_xdr_base64(Limits::none())?),
Expand All @@ -135,20 +133,17 @@ impl Cmd {
}
Ok(())
}
}

fn validate_alias(&self) -> Result<(), Error> {
match self.alias.clone() {
Some(alias) => {
let regex = Regex::new(r"^[a-zA-Z0-9_-]{1,30}$").unwrap();
fn alias_validator(alias: &str) -> Result<String, Error> {
let regex = Regex::new(r"^[a-zA-Z0-9_-]{1,30}$").unwrap();

if regex.is_match(&alias) {
Ok(())
} else {
Err(Error::InvalidAliasFormat { alias })
}
}
None => Ok(()),
}
if regex.is_match(alias) {
Ok(alias.into())
} else {
Err(Error::InvalidAliasFormat {
alias: alias.into(),
})
}
}

Expand Down Expand Up @@ -306,4 +301,34 @@ mod tests {

assert!(result.is_ok());
}

#[test]
fn test_alias_validator_with_valid_inputs() {
let valid_inputs = [
"hello",
"123",
"hello123",
"hello_123",
"123_hello",
"123-hello",
"hello-123",
"HeLlo-123",
];

for input in valid_inputs {
let result = alias_validator(input);
assert!(result.is_ok());
assert!(result.unwrap() == input);
}
}

#[test]
fn test_alias_validator_with_invalid_inputs() {
let invalid_inputs = ["", "invalid!", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"];

for input in invalid_inputs {
let result = alias_validator(input);
assert!(result.is_err());
}
}
}
Loading