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
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use crate::args::*;
use crate::errors::{Result, *};
use std::collections::HashMap;

/// Specifies the valid arguments of the program and is used to parse
/// the command-line arguments into an [`Arg`].
pub struct ArgSpec {
  args: HashMap<String, ArgType>,
}

type ArgIter = std::iter::Peekable<std::iter::Skip<std::env::Args>>;

impl ArgSpec {
  /// Creates an [`ArgSpecBuilder`] that can be used to build the [`ArgSpec`].
  ///
  /// # Example
  ///
  /// ```
  /// let spec = ArgSpec::build().boolean("arg1").done();
  /// ```
  pub fn build() -> ArgSpecBuilder {
    ArgSpecBuilder {
      args: HashMap::new(),
    }
  }

  /// Determines if an argument of a given name and [`ArgType`] exists
  /// within the [`ArgSpec`].
  ///
  /// # Example
  ///
  /// ```
  /// if spec.has_arg("username", ArgType::String) {
  ///     let args = spec.parse()?;
  ///     if let Some(username) = args.string("username") {
  ///         // let's just ignore the password ;)
  ///         login(username);
  ///     }
  /// }
  /// ```
  pub fn has_arg(&self, name: impl Into<String>, ty: ArgType) -> bool {
    if let Some(_t) = self.args.get(&name.into()) {
      matches!(ty, _t)
    } else {
      false
    }
  }

  /// Parses the command-line arguments and Returns [`Ok(Args)`] if there
  /// were no parse errors and [`Err(ParseError)`] if otherwise.
  ///
  /// # Example
  ///
  /// ```
  /// match spec.parse() {
  ///     Ok(args) => {
  ///         // do stuff with the arguments
  ///     }
  ///     Err(err) => eprintln!("{:?}", err),
  /// }
  /// ```
  pub fn parse(&self) -> Result<Args> {
    let mut bools: HashMap<String, bool> = HashMap::new();
    let mut ints: HashMap<String, i64> = HashMap::new();
    let mut uints: HashMap<String, u64> = HashMap::new();
    let mut strs: HashMap<String, String> = HashMap::new();
    let mut loan_args: Vec<String> = Vec::new();
    let mut args = std::env::args().skip(1).peekable();

    while let Some(arg) = args.next() {
      let mut chars = arg.chars().peekable();
      if chars.peek() == Some(&'-') {
        chars.next();
        if chars.peek() == Some(&'-') {
          chars.next();
        }
        let arg_name: String = chars.collect();
        let arg_type = *self
          .args
          .get(&arg_name)
          .ok_or(ParseError::UnknownArgument(arg_name.clone()))?;
        match arg_type {
          ArgType::Boolean => parse_bool(arg_name, &mut args, &mut bools),
          ArgType::Integer => parse_arg(arg_name, arg_type, &mut args, &mut ints)?,
          ArgType::UInteger => parse_arg(arg_name, arg_type, &mut args, &mut uints)?,
          ArgType::String => parse_arg(arg_name, arg_type, &mut args, &mut strs)?,
        }
      } else {
        loan_args.push(chars.collect());
      }
    }

    Ok(Args::new(bools, ints, uints, strs, loan_args))
  }
}

fn parse_arg<T: std::str::FromStr>(
  arg_name: String,
  arg_type: ArgType,
  args: &mut ArgIter,
  dict: &mut HashMap<String, T>,
) -> Result<()> {
  let arg_str = args
    .next()
    .ok_or(ParseError::MissingParameter(arg_name.clone(), arg_type))?;
  dict.insert(
    arg_name.clone(),
    arg_str.parse::<T>().or(Err(ParseError::InvalidParameter(
      arg_name.clone(),
      arg_type,
      arg_str,
    )))?,
  );
  Ok(())
}

fn parse_bool(arg_name: String, args: &mut ArgIter, bools: &mut HashMap<String, bool>) {
  let value = if args.peek() == Some(&"false".to_string()) {
    args.next();
    false
  } else if args.peek() == Some(&"true".to_string()) {
    args.next();
    true
  } else {
    true
  };
  bools.insert(arg_name, value);
}

impl std::fmt::Debug for ArgSpec {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_map().entries(self.args.iter()).finish()
  }
}

/// Enumerates all data types that are handled by [`ArgSpec::parse()`].
#[derive(Copy, Clone, Debug)]
pub enum ArgType {
  Boolean,
  Integer,
  UInteger,
  String,
}

/// Builder type for [`ArgSpec`].
pub struct ArgSpecBuilder {
  args: HashMap<String, ArgType>,
}

impl ArgSpecBuilder {
  /// Completes building the [`ArgSpec`] and returns it.
  ///
  /// # Example
  ///
  /// ```
  /// let spec = ArgSpec::build()
  ///     .unsigned_integer("chickens")
  ///     .done();
  /// ```
  pub fn done(self) -> ArgSpec {
    ArgSpec { args: self.args }
  }

  /// Little Wrapper function that will complete building the [`ArgSpec`]
  /// and immediately call [`parse()`].
  ///
  /// # Example
  ///
  /// ```
  /// let args = ArgSpec::build()
  ///     .boolean("fullscreen")
  ///     .boolean("vsync")
  ///     .string("username")
  ///     .parse()?;
  /// ```
  pub fn parse(self) -> Result<Args> {
    self.done().parse()
  }

  /// Adds a boolean argument to the [`ArgSpec`].
  ///
  /// # Example
  ///
  /// ```
  ///  let spec = ArgSpec::build().boolean("vsync").done();
  ///  assert_eq!(spec.has_arg("vsync", ArgType::Boolean), true);
  /// ```
  pub fn boolean(mut self, name: impl Into<String>) -> ArgSpecBuilder {
    self.args.insert(name.into(), ArgType::Boolean);
    self
  }

  /// Adds an i64 argument to the [`ArgSpec`].
  ///
  /// # Exmaple
  ///
  /// ```
  /// let spec = ArgSpec::build().integer("num-bananas").done();
  /// assert_eq!(spec.has_arg("num-bananas", ArgType::Integer), true);
  /// ```
  pub fn integer(mut self, name: impl Into<String>) -> ArgSpecBuilder {
    self.args.insert(name.into(), ArgType::Integer);
    self
  }

  /// Adds a u64 argument to the [`ArgSpec`].
  ///
  /// # Exmaple
  ///
  /// ```
  /// let spec = ArgSpec::build().unsigned_integer("screen-width").done();
  /// assert_eq!(spec.has_arg("screen-width", ArgType::UInteger), true);
  /// ```
  pub fn unsigned_integer(mut self, name: impl Into<String>) -> ArgSpecBuilder {
    self.args.insert(name.into(), ArgType::UInteger);
    self
  }

  /// Adds a String argument to the [`ArgSpec`].
  ///
  /// # Exmaple
  ///
  /// ```
  /// let spec = ArgSpec::build().string("MOD").done();
  /// assert_eq!(spec.has_arg("MOD", ArgType::String), true);
  /// ```
  pub fn string(mut self, name: impl Into<String>) -> ArgSpecBuilder {
    self.args.insert(name.into(), ArgType::String);
    self
  }
}