-
-
Save magistau/9ee78c80f540fdc84b43e52750502d0e to your computer and use it in GitHub Desktop.
Simple command line parser with clap
This file contains 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 clap::Parser; | |
use regex::Regex; | |
use std::{ | |
fmt::{self, Debug, Display}, | |
str::FromStr, | |
}; | |
use thiserror::Error; | |
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] | |
enum Browser { | |
#[default] | |
Chrome, | |
Firefox, | |
Edge, | |
} | |
#[derive(Debug, Error)] | |
#[error("Unknown browser")] | |
struct UnknownBrowser; | |
impl FromStr for Browser { | |
type Err = UnknownBrowser; | |
fn from_str(s: &str) -> Result<Self, Self::Err> { | |
match s.to_lowercase().as_str() { | |
"chrome" => Ok(Browser::Chrome), | |
"firefox" => Ok(Browser::Firefox), | |
"edge" => Ok(Browser::Edge), | |
_ => Err(UnknownBrowser), | |
} | |
} | |
} | |
impl Display for Browser { | |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
match self { | |
Self::Chrome => write!(f, "Chrome"), | |
Self::Firefox => write!(f, "Firefox"), | |
Self::Edge => write!(f, "Edge"), | |
} | |
} | |
} | |
/// Simple command-line argument parser | |
#[derive(Parser, Debug)] | |
#[command(version, about, long_about = None)] | |
struct Args { | |
/// Name of the environment (and associated properties) | |
#[arg(short, long, default_value = "v2.0")] | |
env: String, | |
/// Test suite to execute in src/test/resources/testsuites | |
#[arg(short, long)] | |
xml: Option<String>, | |
/// Browser to use for testing | |
#[arg(short, long, default_value_t)] | |
browser: Browser, | |
/// Selenium WebDriverWait value in seconds | |
#[arg(short, long, default_value_t = 10)] | |
wait: u8, | |
/// Regex pattern for test cases to execute with maven failsafe plugin | |
#[arg(short, long, default_value = ".*")] | |
tests: Regex, | |
} | |
// cargo run -- --browser=Firefox --env=v1.0 --wait=30 --xml=smoke.xml | |
fn main() { | |
let args = Args::parse(); | |
println!("Environment: {}", args.env); | |
println!("Test suite: {:?}", args.xml); | |
println!("Browser: {:?}", args.browser); | |
println!("Selenium WebDriverWait: {} seconds", args.wait); | |
println!("Regex pattern for test cases: {:?}", args.tests); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment