doc(derive): Update for value_parser

This commit is contained in:
Ed Page 2022-05-20 19:52:04 -05:00
parent 852a1b15d4
commit e23800e10e
25 changed files with 68 additions and 45 deletions

View file

@ -44,11 +44,11 @@ use clap::Parser;
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Args { struct Args {
/// Name of the person to greet /// Name of the person to greet
#[clap(short, long)] #[clap(short, long, value_parser)]
name: String, name: String,
/// Number of times to greet /// Number of times to greet
#[clap(short, long, default_value_t = 1)] #[clap(short, long, value_parser, default_value_t = 1)]
count: u8, count: u8,
} }

View file

@ -12,7 +12,7 @@ enum Cargo {
#[derive(clap::Args)] #[derive(clap::Args)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct ExampleDerive { struct ExampleDerive {
#[clap(long, parse(from_os_str))] #[clap(long, value_parser)]
manifest_path: Option<std::path::PathBuf>, manifest_path: Option<std::path::PathBuf>,
} }

View file

@ -7,11 +7,11 @@ use clap::Parser;
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Args { struct Args {
/// Name of the person to greet /// Name of the person to greet
#[clap(short, long)] #[clap(short, long, value_parser)]
name: String, name: String,
/// Number of times to greet /// Number of times to greet
#[clap(short, long, default_value_t = 1)] #[clap(short, long, value_parser, default_value_t = 1)]
count: u8, count: u8,
} }

View file

@ -200,7 +200,7 @@ These correspond to a `clap::Arg`.
- When `Option<T>`, the subcommand becomes optional - When `Option<T>`, the subcommand becomes optional
- `from_global`: Read a `clap::Arg::global` argument (raw attribute), regardless of what subcommand you are in - `from_global`: Read a `clap::Arg::global` argument (raw attribute), regardless of what subcommand you are in
- `parse(<kind> [= <function>])`: `clap::Arg::validator` and `clap::ArgMatches::values_of_t` - `parse(<kind> [= <function>])`: `clap::Arg::validator` and `clap::ArgMatches::values_of_t`
- **Deprecated:** See `value_parser` - **Deprecated:** except for `from_flag` or `from_occurrences`, instead use `value_parser`
- Default: `try_from_str` - Default: `try_from_str`
- Warning: for `Path` / `OsString`, be sure to use `try_from_os_str` - Warning: for `Path` / `OsString`, be sure to use `try_from_os_str`
- See [Arg Types](#arg-types) for more details - See [Arg Types](#arg-types) for more details

View file

@ -3,12 +3,14 @@ use clap::{ArgMatches, Args as _, Command, FromArgMatches, Parser, Subcommand};
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
struct AddArgs { struct AddArgs {
#[clap(value_parser)]
name: Vec<String>, name: Vec<String>,
} }
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
struct RemoveArgs { struct RemoveArgs {
#[clap(short, long)] #[clap(short, long)]
force: bool, force: bool,
#[clap(value_parser)]
name: Vec<String>, name: Vec<String>,
} }

View file

@ -8,10 +8,10 @@ struct Cli {
#[clap(short = 'f')] #[clap(short = 'f')]
eff: bool, eff: bool,
#[clap(short = 'p', value_name = "PEAR")] #[clap(short = 'p', value_name = "PEAR", value_parser)]
pea: Option<String>, pea: Option<String>,
#[clap(last = true)] #[clap(last = true, value_parser)]
slop: Vec<String>, slop: Vec<String>,
} }

View file

