2023-01-16 23:44:21 -05:00
|
|
|
use super::Cmd;
|
2023-02-05 23:50:59 -05:00
|
|
|
use shitbox::args;
|
2023-01-16 23:44:21 -05:00
|
|
|
use clap::{Arg, ArgAction, Command, ValueHint};
|
2023-02-04 08:54:27 -05:00
|
|
|
use std::{error::Error, fs, path::Path};
|
2022-12-20 12:05:21 -05:00
|
|
|
|
2023-01-16 23:44:21 -05:00
|
|
|
#[derive(Debug, Default)]
|
|
|
|
pub struct Rmdir;
|
|
|
|
|
|
|
|
impl Cmd for Rmdir {
|
|
|
|
fn cli(&self) -> clap::Command {
|
|
|
|
Command::new("rmdir")
|
|
|
|
.about("remove directories")
|
|
|
|
.author("Nathan Fisher")
|
|
|
|
.version(env!("CARGO_PKG_VERSION"))
|
|
|
|
.args([
|
|
|
|
Arg::new("parents")
|
|
|
|
.help("remove DIRECTORY and it's ancestors")
|
|
|
|
.short('p')
|
|
|
|
.long("parents")
|
|
|
|
.action(ArgAction::SetTrue),
|
|
|
|
Arg::new("dir")
|
|
|
|
.num_args(1..)
|
|
|
|
.value_name("DIRECTORY")
|
|
|
|
.value_hint(ValueHint::DirPath)
|
|
|
|
.required(true),
|
2023-01-21 18:25:09 -05:00
|
|
|
args::verbose(),
|
2023-01-16 23:44:21 -05:00
|
|
|
])
|
|
|
|
}
|
|
|
|
|
2023-02-04 08:54:27 -05:00
|
|
|
fn run(&self, matches: &clap::ArgMatches) -> Result<(), Box<dyn std::error::Error>> {
|
2023-01-16 23:44:21 -05:00
|
|
|
if let Some(directories) = matches.get_many::<String>("dir") {
|
|
|
|
for dir in directories {
|
|
|
|
if matches.get_flag("parents") {
|
|
|
|
let path = Path::new(dir);
|
|
|
|
rmdir_recursive(path, matches.get_flag("verbose"))?;
|
|
|
|
} else {
|
|
|
|
fs::remove_dir(dir)?;
|
|
|
|
if matches.get_flag("verbose") {
|
|
|
|
println!("rmdir: removing directory, '{dir}'");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-02-05 23:50:59 -05:00
|
|
|
fn path(&self) -> Option<shitbox::Path> {
|
|
|
|
Some(shitbox::Path::Bin)
|
2023-01-16 23:44:21 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn rmdir_recursive(dir: &Path, verbose: bool) -> Result<(), Box<dyn Error>> {
|
|
|
|
fs::remove_dir(dir)?;
|
|
|
|
if verbose {
|
|
|
|
println!("rmdir: removing directory, '{}'", dir.display());
|
|
|
|
}
|
|
|
|
if let Some(parent) = dir.parent() {
|
|
|
|
if let Some(name) = parent.to_str() {
|
|
|
|
if !name.is_empty() {
|
|
|
|
rmdir_recursive(parent, verbose)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|