rustutils_mkdir/
lib.rs

1use clap::Parser;
2use rustutils_runnable::Runnable;
3use std::error::Error;
4use std::fs::create_dir;
5use std::io;
6use std::path::{Path, PathBuf};
7
8/// Create directories, if they do not already exist.
9#[derive(Parser, Clone, Debug)]
10#[clap(author, version, about)]
11pub struct Mkdir {
12    /// Remove directory and its ancestors.
13    #[clap(long, short)]
14    pub parents: bool,
15    /// Output a diagnostic every time a directory is removed.
16    #[clap(long, short)]
17    pub verbose: bool,
18    /// List of directories to remove.
19    #[clap(required = true)]
20    pub directory: Vec<PathBuf>,
21}
22
23impl Mkdir {
24    /// Run command
25    pub fn run(&self) -> Result<(), io::Error> {
26        for directory in &self.directory {
27            if self.parents {
28                self.create_parents(directory)?
29            } else {
30                self.create_directory(directory)?
31            }
32        }
33        Ok(())
34    }
35
36    /// Create all parents and the directory
37    pub fn create_parents(&self, path: &Path) -> Result<(), io::Error> {
38        if let Some(parent) = path.parent() {
39            self.create_parents(parent)?;
40        }
41        self.create_directory(path)?;
42        Ok(())
43    }
44
45    /// Create directory
46    pub fn create_directory(&self, dir: &Path) -> Result<(), io::Error> {
47        if self.verbose {
48            eprintln!("Mkdir: Creating directory {dir:?}");
49        }
50
51        create_dir(dir)?;
52        Ok(())
53    }
54}
55
56impl Runnable for Mkdir {
57    fn run(&self) -> Result<(), Box<dyn Error>> {
58        self.run().map_err(|e| Box::new(e) as Box<dyn Error>)
59    }
60}