@ -20,19 +20,21 @@ enum Commands {
#[clap(arg_required_else_help = true)] #[clap(arg_required_else_help = true)]
Clone { Clone {
/// The remote to clone /// The remote to clone
#[clap(value_parser)]
remote: String, remote: String,
}, },
/// pushes things /// pushes things
#[clap(arg_required_else_help = true)] #[clap(arg_required_else_help = true)]
Push { Push {
/// The remote to target /// The remote to target
#[clap(value_parser)]
remote: String, remote: String,
}, },
/// adds things /// adds things
#[clap(arg_required_else_help = true)] #[clap(arg_required_else_help = true)]
Add { Add {
/// Stuff to add /// Stuff to add
#[clap(required = true, parse(from_os_str))] #[clap(required = true, value_parser)]
path: Vec<PathBuf>, path: Vec<PathBuf>,
}, },
Stash(Stash), Stash(Stash),
@ -53,13 +55,19 @@ struct Stash {
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
enum StashCommands { enum StashCommands {
Push(StashPush), Push(StashPush),
Pop { stash: Option<String> }, Pop {
Apply { stash: Option<String> }, #[clap(value_parser)]
stash: Option<String>,
},
Apply {
#[clap(value_parser)]
stash: Option<String>,
},
} }
#[derive(Debug, Args)] #[derive(Debug, Args)]
struct StashPush { struct StashPush {
#[clap(short, long)] #[clap(short, long, value_parser)]
message: Option<String>, message: Option<String>,
} }

View file

@ -6,10 +6,11 @@ use clap::{Parser, Subcommand};
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
/// Optional name to operate on /// Optional name to operate on
#[clap(value_parser)]
name: Option<String>, name: Option<String>,
/// Sets a custom config file /// Sets a custom config file
#[clap(short, long, parse(from_os_str), value_name = "FILE")] #[clap(short, long, value_parser, value_name = "FILE")]
config: Option<PathBuf>, config: Option<PathBuf>,
/// Turn debugging information on /// Turn debugging information on
@ -25,7 +26,7 @@ enum Commands {
/// does testing things /// does testing things
Test { Test {
/// lists test values /// lists test values
#[clap(short, long)] #[clap(short, long, value_parser)]
list: bool, list: bool,
}, },
} }

View file

@ -6,9 +6,9 @@ use clap::{AppSettings, Parser};
#[clap(allow_negative_numbers = true)] #[clap(allow_negative_numbers = true)]
#[clap(global_setting(AppSettings::DeriveDisplayOrder))] #[clap(global_setting(AppSettings::DeriveDisplayOrder))]
struct Cli { struct Cli {
#[clap(long)] #[clap(long, value_parser)]
two: String, two: String,
#[clap(long)] #[clap(long, value_parser)]
one: String, one: String,
} }

View file

@ -6,9 +6,9 @@ use clap::Parser;
#[clap(version = "1.0")] #[clap(version = "1.0")]
#[clap(about = "Does awesome things", long_about = None)] #[clap(about = "Does awesome things", long_about = None)]
struct Cli { struct Cli {
#[clap(long)] #[clap(long, value_parser)]
two: String, two: String,
#[clap(long)] #[clap(long, value_parser)]
one: String, one: String,
} }

View file

@ -3,9 +3,9 @@ use clap::Parser;
#[derive(Parser)] #[derive(Parser)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
#[clap(long)] #[clap(long, value_parser)]
two: String, two: String,
#[clap(long)] #[clap(long, value_parser)]
one: String, one: String,
} }

View file

@ -3,7 +3,7 @@ use clap::Parser;
#[derive(Parser)] #[derive(Parser)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
#[clap(short, long)] #[clap(short, long, value_parser)]
verbose: bool, verbose: bool,
} }

View file

@ -3,7 +3,7 @@ use clap::Parser;
#[derive(Parser)] #[derive(Parser)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
#[clap(short, long)] #[clap(short, long, value_parser)]
name: Option<String>, name: Option<String>,
} }

View file

@ -3,6 +3,7 @@ use clap::Parser;
#[derive(Parser)] #[derive(Parser)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
#[clap(value_parser)]
name: Option<String>, name: Option<String>,
} }

View file

@ -11,7 +11,10 @@ struct Cli {
#[derive(Subcommand)] #[derive(Subcommand)]
enum Commands { enum Commands {
/// Adds files to myapp /// Adds files to myapp
Add { name: Option<String> }, Add {
#[clap(value_parser)]
name: Option<String>,
},
} }
fn main() { fn main() {

View file

@ -16,6 +16,7 @@ enum Commands {
#[derive(Args)] #[derive(Args)]
struct Add { struct Add {
#[clap(value_parser)]
name: Option<String>, name: Option<String>,
} }

View file

@ -3,7 +3,7 @@ use clap::Parser;
#[derive(Parser)] #[derive(Parser)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
#[clap(default_value_t = String::from("alice"))] #[clap(default_value_t = String::from("alice"), value_parser)]
name: String, name: String,
} }

View file

@ -4,7 +4,7 @@ use clap::{ArgEnum, Parser};
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
/// What mode to run the program in /// What mode to run the program in
#[clap(arg_enum)] #[clap(arg_enum, value_parser)]
mode: Mode, mode: Mode,
} }

View file

