From 5da1310696ef807a1d83c0a79c21ebe34184d106 Mon Sep 17 00:00:00 2001 From: xiuxiu62 Date: Tue, 5 Oct 2021 12:55:33 -0700 Subject: [PATCH] add fs utils --- crates/nu-command/src/filesystem/mod.rs | 3 + crates/nu-command/src/filesystem/util.rs | 82 ++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 crates/nu-command/src/filesystem/util.rs diff --git a/crates/nu-command/src/filesystem/mod.rs b/crates/nu-command/src/filesystem/mod.rs index 90b697fcd..2d2212766 100644 --- a/crates/nu-command/src/filesystem/mod.rs +++ b/crates/nu-command/src/filesystem/mod.rs @@ -1,7 +1,10 @@ mod cd; +mod cp; mod ls; mod mv; +mod util; pub use cd::Cd; +pub use cp::Cp; pub use ls::Ls; pub use mv::Mv; diff --git a/crates/nu-command/src/filesystem/util.rs b/crates/nu-command/src/filesystem/util.rs new file mode 100644 index 000000000..86a0bd4c9 --- /dev/null +++ b/crates/nu-command/src/filesystem/util.rs @@ -0,0 +1,82 @@ +use std::path::{Path, PathBuf}; + +use nu_path::canonicalize_with; +use nu_protocol::ShellError; + +#[derive(Default)] +pub struct FileStructure { + pub resources: Vec, +} + +impl FileStructure { + pub fn new() -> FileStructure { + FileStructure { resources: vec![] } + } + + #[allow(dead_code)] + pub fn contains_more_than_one_file(&self) -> bool { + self.resources.len() > 1 + } + + #[allow(dead_code)] + pub fn contains_files(&self) -> bool { + !self.resources.is_empty() + } + + pub fn paths_applying_with( + &mut self, + to: F, + ) -> Result, Box> + where + F: Fn((PathBuf, usize)) -> Result<(PathBuf, PathBuf), Box>, + { + self.resources + .iter() + .map(|f| (PathBuf::from(&f.location), f.at)) + .map(|f| to(f)) + .collect() + } + + pub fn walk_decorate(&mut self, start_path: &Path) -> Result<(), ShellError> { + self.resources = Vec::::new(); + self.build(start_path, 0)?; + self.resources.sort(); + + Ok(()) + } + + fn build(&mut self, src: &Path, lvl: usize) -> Result<(), ShellError> { + let source = canonicalize_with(src, std::env::current_dir()?)?; + + if source.is_dir() { + for entry in std::fs::read_dir(src)? { + let entry = entry?; + let path = entry.path(); + + if path.is_dir() { + self.build(&path, lvl + 1)?; + } + + self.resources.push(Resource { + location: path.to_path_buf(), + at: lvl, + }); + } + } else { + self.resources.push(Resource { + location: source, + at: lvl, + }); + } + + Ok(()) + } +} + +#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] +pub struct Resource { + pub at: usize, + pub location: PathBuf, +} + +impl Resource {}