From 1a0fde95fc2403041f9f477f4220618ee916853b Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Wed, 24 Apr 2024 20:10:19 +0200 Subject: args: Argument parser Still getting used to rust --- src/main.rs | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 2 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index e7a11a9..6b7c181 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,67 @@ -fn main() { - println!("Hello, world!"); +mod args; + +use crate::args::Parser; +use std::process::ExitCode; + +fn parse_args() -> Result { + let mut options = args::Options::new(); + let help_idx = options.push( + args::OptionBuilder::default() + .short('h') + .long("help") + .description("display this and exit") + .build().unwrap()); + let version_idx = options.push( + args::OptionBuilder::default() + .short('V') + .long("version") + .description("display version and exit") + .build().unwrap()); + let verbose_idx = options.push( + args::OptionBuilder::default() + .long("verbose") + .description("be verbose") + .build().unwrap()); + let test_idx = options.push( + args::OptionBuilder::default() + .short('t') + .long("test") + .description("testing") + .value(args::ValueRequirement::Required("FILE")) + .build().unwrap()); + + let parser = args::ShortAndLongParser::new(); + let args = parser.run(&mut options, std::env::args())?; + let ref help = options[help_idx]; + if help.is_set() { + parser.print_help(&options); + return Ok(true); + } + let ref version = options[version_idx]; + if version.is_set() { + println!("Version is 0.0.1"); + return Ok(true); + } + let ref verbose = options[verbose_idx]; + let ref test = options[test_idx]; + println!("verbose: {}", verbose.is_set()); + println!("test: {:?}", test.value()); + println!("args: {:?}", args.args); + Ok(false) +} + +fn main() -> ExitCode { + match parse_args() { + Ok(exit) => { + if exit { + return ExitCode::SUCCESS; + } + } + Err(msg) => { + eprintln!("{}", msg); + return ExitCode::FAILURE; + } + } + + ExitCode::SUCCESS } -- cgit v1.2.3-70-g09d2