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
use std::{
    ffi::{OsStr, OsString},
    fs, io,
    path::{Path, PathBuf},
};

use thiserror::Error;

use kalavor::Katetime;

pub mod ioers;

use ioers::*;

/// Use single hyphen (`-`) as path to indicate IO from Stdio.
///
/// # Notes
///
/// - Auto time-based unique naming (`auto_tnamed_dst_`) only takes effect when DST is not provided.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseConfig {
    pub allow_from_stdin: bool,
    pub allow_to_stdout: bool,

    pub auto_tnamed_dst_file: bool,
    pub auto_tnamed_dst_dir: bool,

    pub default_extension: OsString,

    /// Disallowed by default. There may be a potential to `open` and `create` the same file at the same time.
    pub allow_inplace: bool,
}

impl ParseConfig {
    pub fn new<S: AsRef<OsStr>>(default_extension: S) -> Self {
        Self {
            allow_from_stdin: true,
            allow_to_stdout: true,
            auto_tnamed_dst_file: true,
            auto_tnamed_dst_dir: true,
            default_extension: default_extension.as_ref().to_owned(),
            allow_inplace: false,
        }
    }

    pub fn new_with_allow_inplace<S: AsRef<OsStr>>(default_extension: S) -> Self {
        Self {
            allow_from_stdin: true,
            allow_to_stdout: true,
            auto_tnamed_dst_file: true,
            auto_tnamed_dst_dir: true,
            default_extension: default_extension.as_ref().to_owned(),
            allow_inplace: true,
        }
    }

