From d7b402c764328ca755e999881b77e2e708fc418b Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Sun, 23 Jul 2023 03:04:59 -0700 Subject: [PATCH] Arg parsing in rust --- Cargo.lock | 9 +++++++++ Cargo.toml | 2 ++ src/args.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 +- 4 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/args.rs diff --git a/Cargo.lock b/Cargo.lock index b091cdb..1dcda70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "lexopt" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baff4b617f7df3d896f97fe922b64817f6cd9a756bb81d40f8883f2f66dcb401" + [[package]] name = "nmsrust" version = "0.1.0" +dependencies = [ + "lexopt", +] diff --git a/Cargo.toml b/Cargo.toml index 9c78f87..9b816d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,3 +10,5 @@ crate-type = ["staticlib"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +lexopt = "0.3.0" + diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..5747380 --- /dev/null +++ b/src/args.rs @@ -0,0 +1,43 @@ +use std::ffi::OsString; + +use lexopt::prelude::*; + +#[derive(Debug, Default)] +pub struct Args { + version: bool, + clear_screen: bool, + foreground: Option, + autodecrypt: bool, + mask_blanks: bool, +} + +pub fn parse_arguments() -> Result { + let mut parser = lexopt::Parser::from_env(); + + let mut args = Args::default(); + + while let Some(arg) = parser.next()? { + match arg { + Short('a') => { + args.autodecrypt = true; + } + Short('c') => { + args.clear_screen = true; + } + Short('f') => { + let foreground = parser.value()?; + args.foreground = Some(foreground); + } + Short('s') => { + args.mask_blanks = true; + } + Short('v') => { + args.version = true; + } + _ => return Err(arg.unexpected()), + } + } + + Ok(args) +} + diff --git a/src/lib.rs b/src/lib.rs index 318ddca..bf89d5c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ - +mod args; #[no_mangle] pub extern "C" fn rust_main() {