clap/examples/typed-derive.rs

103 lines
2.9 KiB
Rust
Raw Normal View History

use clap::builder::TypedValueParser as _;
use clap::Parser;
use std::error::Error;
docs: Move everything to docs.rs A couple of things happened when preparing to release 3.0 - We needed derive documentation - I had liked how serde handled theres - I had bad experiences finding things in structopt's documentation - The examples were broken and we needed tests - The examples seemed to follow a pattern of having tutorial content and cookbook content - We had been getting bug reports from people looking at master and thinking they were looking at what is currently released - We had gotten feedback to keep down the number of places that documentation was located From this, we went with a mix of docs.rs and github - We kept the number of content locations at 2 rather than 3 by not having an external site like serde - We rewrote the examples into explicit tutorials and cookbooks to align with the 4 styles of documentation - We could test our examples by running `console` code blocks with trycmd - Documentation was versioned and the README pointed to the last release This had downsides - The tutorials didn't have the code inlined - Users still had a hard time finding and navigating between the different forms of documentation - In practice, we were less likely to cross-link between the different types of documentation Moving to docs.rs would offer a lot of benefits, even if it is only designed for Rust-reference documentation and isn't good for Rust derive reference documentation, tutorials, cookbooks, etc. The big problem was keeping the examples tested to keep maintenance costs down. Maybe its just me but its easy to overlook - You can pull documentation from a file using `#[doc = "path"]` - Repeated doc attributes get concatenated rather than first or last writer winning Remember these when specifically thinking about Rust documentation made me realize that we could get everything into docs.rs. When doing this - Tutorial code got brought in as was one of the aims - We needed to split the lib documentation and the README to have all of the linking work. This allowed us to specialize them according to their rule (user vs contributor) - We needed to avoid users getting caught up in making a decision between Derive and Builder APIs so we put the focus on the derive API with links to the FAQ to help users decide when to use one or the other. - Improved cross-referencing between different parts of the documentation - Limited inline comments were added to example code - Introductory example code intentionally does not have teaching comments in it as its meant to give a flavor or sense of things and not meant to teach on its own. This is a first attempt. There will be a lot of room for further improvement. Current know downsides: - Content source is more split up for the tutorials This hopefully addresses #3189
2022-07-19 18:29:31 +00:00
#[derive(Parser, Debug)] // requires `derive` feature
#[command(term_width = 0)] // Just to make testing across clap features easier
struct Args {
2022-03-14 14:43:17 +00:00
/// Implicitly using `std::str::FromStr`
#[arg(short = 'O')]
2022-03-14 14:43:17 +00:00
optimization: Option<usize>,
2022-03-14 14:45:43 +00:00
/// Allow invalid UTF-8 paths
#[arg(short = 'I', value_name = "DIR", value_hint = clap::ValueHint::DirPath)]
2022-03-14 14:45:43 +00:00
include: Option<std::path::PathBuf>,
2022-03-14 14:53:31 +00:00
/// Handle IP addresses
#[arg(long)]
2022-03-14 14:53:31 +00:00
bind: Option<std::net::IpAddr>,
2022-03-14 14:49:46 +00:00
/// Allow human-readable durations
#[arg(long)]
2022-03-14 14:49:46 +00:00
sleep: Option<humantime::Duration>,
2022-03-14 14:43:17 +00:00
/// Hand-written parser for tuples
#[arg(short = 'D', value_parser = parse_key_val::<String, i32>)]
defines: Vec<(String, i32)>,
/// Support for discrete numbers
#[arg(
long,
default_value_t = 22,
value_parser = clap::builder::PossibleValuesParser::new(["22", "80"])
.map(|s| s.parse::<usize>().unwrap()),
)]
port: usize,
/// Support enums from a foreign crate that don't implement `ValueEnum`
#[arg(
long,
default_value_t = foreign_crate::LogLevel::Info,
2023-07-21 15:54:08 +00:00
value_parser = clap::builder::PossibleValuesParser::new(["trace", "debug", "info", "warn", "error"])
.map(|s| s.parse::<foreign_crate::LogLevel>().unwrap()),
)]
log_level: foreign_crate::LogLevel,
}
/// Parse a single key-value pair
fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
where
T: std::str::FromStr,
T::Err: Error + Send + Sync + 'static,
U: std::str::FromStr,
U::Err: Error + Send + Sync + 'static,
{
let pos = s
.find('=')
.ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?;
Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
}
mod foreign_crate {
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
impl std::fmt::Display for LogLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::Trace => "trace",
Self::Debug => "debug",
Self::Info => "info",
Self::Warn => "warn",
Self::Error => "error",
};
s.fmt(f)
}
}
impl std::str::FromStr for LogLevel {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"trace" => Ok(Self::Trace),
"debug" => Ok(Self::Debug),
"info" => Ok(Self::Info),
"warn" => Ok(Self::Warn),
"error" => Ok(Self::Error),
_ => Err(format!("Unknown log level: {s}")),
}
}
}
}
fn main() {
let args = Args::parse();
println!("{args:?}");
}