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)
}
}