misc

Unnamed repository; edit this file 'description' to name the repository.
git clone git://git.alexwennerberg.com/misc
Log | Files | Refs | README | LICENSE

commit d15d0e0161c94d69db2b8a909be2105200213585
parent ee216c00ec2e1dc1ff806e3bfab470e4ca00e459
Author: alex wennerberg <alex@alexwennerberg.com>
Date:   Fri, 24 Dec 2021 02:07:44 -0800

add comments on arg.rs, refactor

Diffstat:
Marg.rs | 47++++++++++++++++++++++++++++++-----------------
1 file changed, 30 insertions(+), 17 deletions(-)

diff --git a/arg.rs b/arg.rs @@ -1,44 +1,57 @@ // Extremely minimalist command line interface, inspired by // [sbase](https://git.suckless.org/sbase/)'s // [arg.h](https://git.suckless.org/sbase/file/arg.h.html) +// +// I believe this has the same behavior, which is: +// * flags can be grouped (-abc) +// * missing arg -> print usage, exit +// * invalid flag -> print usage, exit +// +// This is, of course, aggressively minimalist, perhaps even too much so. +// // Copy/paste this code and you have a CLI! No library needed! use std::env; use std::process::exit; -fn usage() { - eprintln!(r#"./main [-ab] [-c var] [positional] +fn usage() -> ! { + eprintln!( + r#"./main [-ab] [-c var] [positional] -a enables a flag -b enables b flag -c NUM sets var c to NUM - "#); - exit(1); +-d STR sets var c to STR + "# + ); + exit(1) } + fn main() { // Initialize your variables here; let mut a_enabled = false; let mut b_enabled = false; - let mut positional: Option<&str> = None; + let mut positional: Option<String> = None; let mut var: Option<i32> = None; - let args: Vec<String> = env::args().collect(); - for mut n in 1..args.len() { - let mut iter = args[n].chars(); + let mut args = env::args().skip(1); + + while let Some(arg) = args.next() { + let mut iter = arg.chars(); if iter.next() == Some('-') { for m in iter { - // Match your variables here (only supports single-char vars) match m { 'c' => { - if n+1 != args.len() { - var = Some(args[n+1].parse().unwrap()); - n += 1; - } - }, + var = Some( + args.next() + .and_then(|a| a.parse().ok()) + .unwrap_or_else(|| usage()), + ); + } 'a' => { a_enabled = true; - }, - 'b' =>{ + } + 'b' => { b_enabled = true; } _ => { @@ -47,7 +60,7 @@ fn main() { } } } else { - positional = Some(&args[n]); + positional = Some(arg); } }