From 0f5c849cc33431d22b1fdc87f1070f8769bfdf00 Mon Sep 17 00:00:00 2001 From: diogo464 Date: Tue, 12 Aug 2025 15:50:42 +0100 Subject: cli: added type filter to ls command --- src/main.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 3e8cd95..9e12cd1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -471,12 +471,35 @@ impl From<&str> for FsError { } } +#[derive(Debug)] +pub struct InvalidFsNodeKind; + +impl Display for InvalidFsNodeKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("invalid filesystem node type, must be one of 'directory' or 'file'") + } +} + +impl std::error::Error for InvalidFsNodeKind {} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum FsNodeKind { File, Directory, } +impl FromStr for FsNodeKind { + type Err = InvalidFsNodeKind; + + fn from_str(s: &str) -> Result { + match s { + "file" => Ok(Self::File), + "dir" | "directory" => Ok(Self::Directory), + _ => Err(InvalidFsNodeKind), + } + } +} + pub struct FsNode { pub kind: FsNodeKind, pub author: String, @@ -803,6 +826,9 @@ struct LsArgs { #[clap(long)] relative: bool, + #[clap(short = 't', long = "type")] + type_: Option, + path: Option, } @@ -982,6 +1008,7 @@ fn cmd_ls(args: LsArgs) { }, args.recursive, true, + args.type_, ); } writer.flush().unwrap(); @@ -995,19 +1022,22 @@ fn write_node( path: DrivePath, recursive: bool, recurse: bool, + filter_type: Option, ) { let node = &fs.nodes[node_id]; match node.kind { FsNodeKind::File => { - writeln!( - writer, - "{}\tfile\t{}\t{}\t{}\t{}", - path, node.lastmod, node.blob, node.size, node.author - ) - .unwrap(); + if filter_type == None || filter_type == Some(FsNodeKind::File) { + writeln!( + writer, + "{}\tfile\t{}\t{}\t{}\t{}", + path, node.lastmod, node.blob, node.size, node.author + ) + .unwrap(); + } } FsNodeKind::Directory => { - if !recurse { + if !recurse && (filter_type == None || filter_type == Some(FsNodeKind::Directory)) { writeln!( writer, "{}\tdir\t{}\t-\t-\t{}", @@ -1018,7 +1048,15 @@ fn write_node( if recursive || recurse { for (child_comp, child_id) in node.children.iter() { let child_path = path.push(child_comp.clone()); - write_node(writer, fs, *child_id, child_path, recursive, false); + write_node( + writer, + fs, + *child_id, + child_path, + recursive, + false, + filter_type, + ); } } } -- cgit