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
use super::Level;
use clap::Clap;
use std::{fs::File, io::Read, str::FromStr};

/// command line arguments
#[derive(Default, Clap, Debug)]
#[clap(version = "0.1.7")]
pub struct Args {
    /// quiz name
    #[clap(long = "name")]
    quiz_name: Option<String>,

    /// quiz id
    #[clap(long = "id")]
    quiz_id: Option<u64>,

    /// random pick one
    #[clap(short, long)]
    random: bool,

    /// interact or not
    #[clap(short)]
    interact: bool,

    /// difficulty of quiz
    #[clap(short, long)]
    level: Option<String>,

    /// show code snippet
    #[clap(short, long = "code")]
    code_snippet: Option<String>,

    /// template string
    #[clap(long = "temp-str")]
    temp_str: Option<String>,

    /// template file
    #[clap(long = "temp-file")]
    temp_file: Option<String>,

    /// token string
    #[clap(long = "token")]
    token: Option<String>,
}

impl Args {
    pub fn name(&self) -> &Option<String> {
        &self.quiz_name
    }

    pub fn if_random(&self) -> bool {
        self.random
    }

    pub fn if_interact(&self) -> bool {
        self.interact
    }

    pub fn quiz_id(&self) -> &Option<u64> {
        &self.quiz_id
    }

    pub fn level(&self) -> Option<Level> {
        match self.level {
            Some(ref s) => Level::from_str(s).map_or_else(
                |e| {
                    println!("{:?}", e.to_string());
                    None
                },
                |a| Some(a),
            ),
            None => None,
        }
    }

    pub fn if_show_code_snippet(&self) -> &Option<String> {
        &self.code_snippet
    }

    /// give template string, if has template file instead of string
    /// use template file prior.
    pub fn template(&self) -> Option<String> {
        if let Some(filepath) = &self.temp_file {
            let mut f = match File::open(filepath) {
                Ok(f) => f,
                Err(e) => panic!("read temp file has issue: {}", e),
            };
            let mut result = String::new();
            f.read_to_string(&mut result).unwrap();
            // update temp_str with file
            Some(result)
        } else {
            self.temp_str.clone()
        }
    }

    pub fn token(&self) -> &Option<String> {
        &self.token
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_level_parse() {
        let a = Args::parse_from(["a", "-l", "e"]);
        dbg!(a);
    }
}