Skip to content

Commit

Permalink
docs(tutorial): Switch to hand-implemented ValueEnum
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Aug 9, 2022
1 parent 3943ad7 commit 3af94ec
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ required-features = ["cargo"]
[[example]]
name = "04_01_enum"
path = "examples/tutorial_builder/04_01_enum.rs"
required-features = ["cargo", "derive"]
required-features = ["cargo"]

[[example]]
name = "04_02_parse"
Expand Down
40 changes: 38 additions & 2 deletions examples/tutorial_builder/04_01_enum.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,47 @@
use clap::{arg, command, value_parser, ValueEnum};
use clap::{arg, builder::PossibleValue, command, value_parser, ValueEnum};

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] // requires `derive` feature
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Mode {
Fast,
Slow,
}

// Can also be derived] with feature flag `derive`
impl ValueEnum for Mode {
fn value_variants<'a>() -> &'a [Self] {
&[Mode::Fast, Mode::Slow]
}

fn to_possible_value<'a>(&self) -> Option<PossibleValue<'a>> {
Some(match self {
Mode::Fast => PossibleValue::new("fast"),
Mode::Slow => PossibleValue::new("slow"),
})
}
}

impl std::fmt::Display for Mode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.to_possible_value()
.expect("no values are skipped")
.get_name()
.fmt(f)
}
}

impl std::str::FromStr for Mode {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
for variant in Self::value_variants() {
if variant.to_possible_value().unwrap().matches(s, false) {
return Ok(*variant);
}
}
Err(format!("Invalid variant: {}", s))
}
}

fn main() {
let matches = command!() // requires `cargo` feature
.arg(
Expand Down

0 comments on commit 3af94ec

Please sign in to comment.