code_it_later_rs/
config.rs

1use regex::{Regex, RegexBuilder};
2use std::collections::HashMap;
3use std::ffi::OsString;
4
5use std::fs::File;
6use std::io::Read;
7use std::sync::{LazyLock, Mutex};
8
9use super::args::Args;
10
11/// Inner dictionary
12const DICT: &'static str = r#"
13{
14"rs":["//", "/\\*"],
15"go":["//", "/\\*", "// "],
16"lisp":[";"],
17"asd":[";"],
18"asdf":[";"],
19"py":["\\#"],
20"hs":["-- "],
21"el":[";"],
22"clj":[";"],
23"js":["//"]
24}
25"#;
26
27static TABLE: LazyLock<Mutex<HashMap<String, Vec<String>>>> =
28    LazyLock::new(|| Mutex::new(serde_json::from_str(DICT).unwrap()));
29
30pub static REGEX_TABLE: LazyLock<Mutex<HashMap<String, Regex>>> = LazyLock::new(|| {
31    Mutex::new({
32        let a = TABLE.lock().unwrap();
33        a.iter()
34            .map(|(k, v)| (k.clone(), Regex::new(&make_regex(v)).unwrap()))
35            .collect()
36    })
37});
38
39pub static KEYWORDS_REGEX: LazyLock<Mutex<Option<Regex>>> = LazyLock::new(|| Mutex::new(None));
40
41/// Update static table with new raw_json str
42fn update_table(raw_json: &str) {
43    let new_table: HashMap<String, Vec<String>> = serde_json::from_str(raw_json).unwrap();
44
45    let mut table = TABLE.lock().unwrap();
46    for (k, v) in new_table.iter() {
47        table.insert(k.clone(), v.clone());
48    }
49
50    let mut re_table = REGEX_TABLE.lock().unwrap();
51    table
52        .iter()
53        .map(|(k, v)| (k.clone(), Regex::new(&make_regex(v)).unwrap()))
54        .for_each(|(k, v)| {
55            let _ = re_table.insert(k, v);
56        });
57}
58
59/// Making regex string
60fn make_regex(com_syms: &Vec<String>) -> String {
61    let mut head = String::new();
62    for s in com_syms {
63        head.push('|');
64        head.push_str(s);
65        head.push_str("+");
66    }
67
68    let _ = head.drain(..1).collect::<String>();
69
70    format!("({}):=\\s+(.*)", head)
71}
72
73/// making the keyword regex, case insensitive
74pub(super) fn make_key_regex(keywords: &Vec<String>) {
75    let mut ss = String::new();
76    for s in keywords {
77        ss.push_str(&s);
78        ss.push('|');
79    }
80
81    let _ = ss.drain(ss.len() - 1..).collect::<String>();
82    let mut kk = KEYWORDS_REGEX.lock().unwrap();
83    *kk = Some(
84        RegexBuilder::new(&format!("({}):\\s*(.*)", ss))
85            .case_insensitive(true)
86            .build()
87            .unwrap(),
88    );
89}
90
91pub fn clean_keywords_table() {
92    let mut kk = KEYWORDS_REGEX.lock().unwrap();
93    *kk = None;
94}
95
96#[derive(Clone, Debug)]
97pub(super) enum OutputFormat {
98    None,
99    Json,
100    List,
101}
102
103impl Default for OutputFormat {
104    fn default() -> Self {
105        Self::None
106    }
107}
108
109/// config when running
110#[derive(Default, Debug, Clone)]
111pub struct Config {
112    pub(super) filetypes: Vec<OsString>,
113    pub(super) ignore_dirs: Vec<OsString>,
114    pub(super) files: Vec<String>,
115
116    /// if delete
117    pub(super) delete: bool,
118
119    /// if restore
120    pub(super) restore: bool,
121
122    /// output format
123    pub(super) output: OutputFormat,
124
125    /// show ignored
126    pub(super) show_ignored: bool,
127}
128
129impl From<&Args> for Config {
130    fn from(a: &Args) -> Self {
131        match &a.jsonx {
132            Some(j) => {
133                let mut buf = vec![];
134                File::open(j).unwrap().read_to_end(&mut buf).unwrap();
135                update_table(&String::from_utf8(buf).unwrap());
136            }
137            None => (),
138        }
139
140        match &a.keywords {
141            Some(kk) => make_key_regex(&kk),
142            None => (),
143        }
144
145        let output = match &a.output_format {
146            Some(v) if v.to_lowercase().as_str() == "json" => OutputFormat::Json,
147            Some(v) if v.to_lowercase().as_str() == "list" => OutputFormat::List,
148            _ => OutputFormat::None,
149        };
150
151        Self {
152            filetypes: a.filetypes.clone(),
153            ignore_dirs: a.ignore_dirs.clone(),
154            files: a.targets.clone(),
155
156            delete: a.delete,
157            // delete and restore cannot be true at the same time
158            // and delete has higher priority
159            restore: if a.delete { false } else { a.restore },
160
161            output,
162            show_ignored: a.show_ignore,
163        }
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use regex::Regex;
171
172    #[test]
173    fn test_update_table() {
174        assert_eq!(
175            TABLE.lock().unwrap().get("rs").unwrap(),
176            &vec![String::from("//"), String::from(r#"/\*"#)]
177        );
178
179        assert_eq!(
180            REGEX_TABLE.lock().unwrap().get("rs").unwrap().as_str(),
181            &String::from(r#"(//+|/\*+):=\s+(.*)"#)
182        );
183
184        // update here
185        update_table(r##"{"rs":["//","#"]}"##);
186
187        assert_eq!(
188            TABLE.lock().unwrap().get("rs").unwrap(),
189            &vec![String::from("//"), String::from("#")]
190        );
191
192        assert_eq!(
193            REGEX_TABLE.lock().unwrap().get("rs").unwrap().as_str(),
194            &String::from(r#"(//+|#+):=\s+(.*)"#)
195        );
196
197        // more test
198        update_table(r#"{"rs":["//","/\\*"]}"#);
199
200        assert_eq!(
201            TABLE.lock().unwrap().get("rs").unwrap(),
202            &vec![String::from("//"), String::from("/\\*")]
203        );
204
205        assert_eq!(
206            TABLE.lock().unwrap().get("rs").unwrap(),
207            &vec![String::from("//"), String::from(r#"/\*"#)]
208        );
209
210        assert_eq!(
211            REGEX_TABLE.lock().unwrap().get("rs").unwrap().as_str(),
212            &String::from(r#"(//+|/\*+):=\s+(.*)"#)
213        );
214    }
215
216    #[test]
217    fn test_update_table_with_json() {
218        let mut buf = vec![];
219        File::open("./tests/testcases/test.json")
220            .unwrap()
221            .read_to_end(&mut buf)
222            .unwrap();
223        let ss: &str = &String::from_utf8(buf).unwrap();
224
225        // This means file content equal the pure str
226        // which already test before in test_update_table
227        assert_eq!(
228            serde_json::from_str::<HashMap<String, Vec<String>>>(ss).unwrap(),
229            serde_json::from_str(r#"{"rs":["//","/\\*"]}"#).unwrap() // json reader need one more '/'
230        );
231    }
232
233    #[test]
234    fn test_make_regex() {
235        assert_eq!(
236            make_regex(&vec![String::from("//"), String::from(";")]),
237            String::from(r#"(//+|;+):=\s+(.*)"#)
238        );
239
240        assert_eq!(
241            make_regex(&vec![String::from("//"), String::from(r#"/\*"#)]),
242            String::from(r#"(//+|/\*+):=\s+(.*)"#)
243        );
244    }
245
246    #[test]
247    fn test_regex() {
248        let re = Regex::new(&make_regex(&vec![String::from("--"), String::from(";")])).unwrap();
249        let cap = re.captures("Aabbcc --:= test").unwrap();
250        assert_eq!(&cap[2], "test");
251
252        let cap = re.captures("Aabbcc ;:= test").unwrap();
253        assert_eq!(&cap[2], "test");
254
255        let cap = re.captures("Aabbcc ;;;:= test").unwrap();
256        assert_eq!(&cap[2], "test");
257        assert_eq!(&cap[1], ";;;");
258
259        assert!(re.captures("Aabbcc #:= test").is_none());
260
261        assert!(re.captures("Aabbcc ; test").is_none());
262
263        assert!(re.captures("Aabbcc ; := test").is_none());
264
265        // more tests
266        let re = Regex::new(&make_regex(&vec![
267            String::from("//"),
268            String::from(r#"/\*"#),
269            String::from(r#"// "#),
270        ]))
271        .unwrap();
272        assert!(re.captures("err := test").is_none());
273        assert!(re.captures("err // := test").is_some());
274        assert_eq!(&re.captures("err // := test").unwrap()[1], "// ");
275    }
276
277    #[test]
278    fn test_restore_overwrited_by_delete() {
279        let mut arg: Args = Default::default();
280        arg.delete = true;
281        arg.restore = true;
282        let conf = Config::from(&arg);
283        assert!(conf.delete);
284        assert!(!conf.restore);
285
286        arg.delete = false;
287        arg.restore = true;
288        let conf = Config::from(&arg);
289        assert!(!conf.delete);
290        assert!(conf.restore);
291    }
292}