easy_arg 0.2.6

EasyArg read variables from command line arguments/system envrioment/.env files
Documentation
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! # EasyArg
//!
//! EasyArg parse args from command line arguments/system envrioment/.env files
//!
//! ### You will read:
//! - how to set
//! - how to get
//! - how to alias
//! - how to add help description
//!
//! ## How to set
//!  
//! ### 1.Command line:
//! ```bash
//! your_app -p --name=some_one -- invalid --hello "world"
//! ```
//! will produce:
//!
//! ```
//! {
//!     "name": "some_one",
//!     "hello": "world",
//!     "p": "true",
//! }
//! ```
//!
//! rule:
//! ```
//! --p = "abc" ✔
//! --p=abc     ✔
//! --p abc     ✔
//! --p -- abc  ✔ // p = "abc",-- will be ignored
//! -p          ✔ // p = "true"
//! -p=abc      ✔
//! --p         ❌
//! ```
//!
//!
//! ### 2.system envrironment variable
//! ```bash
//! export SOME_VAR=123
//! ```
//!
//! Then you can access it by:
//!
//! ```
//! let easy = EasyArg::new();
//! easy.get_string("SOME_VAR") // "123"
//! ```
//!
//! ### 3..env files
//! You can use .env file in diffrent ways:
//!
//! - pass `-e`/`--envfile`/`-envfile` args
//!
//! If no envfile args, it will search (in order):
//!
//! 1. current_working_directory/.env
//! 2. current_working_directory/.easy_arg.env
//! 3. home_directory/.easy_arg.env
//!
//! #### If you want to customize the .env filename, use
//!
//! ```
//! EasyArg::new_with_env("your_file_name");
//! ```
//!
//! It will search:
//! - current_working_directory/your_file_name.env
//! - home_directory/your_file_name.env
//!
//! .env example:
//!
//! <span style="color: cyan;">(docs.rs couldn't display .env code properly, read it on [crates.io](https://crates.io/crates/easy_arg))</span>
//!
//! ```
//! DIR = abc
//! DIR2="dfdadfasfasf" # this is a comment
//! GOOD
//! # THIS IS A COMMENT LINE
//!     =
//!HHD = ${HOME}/abc/${NOT_EXIST}
//!OK=
//! ```
//!
//! will produce
//!
//! ```
//! {
//!     "OK": "true",
//!     "DIR": "abc",
//!     "DIR2": "dfdadfasfasf",
//!     "HHD": "/home/xxx/abc/${NOT_EXIST}",
//!     "GOOD": "true",
//! }
//! ```
//!
//!
//! ## How to get
//!
//! Note: All variables will be parsed to string.
//!
//! `easy` represents an instance of `EasyArg`.
//!
//! ### 1. You need the raw string
//! ```
//! easy.raw_value("KEY");
//! ```
//!
//! ### 2. You need a string, event it doesn't exist
//! ```
//! easy.get_string("KEY");
//! ```
//!
//! ### 3. panic if the string doesn't exist
//! ```
//! easy.must_get_string("IMPORTANT_KEY");
//! ```
//!
//! ### 4. You need bool value
//! if you didn't provid a value for the key, it defaults to true.
//! Only `"false"`,`"False"`,`"FALSE"`,`"0"`,`"null"`,`"NULL"`,`"Null"` will be parsed to false.
//! ```
//! easy.get_bool("KEY");
//! ```
//!
//! ### 5. You need a vec
//! ```
//! // --list=a,b,c
//! easy.get_vec("KEY") // the result: vec!["a", "b", "c"]
//! ```
//!
//! ## How to alias
//! ```
//! your_app -p --s=xbox
//! ```
//! your rust code
//!
//! ```
//! easy.alias("p", "PS5")
//!
//! easy.to_string("PS5") // "true"
//! easy.to_string("p") // "true"
//! ```
//!
//! ## How to add help description
//!
//! ```
//! easy.desc_str("a", "description")
//! easy.desc_flag("b", "description")
//! ```
//!
//! output:
//! ```
//! Executable: target/debug/xxx
//! -- a           description
//! - b           description
//! ```
//!
//!

use std::{collections::HashMap, env};

use regex::Regex;

pub use crate::{
    envfile::{load_env, Section},
    utils::to_bool,
};
mod envfile;
mod utils;

#[derive(Debug, PartialEq, PartialOrd)]
pub enum ArgType {
    /// -
    Hyphen,
    /// --
    DoubeHyPhen,
}

#[derive(Debug)]
pub struct EasyArg {
    config: HashMap<String, String>,
    invalid: Vec<String>,
    _desc: HashMap<String, (ArgType, String)>,
    _alias: HashMap<String, String>,
    sections: Vec<Section>,
    _section_key: Option<String>,
    _sub_section_key: Option<String>,
}