    /// # Possible Combinations
    ///
    /// ``` plaintext
    /// SRC => DST:   Stdout,6   File   Dir     NotProvided
    /// Stdin,6          1+2      1      1         1+3,5
    /// File               2      ✓      ✓           3
    /// Dir                ×      ×      ✓           4
    /// ```
    ///
    /// 1. `allow_from_stdin`.
    /// 2. `allow_to_stdout`.
    /// 3. `auto_tnamed_dst_file`.
    /// 4. `auto_tnamed_dst_dir`.
    ///     Note: A directory with specified name will not be created automatically
    ///     (an error will be returned if it does not exist).
    /// 5. Note that [`std::env::current_dir`] will be used as output directory.
    /// 6. *Stdio will be always treated as a file.*
    pub fn parse<P: AsRef<Path>>(
        &self,
        src: P,
        dst: Option<P>,
    ) -> io::Result<Result<IoPairs, ParseError>> {
        enum InnerSource {
            Stdin,
            File(PathBuf),
            Dir(PathBuf),
        }

        enum InnerDrain {
            Stdout,
            File(PathBuf),
            Dir(PathBuf),
            NotExist(PathBuf),
            NotProvided,
        }

        let src = src.as_ref();
        let src = if src.as_os_str() == "-" {
            InnerSource::Stdin
        } else if !src.exists() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!("SRC '{}' does not exist", src.to_string_lossy()),
            ));
        } else {
            let src = fs::canonicalize(src)?;
            if src.is_file() {
                InnerSource::File(src)
            } else {
                InnerSource::Dir(src)
            }
        };

        let dst = dst.as_ref();
        let mut dst = match dst {
            None => InnerDrain::NotProvided,
            Some(dst) => {
                let dst = dst.as_ref();
                if dst.as_os_str() == "-" {
                    InnerDrain::Stdout
                } else if !dst.exists() {
                    InnerDrain::NotExist(dst.to_owned())
                } else {
                    let dst = fs::canonicalize(dst)?;
                    if dst.is_file() {
                        InnerDrain::File(dst)
                    } else {
                        InnerDrain::Dir(dst)
                    }
                }
            }
        };

        if matches!(src, InnerSource::Stdin) && !self.allow_from_stdin {
            return Ok(Err(ParseError::DisallowFromStdin)); // 1
        }
        if matches!(dst, InnerDrain::Stdout) && !self.allow_to_stdout {
            return Ok(Err(ParseError::DisallowToStdout)); // 2
        }
        if matches!(dst, InnerDrain::NotProvided) {
            if matches!(src, InnerSource::Dir(_)) && !self.auto_tnamed_dst_dir {
                return Ok(Err(ParseError::ForbidAutoTnamedDstDir)); // 4
            } else if !self.auto_tnamed_dst_file {
                return Ok(Err(ParseError::ForbidAutoTnamedDstFile)); // 3
            }
        }
        if let InnerDrain::Dir(parent) = &dst {
            if let InnerSource::File(src) = &src {
                if fs::canonicalize(parent)? == fs::canonicalize(src)?.parent().unwrap() {
                    dst = InnerDrain::NotProvided; // 当 DST目录 与 SRC文件所在目录 相同时,切换至 tname
                }
            } else if !self.allow_inplace {
                if let InnerSource::Dir(src) = &src {
                    if fs::canonicalize(parent)? == fs::canonicalize(src)? {
                        return Ok(Err(ParseError::Inplaced));
                    }
                }
            }
        }

        let (src, dst): (Source, Drain) = match src {
            InnerSource::Stdin | InnerSource::File(_) => {
                fn dst_parent_src_name(src: &InnerSource, dst: &InnerDrain) -> io::Result<PathBuf> {
                    let mut parent = match dst {
                        InnerDrain::Dir(parent) => parent.to_owned(),
                        InnerDrain::NotProvided => fs::canonicalize(std::env::current_dir()?)?,
                        _ => unreachable!(),
                    };
                    parent.push(match src {
                        InnerSource::Stdin => OsString::from("stdin"),
                        InnerSource::File(src) => src.file_name().unwrap().into(), // 在调用这个函数时,SRC 已经规范化了
                        InnerSource::Dir(_) => unreachable!(),
                    });

                    Ok(parent)
                }

                (
                    match &src {
                        InnerSource::Stdin => Source::Stdin,
                        InnerSource::File(src) => Source::File(src.clone()),
                        InnerSource::Dir(_) => unreachable!(),
                    },
                    match dst {
                        InnerDrain::Stdout => Drain::Stdout,
                        InnerDrain::File(dst) => Drain::Single(dst),
                        InnerDrain::Dir(_) => Drain::Single(dst_parent_src_name(&src, &dst)?),
                        InnerDrain::NotExist(dst) => Drain::Single(dst),
                        InnerDrain::NotProvided => {
                            // input.png => input-A01123-0456-0789.png
                            // input.jpg => input.jpg-A01123-0456-0789.png

                            let mut dst = dst_parent_src_name(&src, &dst)?;

                            dst.extension()
                                .and_then(|ext| Some(ext == self.default_extension))
                                .unwrap_or(false)
                                .then(|| dst.set_extension("")); // 如果后缀不错,那么就去掉
                            dst.set_file_name(format!(
                                "{}-{}{}",
                                dst.as_os_str().to_string_lossy(),
                                Katetime::now_datetime(),
                                match self.default_extension.is_empty() {
                                    true => String::with_capacity(0),
                                    false =>
                                        format!(".{}", self.default_extension.to_string_lossy()),
                                }
                            ));

                            Drain::Single(dst)
                        }
                    },
                )
            }

            InnerSource::Dir(src) => {
                fn shallow_walk<P: AsRef<Path>>(src: P) -> io::Result<Vec<PathBuf>> {
                    let mut files = fs::read_dir(src)?
                        .filter_map(Result::ok)
                        .filter_map(|p| {
                            p.metadata()
                                .ok()
                                .and_then(|m| m.is_file().then(|| p.path()))
                        })
                        .collect::<Vec<_>>();
                    files.sort_unstable_by(|a, b| b.cmp(a));
                    Ok(files)
                }

                match dst {
                    InnerDrain::Stdout => return Ok(Err(ParseError::ManyToOne)),
                    InnerDrain::File(_) => return Ok(Err(ParseError::ManyToOne)),
                    InnerDrain::Dir(dst) => (Source::Files(shallow_walk(src)?), Drain::Single(dst)),
                    InnerDrain::NotExist(_) => return Ok(Err(ParseError::DstDirNotExist)),
                    InnerDrain::NotProvided => {
                        // ./inputs => ./inputs-A01123-0456-0789
                        let mut dst = src
                            .parent()
                            .ok_or_else(|| {
                                io::Error::new(
                                    io::ErrorKind::PermissionDenied,
                                    format!("parent directory of {src:?} are unavailable"),
                                )
                            })?
                            .to_owned();
                        dst.push(format!(
                            "{}-{}",
                            src.file_name().unwrap().to_string_lossy(),
                            Katetime::now_datetime()
                        ));

                        (Source::Files(shallow_walk(src)?), Drain::Single(dst))
                    }
                }
            }
        };

        Ok(Ok(IoPairs {
            src,
            dst,
            finished: false,
        }))
    }
}