@ -4,8 +4,8 @@ use clap::Parser;
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
/// Network port to use /// Network port to use
#[clap(parse(try_from_str))] #[clap(value_parser = clap::value_parser!(u16).range(1..))]
port: usize, port: u16,
} }
fn main() { fn main() {

View file

@ -6,8 +6,8 @@ use clap::Parser;
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
/// Network port to use /// Network port to use
#[clap(parse(try_from_str=port_in_range))] #[clap(value_parser = port_in_range)]
port: usize, port: u16,
} }
fn main() { fn main() {
@ -18,12 +18,12 @@ fn main() {
const PORT_RANGE: RangeInclusive<usize> = 1..=65535; const PORT_RANGE: RangeInclusive<usize> = 1..=65535;
fn port_in_range(s: &str) -> Result<usize, String> { fn port_in_range(s: &str) -> Result<u16, String> {
let port: usize = s let port: usize = s
.parse() .parse()
.map_err(|_| format!("`{}` isn't a port number", s))?; .map_err(|_| format!("`{}` isn't a port number", s))?;
if PORT_RANGE.contains(&port) { if PORT_RANGE.contains(&port) {
Ok(port) Ok(port as u16)
} else { } else {
Err(format!( Err(format!(
"Port not in range {}-{}", "Port not in range {}-{}",

View file

@ -9,7 +9,7 @@ use clap::{ArgGroup, Parser};
))] ))]
struct Cli { struct Cli {
/// set version manually /// set version manually
#[clap(long, value_name = "VER")] #[clap(long, value_name = "VER", value_parser)]
set_ver: Option<String>, set_ver: Option<String>,
/// auto inc major /// auto inc major
@ -25,14 +25,14 @@ struct Cli {
patch: bool, patch: bool,
/// some regular input /// some regular input
#[clap(group = "input")] #[clap(group = "input", value_parser)]
input_file: Option<String>, input_file: Option<String>,
/// some special input argument /// some special input argument
#[clap(long, group = "input")] #[clap(long, group = "input", value_parser)]
spec_in: Option<String>, spec_in: Option<String>,
#[clap(short, requires = "input")] #[clap(short, requires = "input", value_parser)]
config: Option<String>, config: Option<String>,
} }

View file

@ -4,7 +4,7 @@ use clap::{CommandFactory, ErrorKind, Parser};
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
/// set version manually /// set version manually
#[clap(long, value_name = "VER")] #[clap(long, value_name = "VER", value_parser)]
set_ver: Option<String>, set_ver: Option<String>,
/// auto inc major /// auto inc major
@ -20,13 +20,14 @@ struct Cli {
patch: bool, patch: bool,
/// some regular input /// some regular input
#[clap(value_parser)]
input_file: Option<String>, input_file: Option<String>,
/// some special input argument /// some special input argument
#[clap(long)] #[clap(long, value_parser)]
spec_in: Option<String>, spec_in: Option<String>,
#[clap(short)] #[clap(short, value_parser)]
config: Option<String>, config: Option<String>,
} }

View file

@ -4,8 +4,8 @@ use clap::Parser;
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
struct Cli { struct Cli {
/// Network port to use /// Network port to use
#[clap(parse(try_from_str))] #[clap(value_parser)]
port: usize, port: u16,
} }
fn main() { fn main() {

View file

@ -453,6 +453,12 @@ error: Invalid value "foobar" for '<PORT>': invalid digit found in string
For more information try --help For more information try --help
$ 04_02_parse_derive 0
? failed
error: Invalid value "0" for '<PORT>': 0 is not in 1..=65535
For more information try --help
``` ```
A custom parser can be used to improve the error messages or provide additional validation: A custom parser can be used to improve the error messages or provide additional validation:

View file

@ -6,23 +6,23 @@ use std::error::Error;
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
struct Args { struct Args {
/// Implicitly using `std::str::FromStr` /// Implicitly using `std::str::FromStr`
#[clap(short = 'O')] #[clap(short = 'O', value_parser)]
optimization: Option<usize>, optimization: Option<usize>,
/// Allow invalid UTF-8 paths /// Allow invalid UTF-8 paths
#[clap(short = 'I', parse(from_os_str), value_name = "DIR", value_hint = clap::ValueHint::DirPath)] #[clap(short = 'I', value_parser, value_name = "DIR", value_hint = clap::ValueHint::DirPath)]
include: Option<std::path::PathBuf>, include: Option<std::path::PathBuf>,
/// Handle IP addresses /// Handle IP addresses
#[clap(long)] #[clap(long, value_parser)]
bind: Option<std::net::IpAddr>, bind: Option<std::net::IpAddr>,
/// Allow human-readable durations /// Allow human-readable durations
#[clap(long)] #[clap(long, value_parser)]
sleep: Option<humantime::Duration>, sleep: Option<humantime::Duration>,
/// Hand-written parser for tuples /// Hand-written parser for tuples
#[clap(short = 'D', parse(try_from_str = parse_key_val), multiple_occurrences(true))] #[clap(short = 'D', value_parser = parse_key_val::<String, i32>, multiple_occurrences(true))]
defines: Vec<(String, i32)>, defines: Vec<(String, i32)>,
} }