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

/// Remove directories, if they are empty.
#[derive(Parser, Clone, Debug)]
#[clap(author, version, about)]
pub struct Rmdir {
    /// Remove directory and its ancestors.
    #[clap(long, short)]
    pub parents: bool,
    /// Ignore failures that are solely because a directory is non-empty.
    #[clap(long, short)]
    pub ignore_fail_on_non_empty: bool,
    /// Output a diagnostic every time a directory is removed.
    #[clap(long, short)]
    pub verbose: bool,
    /// List of directories to remove.
    #[clap(required = true)]
    pub directories: Vec<PathBuf>,
}

impl Rmdir {
    /// Run command
    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(())
    }

    /// Remove all parents and the directory
    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(())
    }

    /// Remove directory
    pub fn remove_directory(&self, dir: &Path) -> Result<(), io::Error> {
        if self.verbose {
            eprintln!("rmdir: removing directory, {dir:?}");
        }

        match remove_dir(dir) {
            Ok(()) => Ok(()),
            // Match on io::ErrorKind::DirectoryNotEmpty once library features 'io_error_more'
            // stabilises. This is a hack for now, it is not pretty but it works.
            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>)
    }
}