Skip to main content

fm/modes/menu/
node_creation.rs

1use std::fmt::Display;
2use std::fs;
3
4use anyhow::{Context, Result};
5
6use crate::app::{Status, Tab};
7use crate::log_line;
8use crate::modes::Display as DisplayMode;
9
10/// Used to create of files or directory.
11pub enum NodeCreation {
12    Newfile,
13    Newdir,
14}
15
16impl Display for NodeCreation {
17    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
18        match self {
19            Self::Newfile => write!(f, "file"),
20            Self::Newdir => write!(f, "directory"),
21        }
22    }
23}
24
25impl NodeCreation {
26    /// Create a new file or directory in current dir.
27    /// The filename is read from inputstring.
28    ///
29    /// # Errors
30    ///
31    /// It may fail if the node creation fail. See [`std::fs::create_dir_all`] and [`std::fs::File::create`]
32    pub fn create(&self, status: &mut Status) -> Result<std::path::PathBuf> {
33        let tab = status.current_tab_mut();
34        let root_path = Self::root_path(tab)?;
35        let path = root_path.join(status.menu.input.string());
36
37        if path.exists() {
38            log_line!("{self} {path} already exists", path = path.display());
39            return Err(anyhow::anyhow!(
40                "File {path} alredy exists",
41                path = path.display()
42            ));
43        };
44
45        match self {
46            Self::Newdir => {
47                fs::create_dir_all(&path)?;
48            }
49            Self::Newfile => {
50                fs::File::create(&path)?;
51            }
52        }
53        log_line!("Created new {self}: {path}", path = path.display());
54        Ok(path)
55    }
56
57    fn root_path(tab: &mut Tab) -> Result<std::path::PathBuf> {
58        let root_path = match tab.display_mode {
59            DisplayMode::Tree => tab
60                .tree
61                .directory_of_selected()
62                .context("no parent")?
63                .to_owned(),
64            _ => tab.directory.path.to_path_buf(),
65        };
66        Ok(root_path)
67    }
68}