Skip to content

Commit

Permalink
chore: upgrade deprecated clap usage (#3346)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse authored Sep 25, 2022
1 parent d6fae73 commit 9e29032
Show file tree
Hide file tree
Showing 17 changed files with 81 additions and 75 deletions.
6 changes: 3 additions & 3 deletions cli/src/cmd/cast/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use foundry_config::{Chain, Config};

#[derive(Debug, Parser)]
pub struct CallArgs {
#[clap(help = "The destination of the transaction.", parse(try_from_str = parse_name_or_address), value_name = "TO")]
#[clap(help = "The destination of the transaction.", value_parser = parse_name_or_address, value_name = "TO")]
to: Option<NameOrAddress>,
#[clap(help = "The signature of the function to call.", value_name = "SIG")]
sig: Option<String>,
Expand All @@ -28,7 +28,7 @@ pub struct CallArgs {
#[clap(flatten)]
// TODO: We only need RPC URL and Etherscan API key here.
eth: EthereumOpts,
#[clap(long, short, help = "the block you want to query, can also be earliest/latest/pending", parse(try_from_str = parse_block_id), value_name = "BLOCK")]
#[clap(long, short, help = "the block you want to query, can also be earliest/latest/pending", value_parser = parse_block_id, value_name = "BLOCK")]
block: Option<BlockId>,
#[clap(subcommand)]
command: Option<CallSubcommands>,
Expand All @@ -50,7 +50,7 @@ pub enum CallSubcommands {
long_help = r#"Ether to send in the transaction, either specified in wei, or as a string with a unit type.
Examples: 1ether, 10gwei, 0.01ether"#,
parse(try_from_str = parse_ether_value),
value_parser = parse_ether_value,
value_name = "VALUE"
)]
value: Option<U256>,
Expand Down
6 changes: 3 additions & 3 deletions cli/src/cmd/cast/estimate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use foundry_config::{Chain, Config};

#[derive(Debug, Parser)]
pub struct EstimateArgs {
#[clap(help = "The destination of the transaction.", parse(try_from_str = parse_name_or_address), value_name = "TO")]
#[clap(help = "The destination of the transaction.", value_parser = parse_name_or_address, value_name = "TO")]
to: Option<NameOrAddress>,
#[clap(help = "The signature of the function to call.", value_name = "SIG")]
sig: Option<String>,
Expand All @@ -26,7 +26,7 @@ pub struct EstimateArgs {
long_help = r#"Ether to send in the transaction, either specified in wei, or as a string with a unit type.
Examples: 1ether, 10gwei, 0.01ether"#,
parse(try_from_str = parse_ether_value),
value_parser = parse_ether_value,
value_name = "VALUE"
)]
value: Option<U256>,
Expand All @@ -53,7 +53,7 @@ pub enum EstimateSubcommands {
long_help = r#"Ether to send in the transaction, either specified in wei, or as a string with a unit type.
Examples: 1ether, 10gwei, 0.01ether"#,
parse(try_from_str = parse_ether_value),
value_parser = parse_ether_value,
value_name = "VALUE"
)]
value: Option<U256>,
Expand Down
2 changes: 1 addition & 1 deletion cli/src/cmd/cast/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::sync::Arc;
pub struct SendTxArgs {
#[clap(
help = "The destination of the transaction. If not provided, you must use cast send --create.",
parse(try_from_str = parse_name_or_address),
value_parser = parse_name_or_address,
value_name = "TO"
)]
to: Option<NameOrAddress>,
Expand Down
35 changes: 26 additions & 9 deletions cli/src/cmd/cast/wallet/vanity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use crate::cmd::Cmd;
use cast::SimpleCast;
use clap::Parser;
use clap::{builder::TypedValueParser, Parser};
use ethers::{
core::{k256::ecdsa::SigningKey, rand::thread_rng},
prelude::{LocalWallet, Signer},
Expand All @@ -22,11 +22,11 @@ pub struct VanityArgs {
long,
help = "Prefix for the vanity address.",
required_unless_present = "ends-with",
validator = hex_address_validator(),
value_parser = HexAddressValidator::default(),
value_name = "HEX"
)]
pub starts_with: Option<String>,
#[clap(long, help = "Suffix for the vanity address.", validator = hex_address_validator(), value_name = "HEX")]
#[clap(long, help = "Suffix for the vanity address.", value_parser = HexAddressValidator::default(), value_name = "HEX")]
pub ends_with: Option<String>,
#[clap(
long,
Expand Down Expand Up @@ -280,13 +280,30 @@ impl VanityMatcher for RegexMatcher {
}
}

