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
use regex::Regex;
use std::borrow::Cow;
use std::error::Error;
use std::fs;
use std::path::Path;
use structopt::StructOpt;
fn parse_re(src: &str) -> Result<Regex, regex::Error> {
Regex::new(src)
}
#[derive(StructOpt, Debug)]
#[structopt(name = "qesp")]
pub struct Config {
#[structopt(default_value = ".")]
pub dir: String,
#[structopt(long = "recursive", short = "r")]
pub recursive: bool,
#[structopt(default_value = "[ ()]", long = "pattern", short = "p", parse(try_from_str = parse_re))]
pub pattern: Regex,
}
fn trim<'a>(from: &'a str, pat: &Regex) -> Cow<'a, str> {
pat.replace_all(from, "")
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
qesp(config.dir, config.recursive, &config.pattern)
}
fn qesp(dir: String, recursive: bool, pattern: &Regex) -> Result<(), Box<dyn Error>> {
let target = fs::read_dir(dir)?;
for file in target {
let file = file?;
let from = String::from(file.path().to_str().unwrap());
let path = &*trim(&from, pattern);
fs::rename(&from, path)?;
if Path::new(path).is_dir() & recursive {
let dir = String::from(path);
qesp(dir, recursive, pattern)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn trim_a_line() {
let line = "annoying name for dir(very annoying)";
let to = trim(line, &Regex::new("[ ()]").unwrap());
assert_eq!("annoyingnamefordirveryannoying", to)
}
}