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
//! The arguments of codeitlater are using

use clap::Parser;
use std::{
    ffi::OsString,
    fs::File,
    io::{BufRead, BufReader},
};

/// Command Line Args
#[derive(Default, Parser, Debug)]
#[command(author = "ccQpein", version, about)]
pub struct Args {
    /// What are the filetypes you want to scan.
    #[arg(short, long)]
    pub(crate) filetypes: Vec<OsString>,

    /// The folder name should ignored
    #[arg(short = 'x', long = "ignore-dir")]
    pub(crate) ignore_dirs: Vec<OsString>,

    /// Keywords
    #[arg(short, long)]
    pub(crate) keywords: Option<Vec<String>>,

    /// Expand dictionary json file path
    #[arg(short, long)]
    pub(crate) jsonx: Option<String>,

    /// files/dirs input directly
    #[arg(value_name = "files/dirs", default_value = ".")]
    pub(crate) targets: Vec<String>,

    /// delete the crumbs
    #[arg(short = 'D', long = "del")]
    pub(crate) delete: bool,

    /// format command after delete crumbs
    #[arg(long = "fmt")]
    pub(crate) fmt_command: Option<String>,

    /// output format: json
    #[arg(short = 'O', long = "output-format")]
    pub(crate) output_format: Option<String>,

    /// show all ignored crumbs
    #[arg(long = "show-ignored", default_value = "false")]
    pub(crate) show_ignore: Option<bool>,
}

impl Args {
    /// cover this args with other, self values totally rewrotten by other
    /// if both of args have same fields. Except ignore dirs, they are merged
    pub fn cover(&mut self, mut other: Self) {
        if other.filetypes.len() != 0 {
            self.filetypes = other.filetypes
        }

        if other.ignore_dirs.len() != 0 {
            self.ignore_dirs.append(&mut other.ignore_dirs)
        }

        if other.keywords.is_some() {
            self.keywords = other.keywords
        }

        if other.jsonx.is_some() {
            self.jsonx = other.jsonx
        }

        if other.targets.len() != 0 {
            self.targets = other.targets;
        }

        if other.delete {
            self.delete = other.delete
        }

        if other.fmt_command.is_some() {
            self.fmt_command = other.fmt_command
        }

        if other.output_format.is_some() {
            self.output_format = other.output_format
        }

        if other.show_ignore.is_some() {
            self.show_ignore = other.show_ignore
        }
    }

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

fn split_space_exclude_those_in_inner_string(s: &str) -> Result<Vec<String>, String> {
    let mut result = vec![];
    let mut buf = vec![];
    let mut in_string = false;

    for b in s.bytes() {
        if b == b' ' && !in_string {
            if !buf.is_empty() {
                result.push(String::from_utf8(buf).map_err(|e| e.to_string())?);
                buf = vec![];
            }
        } else {
            if b == b'"' {
                in_string ^= true;
                continue;
            }
            buf.push(b);
        }
    }

    if !buf.is_empty() {
        result.push(String::from_utf8(buf).map_err(|e| e.to_string())?);
    }

    Ok(result)
}

fn read_config_raw_content<R: BufRead>(content: R) -> Vec<String> {
    let buf_reader = BufReader::new(content);
    let mut a = vec!["codeitlater".to_string()];
    a.append(
        &mut buf_reader
            .lines()
            .filter_map(|l| {
                let ll = l.unwrap();
                if ll.is_empty() {
                    None
                } else {
                    Some(split_space_exclude_those_in_inner_string(&ll).unwrap())
                }
            })
            .flatten()
            .collect::<Vec<String>>(),
    );
    a
}

pub fn parse_from_current_path_config() -> Option<Args> {
    match File::open(".codeitlater") {
        Ok(f) => Some(Args::parse_from(read_config_raw_content(BufReader::new(f)))),
        Err(_e) => {
            //println!("{}", _e.to_string());
            None
        }
    }
}

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

    #[test]
    fn test_parse_from_iter() {
        let args = vec!["codeitlater", "-x", "dd"];
        assert_eq!(Args::parse_from(args).ignore_dirs, vec!["dd"]);

        let args = vec!["codeitlater", "-x", "dd", "-x", "ff"];
        assert_eq!(Args::parse_from(args).ignore_dirs, vec!["dd", "ff"]);

        // if there are some options, "--" is required
        let args = vec!["codeitlater", "-x", "dd", "--", "a", "b", "c"];
        assert_eq!(
            Args::parse_from(args).targets,
            vec!["a".to_string(), "b".to_string(), "c".to_string()]
        );

        let args = vec!["codeitlater", "--", "a", "b", "c"];
        assert_eq!(
            Args::parse_from(args).targets,
            vec!["a".to_string(), "b".to_string(), "c".to_string()]
        );

        let args = vec!["codeitlater", "a", "b", "c"];
        assert_eq!(
            Args::parse_from(args).targets,
            vec!["a".to_string(), "b".to_string(), "c".to_string()]
        );

        let args = vec!["codeitlater", "--del", "--", "a", "b", "c"];
        assert_eq!(
            Args::parse_from(args).targets,
            vec!["a".to_string(), "b".to_string(), "c".to_string()]
        );

        let args = vec!["codeitlater", "-x", "dd", "-x", "ff", "-D", "a", "b", "c"];
        let args = Args::parse_from(args);
        assert_eq!(
            args.targets,
            vec!["a".to_string(), "b".to_string(), "c".to_string()]
        );
        assert_eq!(args.delete, true);
        assert_eq!(args.ignore_dirs, vec!["dd", "ff"]);
    }

    #[test]
    fn test_read_current_path_config() {
        let content = "
-x target

-k    TODO"
            .as_bytes();
        //dbg!(read_config_raw_content(content));
        assert_eq!(
            vec!["codeitlater", "-x", "target", "-k", "TODO"],
            read_config_raw_content(content)
        );
    }

    /// fmt command is the shell command, so it has to be string
    #[test]
    fn test_parse_the_fmt_string() {
        let args = vec!["codeitlater", "--fmt", "aaa bbb"];
        assert_eq!(Args::parse_from(args).fmt_command.unwrap(), "aaa bbb");

        let args = vec!["codeitlater", "--fmt", r#""cargo fmt""#];
        assert_eq!(
            Args::parse_from(args).fmt_command.unwrap(),
            r#""cargo fmt""#
        )
    }
}