impl EasyArg {
    pub fn new() -> EasyArg {
        EasyArg::new_with_env(".easy_arg")
    }

    /// create an EasyArg instance.
    ///
    /// It will:
    ///
    /// - parse command line arguments
    ///
    /// - read environment variables
    ///
    /// - load .env files
    ///
    /// # Arguments
    ///
    /// - env_name - &str The default env file name to search if no env args are found
    ///
    /// For example:
    ///
    /// set env_name to ".xxx" will search:
    ///
    /// - current_working_directory/.xxx.env
    /// - $HOME/.xxx.env
    ///
    pub fn new_with_env(env_name: &str) -> EasyArg {
        let mut config: HashMap<String, String> = HashMap::new();
        let mut invalid: Vec<String> = vec![];

        fn add_key_value(conf: &mut HashMap<String, String>, key: &str, value: &str) {
            let key = key.replacen("-", "", 2);
            conf.insert(key, value.to_string());
        }

        fn make_invalid(conf: &mut Vec<String>, key: String) {
            conf.push(key);
        }

        let has_key = Regex::new(r"^--\w").expect("create -- regex");
        let has_flag = Regex::new(r"^-\w").expect("create - regex");
        let has_value = Regex::new(r"=").expect("create = regex");

        let mut key = String::new();
        for argument in env::args().skip(1) {
            if argument == "--" || argument == "-" {
                if has_flag.is_match(&argument) {
                    add_key_value(&mut config, &key.to_string(), "true");
                }
                continue;
            }
            let is_eq = has_value.is_match(&argument);
            if has_key.is_match(&argument) || has_flag.is_match(&argument) {
                if key.len() > 0 {
                    if has_key.is_match(&key) {
                        make_invalid(&mut invalid, key)
                    } else if has_flag.is_match(&key) {
                        add_key_value(&mut config, &key.to_string(), "true");
                    }
                    key = "".to_string();
                }
                if is_eq {
                    let keyval: Vec<&str> = argument.split("=").collect();
                    add_key_value(&mut config, keyval[0], keyval[1]);
                } else {
                    key = argument;
                }
            } else {
                if key.len() > 0 {
                    add_key_value(&mut config, &key, &argument);
                    key = "".to_string();
                }
            }
        }

        if key.len() > 0 {
            if has_key.is_match(&key) {
                make_invalid(&mut invalid, key);
            } else if has_flag.is_match(&key) {
                add_key_value(&mut config, &key.to_string(), "true")
            }
        }

        let mut easy = EasyArg {
            config,
            sections: vec![],
            invalid,
            _desc: HashMap::new(),
            _alias: HashMap::new(),
            _section_key: None,
            _sub_section_key: None,
        };

        easy.alias("e", "envfile");
        easy.alias("h", "help");
        easy.desc_flag("help", "show help");

        let env_file = easy.get_string("envfile");
        if env_file.len() > 0 {
            let (mut env_config, secs) = load_env(&env_file);
            env_config.extend(easy.config.clone());
            easy.config = env_config;
            easy.sections = secs;
        } else {
            match EasyArg::load_env(env_name) {
                Some((mut val, secs)) => {
                    val.extend(easy.config.clone());
                    easy.config = val;
                    easy.sections = secs;
                }
                None => {}
            }
        }
        return easy;
    }

    fn load_env(env_name: &str) -> Option<(HashMap<String, String>, Vec<Section>)> {
        match env::current_dir() {
            Ok(pt) => {
                let env_file = format!("{}/{}.env", pt.display(), env_name);
                if std::path::Path::new(&env_file).exists() {
                    return Some(load_env(&env_file));
                }
                let env_file = format!("{}/.env", pt.display());
                if std::path::Path::new(&env_file).exists() {
                    return Some(load_env(&env_file));
                }
                let home = env::var("HOME").expect("home");
                let env_file = format!("{}/{}.env", home, env_name);
                if std::path::Path::new(&env_file).exists() {
                    return Some(load_env(&env_file));
                } else {
                    return None;
                }
            }
            Err(err) => {
                panic!("{:?}", err);
            }
        }
    }

    /// set default section
    pub fn use_section(&mut self, key: &str) {
        if key.len() == 0 {
            self._section_key = None;
        } else {
            self._section_key = Some(key.to_string());
        }
    }

    /// set default sub_section;
    ///
    /// requires call `use_section` first
    pub fn use_sub_section(&mut self, sub_key: &str) {
        if self._section_key.is_none() {
            return;
        }
        if sub_key.len() == 0 {
            self._sub_section_key = None;
        } else {
            self._sub_section_key = Some(sub_key.to_string());
        }
    }

