summaryrefslogtreecommitdiff
path: root/src/flags.rs
blob: c93f3ef9a24a355f707743c6f31d1786031b0783 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const HELP_FLAG:              &str = "help h";
const VERSION_FLAG:           &str = "version v";
const DONT_PERSIST:           &str = "d";


pub struct Flags {
  pub help: bool,
  pub version: bool,
  pub dont_persist: bool,
  pub arg_count: usize
}


/// Parses an list of String arguments into a set of flags that can be used by crab
/// #### Arguments
/// * `args` - The list of String arguments
/// #### Returns
/// * `None` - If there is an invalid argument in the list
/// * `Some(Flags)` - If the arguments were secussfully parsed, returning the flags
pub fn parse(args: &[String]) -> Option<Flags> {
  let mut flags = Flags { 
    help: false, 
    version: false,
    dont_persist: false, 
    arg_count: 0 
  };
  for arg in args {
    if !is_arg(&arg) { break; }
    flags.arg_count += 1;
    if arg.starts_with("--") {
      let flag = &arg[2..];
      if !set_flag(&flag, &mut flags) {
        eprintln!("Invalid argument: {}", arg);
        return None
      }
    } else {
      let flag = &arg[1..];
      for char in flag.chars() {
        if !set_flag(&char.to_string(), &mut flags) {
            eprintln!("Invalid argument: {}", arg);
            return None
        }
      }
    }
  }
  Some(flags)
}


/// Checks if a given string is a given argument
fn is_arg(arg: &str) -> bool {
  return arg.starts_with("-");
}


/// Sets a flag in a `Flags` struct
/// #### Arguments
/// * `arg` - The argument to check
/// * `flags` - The `Flags` stuct to update
/// #### Returns
/// * `true` - If the argument passed is a valid flag
/// * `false` - If the argument passed is not a valid flag
fn set_flag(arg: &str, flags: &mut Flags) -> bool {
  if has_flag_set(&arg, HELP_FLAG) {
    flags.help = true;
    return true
  } else if has_flag_set(&arg, VERSION_FLAG) {
    flags.version = true;
    return true
  } else if has_flag_set(&arg, DONT_PERSIST) {
    flags.dont_persist = true;
    return true
  }
  false
}


/// Returns if a given argument is a certain flag
/// #### Arguments
/// * `arg` - The arch to check
/// #### Returns
/// * `true` - If the argument matches the flag
/// * `false` - If the argument doesn't match the flag
fn has_flag_set(arg: &str, check: &str) -> bool {
  for check_arg in check.split(" ") {
    if check_arg == arg {
      return true
    }
  }
  return false
}