index/misc

Misc scripts and tools
git clone https://git.alexwennerberg.com/misc

arg.rs@main

raw
38145fa Cleanup arg.rs alex wennerberg 2021-07-20 11:18:46+0700
...

1// Extremely minimalist command line interface, inspired by
2// [sbase](https://git.suckless.org/sbase/)'s
3// [arg.h](https://git.suckless.org/sbase/file/arg.h.html)
4// Copy/paste this code and you have a CLI! No library needed!
5
6use std::env;
7use std::process::exit;
8
9fn usage() {
10    eprintln!(r#"./main [-ab] [-c var] [positional]
11
12-a      enables a flag
13-b      enables b flag
14-c NUM  sets var c to NUM
15              "#);
16    exit(1);
17}
18fn main() {
19    // Initialize your variables here;
20    let mut a_enabled = false;
21    let mut b_enabled = false;
22    let mut positional:  Option<&str> = None;
23    let mut var: Option<i32> = None;
24
25    let args: Vec<String> = env::args().collect();
26    for mut n in 1..args.len() {
27        let mut iter = args[n].chars();
28        if iter.next() == Some('-') {
29            for m in iter {
30                // Match your variables here (only supports single-char vars)
31                match m {
32                    'c' => {
33                        if n+1 != args.len() {
34                            var = Some(args[n+1].parse().unwrap());
35                            n += 1;
36                        }
37                    },
38                    'a' => {
39                        a_enabled = true;
40                    },
41                    'b'  =>{
42                        b_enabled = true;
43                    }
44                    _ => {
45                        usage();
46                    }
47                }
48            }
49        } else {
50            positional = Some(&args[n]);
51        }
52    }
53
54    // Check values of variables, use to direct behavior
55    if a_enabled {
56        println!("a enabled");
57    }
58    if b_enabled {
59        println!("b enabled");
60    }
61    if let Some(v) = var {
62        println!("var: {}", v);
63    }
64    if let Some(p) = positional {
65        println!("positional: {}", p);
66    }
67}
68