#[non_exhaustive]
#[derive(Error, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParseError {
    #[error("disallow read from stdin")]
    DisallowFromStdin = 1,
    #[error("disallow write to stdout")]
    DisallowToStdout,
    #[error("forbid automatic time-based named DST file")]
    ForbidAutoTnamedDstFile,
    #[error("forbid automatic time-based named DST directory")]
    ForbidAutoTnamedDstDir,

    #[error("there may be a potential to `open` and `create` the same file at the same time")]
    Inplaced,

    #[error("many-to-one map is not allowed")]
    ManyToOne,
    #[error("specified DST directory does not exist")]
    DstDirNotExist,
}

#[derive(Debug)]
pub struct IoPairs {
    src: Source,
    dst: Drain,

    finished: bool,
}

#[derive(Debug, PartialEq, Eq)]
enum Source {
    Stdin,
    File(PathBuf),
    /// 注意文件列表应该是倒过来排序的!这样就能把它们一个个 pop 出来了。
    Files(Vec<PathBuf>),
}

#[derive(Debug, PartialEq, Eq)]
enum Drain {
    Stdout,
    /// 注意这玩意必须手动拼接!(如果 SRC 是 [`Source::Files`] 的话)也就是文件名相同,但父目录不同。
    Single(PathBuf),
}

impl Iterator for IoPairs {
    type Item = Box<dyn InputOutput>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None;
        }

        match &mut self.dst {
            Drain::Stdout => match &mut self.src {
                Source::Stdin => {
                    self.finished = true;
                    Some(Box::new(ClarifiedIo::new(
                        ReadStdin::new(),
                        WriteStdout::new(),
                    )))
                }
                Source::File(src) => {
                    self.finished = true;
                    Some(Box::new(ClarifiedIo::new(
                        ReadFile::new(src),
                        WriteStdout::new(),
                    )))
                }
                Source::Files(_) => unreachable!(),
            },

            Drain::Single(dst) => match &mut self.src {
                Source::Stdin => {
                    self.finished = true;
                    Some(Box::new(ClarifiedIo::new(
                        ReadStdin::new(),
                        WriteFile::new(dst),
                    )))
                }
                Source::File(src) => {
                    self.finished = true;
                    Some(Box::new(ClarifiedIo::new(
                        ReadFile::new(src),
                        WriteFile::new(dst),
                    )))
                }
                Source::Files(srcs) => match srcs.pop() {
                    None => None,
                    Some(src) => {
                        let dst = dst.join(src.file_name().unwrap());
                        Some(Box::new(ClarifiedIo::new(
                            ReadFile::new(src),
                            WriteFile::new(dst),
                        )))
                    }
                },
            },
        }
    }
}

/// 我该怎么做测试?只是简单跑一下`cargo test -- --nocapture`吗?
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        match ParseConfig::new("png").parse(".", None) {
            Err(e) => println!("{e}"),
            Ok(p) => match p {
                Err(e) => println!("{e}"),
                Ok(p) => {
                    let p = p.collect::<Vec<_>>();
                    println!("{p:#?}")
                }
            },
        };
    }
}