eastwind_blogger/utils/
bin.rs

1use colored::Colorize;
2use std::error;
3use std::fmt::Display;
4
5#[derive(Debug)]
6pub struct ProgramConfig {
7    pub server: bool,
8    pub watch: bool,
9    pub directory: String,
10    pub port: Option<u16>,
11}
12
13#[derive(Debug)]
14struct ProgramError {
15    msg: String,
16}
17impl error::Error for ProgramError {}
18impl Display for ProgramError {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        write!(f, "{}", self.msg)
21    }
22}
23
24impl ProgramConfig {
25    pub fn new() -> Self {
26        Self {
27            server: false,
28            watch: false,
29            directory: String::from("blogs"),
30            port: None,
31        }
32    }
33
34    pub fn check(&self) -> Result<(), Box<dyn error::Error>> {
35        // if !self.server && self.watch {
36        //     eprintln!("[ERROR] `-w` cannot be set when `-s` not present!");
37        //     return Err(Box::new(ProgramError {
38        //         msg: String::from("Options not acceptable!"),
39        //     }));
40        // }
41
42        Ok(())
43    }
44}
45
46pub fn parse_options(ops: &Vec<String>) -> ProgramConfig {
47    let mut config = ProgramConfig::new();
48
49    let mut i = 0;
50    while i < ops.len() {
51        match ops[i].as_str() {
52            "--server" | "-s" => config.server = true,
53            "--watch" | "-w" => config.watch = true,
54            "--dir" | "-d" => {
55                if i < ops.len() - 1 {
56                    config.directory = ops[i + 1].clone();
57                    i += 1;
58                } else {
59                    panic!(
60                        "[{}] `--dir|-d` expects a relative directory from working directory",
61                        label_red!("ERROR")
62                    );
63                }
64            }
65            "-p" | "--port" => {
66                if i < ops.len() - 1 {
67                    let p = ops[i + 1].clone();
68                    if let Ok(port) = p.parse::<u16>() {
69                        config.port = Some(port);
70                        i += 1;
71                        continue;
72                    }
73                }
74                panic!(
75                    "[{}] `--port|-p` expects a valid TCP port number",
76                    label_red!("ERROR")
77                );
78            }
79            _ => (),
80        }
81        i += 1;
82    }
83
84    config
85}
86
87#[macro_export]
88macro_rules! label_red {
89    ($str:expr) => {
90        $str.red()
91    };
92}
93#[macro_export]
94macro_rules! label_yellow {
95    ($str:expr) => {
96        $str.yellow()
97    };
98}
99#[macro_export]
100macro_rules! label_green {
101    ($str:expr) => {
102        $str.green()
103    };
104}
105
106#[allow(unused_imports)]
107pub(crate) use label_green;
108#[allow(unused_imports)]
109pub(crate) use label_red;
110#[allow(unused_imports)]
111pub(crate) use label_yellow;