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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//! Example:
//!
//! ```rust
//! use rargsxd::*;
//!
//! fn main() {
//!     let mut args = ArgParser::new("program_lol");
//!     args.author("BubbyRoosh")
//!         .version("0.1.0")
//!         .copyright("Copyright (C) 2021 BubbyRoosh")
//!         .info("Example for simple arg parsing crate OwO")
//!         .require_args(true) // Makes the program print help and exit if there are no arguments passed
//!         .args(
//!             vec!(
//!                 Arg::new("test")
//!                     .short("t")
//!                     .help("This is a test flag")
//!                     .flag(false),
//!                 Arg::new("monke")
//!                     .short("m")
//!                     .help("This is a test option")
//!                     .option("oo"),
//!             )
//!         )
//!         .parse();
//!
//!     // If "-t" or "--test" is passed, this will run
//!     if args.get_flag("test").unwrap() {
//!         println!("Hello, world!");
//!     }
//!
//!     // This will be "oo" unless "--monke" or "-m" is passed with a string argument
//!     println!("{}", args.get_option("monke").unwrap());
//! }
//! ```

// Copyright (C) 2021 BubbyRoosh
use std::{env, process};

#[derive(Clone, PartialEq)]
pub enum ArgType {
    /// Only used for initialization. Will panic if there's any unknown ArgTypes when initializing.
    Unknown,
    Flag(bool),
    Option_(String),
}

impl ArgType {
    pub fn new(string: Option<String>) -> Self {
        match string {
            Some(s) => Self::Option_(s),
            None => Self::Flag(false),
        }
    }
}

#[derive(Clone)]
pub struct Arg {
    name: String,
    short: String,
    help: String,
    typ: ArgType,
}

impl Arg {
    pub fn new(name: &str) -> Self {
        let name = String::from(name);
        Self {
            name,
            short: String::new(),
            help: String::new(),
            typ: ArgType::Unknown,
        }
    }

    pub fn flag(&mut self, val: bool) -> &mut Self {
        self.typ = ArgType::Flag(val);
        self
    }

    pub fn option(&mut self, val: &str) -> &mut Self {
        self.typ = ArgType::Option_(String::from(val));
        self
    }

    pub fn help(&mut self, help: &str) -> &mut Self {
        self.help = String::from(help);
        self
    }

    pub fn short(&mut self, short: &str) -> &mut Self {
        self.short = String::from(short);
        self
    }
}

pub struct ArgParser {
    name: String,
    author: String,
    version: String,
    copyright: String,
    info: String,
    usage: String,
    flags: Vec<Arg>,
    options: Vec<Arg>,
    require_args: bool,
}

impl ArgParser {
    pub fn parse(&mut self) -> &mut Self {
        let args: Vec<_> = env::args().collect();
        self.parse_args(args);
        self
    }

    pub fn parse_args(&mut self, args: Vec<String>) -> &mut Self {
        if args.len() == 1 && self.require_args {
            self.print_help();
            process::exit(1);
        }

        for (idx, arg) in args.iter().enumerate() {
            if arg.starts_with("--") {
                let arg = String::from(&arg[2..]);
                if arg == "help" {self.print_help();process::exit(0);}
                else if arg == "version" {println!("{} {}", self.name, self.version);process::exit(0);}
                for flag in self.flags.iter_mut() {
                    if flag.name == arg {
                        // In theory this will always be a Flag because of the args() method
                        if let ArgType::Flag(boolean) = flag.typ {
                            flag.flag(!boolean);
                        }
                    }
                }
                for option in self.options.iter_mut() {
                    if option.name == arg {
                        let next = args.iter().nth(idx + 1);
                        match next {
                            Some(next) => if !next.starts_with("-") {
                                option.option(&next);
                            },
                            None => {},
                        }
                    }
                }
            } else if arg.starts_with("-") {
                let arg = String::from(&arg[1..]);
                if arg == "h" {self.print_help();process::exit(1);}
                else if arg == "v" {println!("{} {}", self.name, self.version);process::exit(0);}
                for flag in self.flags.iter_mut() {
                    if flag.short == arg {
                        // In theory this will always be a Flag because of the args() method
                        if let ArgType::Flag(boolean) = flag.typ {
                            flag.flag(!boolean);
                        }
                    }
                }
                for option in self.options.iter_mut() {
                    if option.short == arg {
                        let next = args.iter().nth(idx + 1);
                        match next {
                            Some(next) => if !next.starts_with("-") {
                                option.option(&next);
                            },
                            None => {},
                        }
                    }
                }
            }
        }
        self
    }

    pub fn get_option(&self, name: &str) -> Option<String> {
        for option in self.options.clone() {
            if option.name == name {
                if let ArgType::Option_(string) = option.typ {
                    return Some(string);
                }
                break;
            }
        }
        None
    }

    pub fn get_flag(&self, name: &str) -> Option<bool> {
        for flag in self.flags.clone() {
            if flag.name == name {
                if let ArgType::Flag(boolean) = flag.typ {
                    return Some(boolean);
                }
                break;
            }
        }
        None
    }

    pub fn new(name: &str) -> Self {
        let mut s = Self {
            name: String::from(name),
            author: String::new(),
            version: String::new(),
            copyright: String::new(),
            info: String::new(),
            usage: format!("{} [flags] [options]", name),
            flags: Vec::new(),
            options: Vec::new(),
            require_args: false,
        };
        s.args(vec!(
            Arg::new("help")
                .short("h")
                .help("Prints the help dialog")
                .flag(false),
            Arg::new("version")
                .short("v")
                .help("Prints the version")
                .flag(false),
        ));
        s
    }

    pub fn print_help(&self) {
        println!("{} {}\n{}\n{}\n{}", self.name, self.version, self.author, self.info, self.copyright);
        println!("\nUsage:\n\t{}", self.usage);

        if self.flags.len() > 0 {
            println!("\nFlags:");
            self.flags.iter().for_each(|flag| {
                println!("\t-{}, --{}\t{}", flag.short, flag.name, flag.help);
            });
        }

        if self.options.len() > 0 {
            println!("\nOptions:");
            self.options.iter().for_each(|opt| {
                println!("\t-{}, --{}\t{}", opt.short, opt.name, opt.help);
            });
        }
    }

    pub fn name(&mut self, name: &str) -> &mut Self {
        self.name = String::from(name);
        self
    }

    pub fn author(&mut self, author: &str) -> &mut Self {
        self.author = String::from(author);
        self
    }

    pub fn version(&mut self, version: &str) -> &mut Self {
        self.version = String::from(version);
        self
    }

    pub fn copyright(&mut self, copyright: &str) -> &mut Self {
        self.copyright = String::from(copyright);
        self
    }

    pub fn info(&mut self, info: &str) -> &mut Self {
        self.info = String::from(info);
        self
    }

    pub fn args(&mut self, args: Vec<&mut Arg>) -> &mut Self {
        for arg in args {
            match arg.typ {
                ArgType::Unknown => panic!("No Args can have type Unknown!"),
                ArgType::Flag(_) => self.flags.push(arg.clone()),
                ArgType::Option_(_) => self.options.push(arg.clone()),
            }

        }
        self
    }

    pub fn require_args(&mut self, require: bool) -> &mut Self {
        self.require_args = require;
        self
    }
}