/// Validates an address from cli args.
pub fn hex_address_validator() -> impl FnMut(&str) -> eyre::Result<()> {
move |v: &str| -> eyre::Result<()> {
if v.len() > 40 {
eyre::bail!("vanity patterns length exceeded. cannot be more than 40 characters")
/// Parse 40 byte addresses
#[derive(Copy, Clone, Debug, Default)]
#[non_exhaustive]
pub struct HexAddressValidator;

impl TypedValueParser for HexAddressValidator {
type Value = String;

fn parse_ref(
&self,
_cmd: &clap::Command,
_arg: Option<&clap::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, clap::Error> {
if value.len() > 40 {
return Err(clap::Error::raw(
clap::ErrorKind::InvalidValue,
"vanity patterns length exceeded. cannot be more than 40 characters",
))
}
Ok(())
let value = value.to_str().ok_or_else(|| {
clap::Error::raw(clap::ErrorKind::InvalidUtf8, "address must be valid utf8")
})?;
Ok(value.to_string())
}
}

Expand Down
14 changes: 8 additions & 6 deletions cli/src/cmd/forge/cache.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! cache command
use clap::{Parser, Subcommand};
use clap::{builder::PossibleValuesParser, Parser, Subcommand};
use std::str::FromStr;
use strum::VariantNames;

Expand All @@ -16,7 +16,7 @@ pub struct CacheArgs {
pub sub: CacheSubcommands,
}

#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum ChainOrAll {
Chain(Chain),
All,
Expand All @@ -43,8 +43,7 @@ pub struct CleanArgs {
#[clap(
env = "CHAIN",
default_value = "all",
possible_value = "all",
possible_values = Chain::VARIANTS,
value_parser = chain_value_parser(),
value_name = "CHAINS"
)]
chains: Vec<ChainOrAll>,
Expand All @@ -70,8 +69,7 @@ pub struct LsArgs {
#[clap(
env = "CHAIN",
default_value = "all",
possible_value = "all",
possible_values = Chain::VARIANTS,
value_parser = chain_value_parser(),
value_name = "CHAINS"
)]
chains: Vec<ChainOrAll>,
Expand Down Expand Up @@ -146,3 +144,7 @@ fn clean_chain_cache(
}
Ok(())
}

fn chain_value_parser() -> PossibleValuesParser {
Some(&"all").into_iter().chain(Chain::VARIANTS).into()
}
2 changes: 1 addition & 1 deletion cli/src/cmd/forge/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub struct FmtArgs {
conflicts_with = "root",
value_hint = ValueHint::FilePath,
value_name = "PATH",
multiple = true
multiple_values = true
)]
paths: Vec<PathBuf>,
#[clap(
Expand Down
2 changes: 1 addition & 1 deletion cli/src/cmd/forge/geiger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub struct GeigerArgs {
conflicts_with = "root",
value_hint = ValueHint::FilePath,
value_name = "PATH",
multiple = true
multiple_values = true
)]
paths: Vec<PathBuf>,
#[clap(
Expand Down
2 changes: 1 addition & 1 deletion cli/src/cmd/forge/script/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ pub struct ScriptArgs {
long,
help = "Gas price for legacy transactions, or max fee per gas for EIP1559 transactions.",
env = "ETH_GAS_PRICE",
parse(try_from_str = parse_ether_value),
value_parser = parse_ether_value,
value_name = "PRICE"
)]
pub with_gas_price: Option<U256>,
Expand Down
6 changes: 3 additions & 3 deletions cli/src/cmd/forge/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ use crate::{
test,
test::{Test, TestOutcome},
},
u32_validator, Cmd,
Cmd,
},
utils::STATIC_FUZZ_SEED,
};
use clap::{Parser, ValueHint};
use clap::{builder::RangedU64ValueParser, Parser, ValueHint};
use ethers::types::U256;
use eyre::Context;
use forge::result::TestKindReport;
Expand Down Expand Up @@ -83,7 +83,7 @@ pub struct SnapshotArgs {
#[clap(
help = "Tolerates gas deviations up to the specified percentage.",
long,
validator = u32_validator(0, 100),
value_parser = RangedU64ValueParser::<u32>::new().range(0..100),
value_name = "SNAPSHOT_THRESHOLD"
)]
tolerance: Option<u32>,
Expand Down
2 changes: 1 addition & 1 deletion cli/src/cmd/forge/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ pub struct TestArgs {
#[clap(
long,
help = "Set seed used to generate randomness during your fuzz runs",
parse(try_from_str = utils::parse_u256)
value_parser = utils::parse_u256
)]
pub fuzz_seed: Option<U256>,
}
Expand Down
6 changes: 3 additions & 3 deletions cli/src/cmd/forge/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{
cmd::forge::{build::BuildArgs, snapshot::SnapshotArgs, test::TestArgs},
utils::{self, FoundryPathExt},
};
use clap::Parser;
use clap::{ArgAction, Parser};
use foundry_config::Config;
use std::{collections::HashSet, convert::Infallible, path::PathBuf, sync::Arc};
use tracing::trace;
Expand Down Expand Up @@ -34,7 +34,7 @@ pub struct WatchArgs {
///
/// When using --poll mode, you'll want a larger duration, or risk
/// overloading disk I/O.
#[clap(long = "watch-delay", forbid_empty_values = true, value_name = "DELAY")]
#[clap(long = "watch-delay", value_parser = clap::builder::NonEmptyStringValueParser::default(), value_name = "DELAY")]
pub watch_delay: Option<String>,

#[clap(long = "no-restart", help = "Do not restart the command while it's still running.")]
Expand All @@ -55,7 +55,7 @@ pub struct WatchArgs {
value_name = "PATH",
min_values = 0,
multiple_values = true,
multiple_occurrences = false,
action = ArgAction::Append,
help = "Watches the given files or directories for changes. If no paths are provided, the source and test directories of the project are watched."
)]
pub watch: Option<Vec<PathBuf>>,
Expand Down
7 changes: 3 additions & 4 deletions cli/src/cmd/retry.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::cmd::u32_validator;
use clap::Parser;
use clap::{builder::RangedU64ValueParser, Parser};
use foundry_utils::Retry;

