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
use clap::Parser;
use rustutils_runnable::Runnable;
use std::error::Error;
use std::fs::remove_dir;
use std::io;
use std::path::{Path, PathBuf};
#[derive(Parser, Clone, Debug)]
#[clap(author, version, about)]
pub struct Rmdir {
#[clap(long, short)]
pub parents: bool,
#[clap(long, short)]
pub ignore_fail_on_non_empty: bool,
#[clap(long, short)]
pub verbose: bool,
#[clap(required = true)]
pub directories: Vec<PathBuf>,
}
impl Rmdir {
pub fn run(&self) -> Result<(), io::Error> {
for directory in &self.directories {
if self.parents {
self.remove_parents(directory)?
} else {
self.remove_directory(directory)?
}
}
Ok(())
}
pub fn remove_parents(&self, path: &Path) -> Result<(), io::Error> {
for ancestor in path.ancestors() {
if ancestor.parent().is_some() {
self.remove_directory(ancestor)?;
}
}
Ok(())
}
pub fn remove_directory(&self, dir: &Path) -> Result<(), io::Error> {
if self.verbose {
eprintln!("rmdir: removing directory, {dir:?}");
}
match remove_dir(dir) {
Ok(()) => Ok(()),
Err(error)
if self.ignore_fail_on_non_empty
&& error.kind().to_string() == "directory not empty" =>
{
if self.verbose {
eprintln!("rmdir: ignoring error, '{error}'");
}
Ok(())
}
Err(error) => Err(error),
}
}
}
impl Runnable for Rmdir {
fn run(&self) -> Result<(), Box<dyn Error>> {
self.run().map_err(|e| Box::new(e) as Box<dyn Error>)
}
}