    /// Get the raw string for key
    pub fn raw_value(&self, key: &str) -> Option<String> {
        let mut real_key = key;
        if !self.config.contains_key(key) {
            for (new_key, old_key) in self._alias.iter() {
                if new_key == key {
                    real_key = old_key
                } else if old_key == key {
                    real_key = new_key
                }
            }
        }

        if let Some(val) = self.config.get(real_key) {
            return Some(val.to_string());
        } else {
            // find section config
            let mut section: Option<&Section> = None;
            if let Some(sec_key) = self._section_key.as_ref() {
                if let Some(sub_key) = self._sub_section_key.as_ref() {
                    for sec in self.sections.iter() {
                        if sec.key == *sub_key {
                            if let Some(this_sec_key) = sec.parent.as_ref() {
                                if this_sec_key == sec_key {
                                    section = Some(sec);
                                }
                            }
                        }
                    }
                } else {
                    for sec in self.sections.iter() {
                        if sec.key == *sec_key {
                            section = Some(sec);
                        }
                    }
                }
            }

            if let Some(sec) = section {
                if let Some(val) = sec.data.get(real_key) {
                    return Some(val.to_string());
                }
            }

            // find sys env
            let val = env::var_os(real_key);
            if let Some(val) = val {
                let val2 = val.to_str().expect("os str to str");
                return Some(val2.to_string());
            } else {
                return None;
            }
        }
    }

    /// get string result; return "" if key not exists.
    pub fn get_string(&self, key: &str) -> String {
        match self.raw_value(key) {
            Some(val) => val,
            None => "".to_string(),
        }
    }

    // panics if key not exists
    pub fn must_get_string(&self, key: &str) -> String {
        match self.raw_value(key) {
            Some(val) => val,
            None => {
                panic!("{} doesn't exist", key)
            }
        }
    }

    /// if you didn't provid a value for the key, it defaults to true
    ///
    /// Only `"false" | "False" | "FALSE" | "0" | "null" | "NULL" | "Null" ` will be  parsed to false
    pub fn get_bool(&self, key: &str) -> bool {
        let val = self.raw_value(key);
        match val {
            Some(val) => to_bool(&val),
            None => false,
        }
    }

    /// Get a `Vec<String>`.
    ///
    /// It will parse `a,b,c` to `vec!["a","b","c"]`
    ///
    pub fn get_vec(&self, key: &str) -> Vec<String> {
        if key.len() == 0 {
            return vec![];
        }
        let val = self.raw_value(key);
        match val {
            Some(val) => val.split(",").map(|s| s.to_string()).collect(),
            None => vec![],
        }
    }

    /// set alias name for key
    pub fn alias(&mut self, source_key: &str, new_key: &str) {
        let new_key = new_key.to_string();
        self._alias.entry(new_key).or_insert(source_key.to_string());
    }

    /// get failed parses
    pub fn get_invalid(&self) -> &Vec<String> {
        return &self.invalid;
    }

    /// set description for the key.
    ///
    /// it will add `--` prefix to the key in help message
    pub fn desc_str(&mut self, key: &str, description: &str) {
        self._desc.entry(key.to_string()).or_insert((ArgType::DoubeHyPhen, description.to_string()));
    }

    /// set description for the key.
    ///
    /// it will add `-` prefix to the key in help message
    pub fn desc_flag(&mut self, key: &str, description: &str) {
        self._desc.entry(key.to_string()).or_insert((ArgType::Hyphen, description.to_string()));
    }

    /// show help message
    ///
    /// add more by `desc_str` / `desc_flag`
    pub fn show_help(&self) -> String {
        let mut help = format!("\nExecutable: {:?}\n", env::args().into_iter().next().unwrap()).replace("\"", "");
        let mut desc: Vec<(&String, &(ArgType, String))> = self._desc.iter().map(|f| f).collect();
        desc.sort_by(|a, b| b.1 .0.partial_cmp(&a.1 .0).expect("compare"));
        for (index, (key, value)) in desc.iter().enumerate() {
            let c = match value.0 {
                ArgType::Hyphen => "-",
                ArgType::DoubeHyPhen => "--",
            };
            let mut spliter = "\n";
            if index >= 1 {
                if desc[index - 1].1 .0 != desc[index].1 .0 {
                    spliter = "\n\n";
                }
            }
            let row = format!("{} {: >3} {: <10}  {}", spliter, c, key, value.1);
            help += row.as_str();
        }
        return help.to_string();
    }

    /// get section config
    ///
    pub fn get_section(&self, key: &str) -> Option<Section> {
        for sec in self.sections.iter() {
            if sec.key == key {
                return Some(sec.clone());
            }
        }
        return None;
    }

    /// get sub section config
    ///
    pub fn get_sub_section(&self, key: &str, sub_key: &str) -> Option<Section> {
        for sec in self.sections.iter() {
            if sec.key == sub_key {
                if let Some(parent) = sec.parent.as_ref() {
                    if parent == key {
                        return Some(sec.clone());
                    }
                }
            }
        }
        return None;
    }
}

#[test]
fn write_test() {
    // todo
}