/// Retry config used when waiting for verification
Expand All @@ -15,7 +14,7 @@ pub struct RetryArgs {
long,
help = "Number of attempts for retrying verification",
default_value = "5",
validator = u32_validator(1, 10),
value_parser = RangedU64ValueParser::<u32>::new().range(1..=10),
value_name = "RETRIES"
)]
pub retries: u32,
Expand All @@ -24,7 +23,7 @@ pub struct RetryArgs {
long,
help = "Optional delay to apply inbetween verification attempts in seconds.",
default_value = "5",
validator = u32_validator(0, 30),
value_parser = RangedU64ValueParser::<u32>::new().range(0..=30),
value_name = "DELAY"
)]
pub delay: u32,
Expand Down
11 changes: 0 additions & 11 deletions cli/src/cmd/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,6 @@ pub fn get_cached_entry_by_name(
eyre::bail!(err)
}

pub fn u32_validator(min: u32, max: u32) -> impl FnMut(&str) -> eyre::Result<()> {
move |v: &str| -> eyre::Result<()> {
let v = v.parse::<u32>()?;
if v >= min && v <= max {
Ok(())
} else {
Err(eyre::eyre!("Expected between {} and {} inclusive.", min, max))
}
}
}

/// Returns error if constructor has arguments.
pub fn ensure_clean_constructor(abi: &Abi) -> eyre::Result<()> {
if let Some(constructor) = &abi.constructor {
Expand Down
Loading

0 comments on commit 9e29032

Please sign in to comment.