Created
October 24, 2021 06:44
-
-
Save graelo/a4ca4ee282a36b75af12cf9a4ff4d8f0 to your computer and use it in GitHub Desktop.
Example usage of arg_enum in Clap 3.0.0-beta.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "clap-argenum-for-ed" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
clap = "= 3.0.0-beta.2" | |
clap_derive = " = 3.0.0-beta.2" | |
thiserror = "1.0.30" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::str::FromStr; | |
use clap::Clap; | |
#[derive(Debug, thiserror::Error)] | |
pub enum MyError { | |
#[error("Error parsing enum: `{0}`")] | |
EnumParseError(String), | |
} | |
/// Specifies which region should be captured. | |
#[derive(Debug, Clone, Clap)] | |
pub enum CaptureRegion { | |
/// The entire history. | |
/// | |
/// This will end up sending `-S - -E -` to `tmux capture-pane`. | |
EntireHistory, | |
/// The visible area. | |
VisibleArea, | |
} | |
impl FromStr for CaptureRegion { | |
type Err = MyError; | |
fn from_str(s: &str) -> Result<Self, MyError> { | |
match s { | |
"entire-history" => Ok(CaptureRegion::EntireHistory), | |
"visible-area" => Ok(CaptureRegion::VisibleArea), | |
_ => Err(MyError::EnumParseError(format!( | |
"entire-history or visible-area, got {}", | |
s | |
))), | |
} | |
} | |
} | |
/// Main configuration, parsed from command line. | |
#[derive(Clap, Debug)] | |
#[clap(author, about, version)] | |
pub struct Config { | |
/// Specifies which region of the terminal buffer to capture. | |
#[clap(arg_enum, default_value = "visible-area")] | |
pub capture_region: CaptureRegion, | |
} | |
fn main() { | |
let _ = Config::parse(); | |
} |
Thanks Ed for the explanation! It confirms my previous vague understanding of it.
I'll now open an issue for long_about
.
I upgraded the code to beta5 and did not see any conflicts.
Sounds surprising to me, as I spent some time adapting to beta.5, but granted I'm not very experienced with Rust. Nevermind.
Best
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
derive(Clap)
is what allowed this. This predecessor toParser
was a magic "derive any clap related trait possible", includingArgEnum
but we moved away from that in the later betas.Mind creating an Issue for this?
I upgraded the code to beta5 and did not see any conflicts.