From cebfe212d4190b4317d606af5563e6e282b92956 Mon Sep 17 00:00:00 2001 From: fdai7375 Date: Tue, 24 Jan 2023 10:10:24 +0100 Subject: [PATCH] feat: add ls command --- src/builtins/ls.rs | 28 ++++++++++++++++++++++++++++ src/builtins/mod.rs | 2 ++ 2 files changed, 30 insertions(+) create mode 100644 src/builtins/ls.rs diff --git a/src/builtins/ls.rs b/src/builtins/ls.rs new file mode 100644 index 0000000..8d79588 --- /dev/null +++ b/src/builtins/ls.rs @@ -0,0 +1,28 @@ +use std::{fs::File, io::stdout, path::PathBuf, str::FromStr}; + +use crate::error::ShellError; + +use super::{Builtin, BuiltinConfig}; + +pub struct Ls; + +impl Builtin for Ls { + fn execute(&mut self, _: &mut BuiltinConfig, args: Vec) -> Result<(), ShellError> { + let dir = std::env::current_dir().unwrap_or(PathBuf::from_str("/").unwrap()); + let entries = match std::fs::read_dir(dir) { + Ok(e) => e, + Err(e) => return Err(ShellError::ExecuteFailure(e.to_string())), + }; + for entry in entries { + let entry = match entry { + Ok(e) => e, + Err(e) => { + println!("Couldn't get directory entry"); + continue; + } + }; + println!("{}", entry.file_name().to_string_lossy()) + } + Ok(()) + } +} diff --git a/src/builtins/mod.rs b/src/builtins/mod.rs index d0ef272..e0246ed 100644 --- a/src/builtins/mod.rs +++ b/src/builtins/mod.rs @@ -6,6 +6,7 @@ mod cd; mod change_prompt; mod exit; mod fetch; +mod ls; mod open; mod pwd; @@ -33,6 +34,7 @@ const BUILTINS: Lazy)>> = Lazy::new(|| { ("pwd", Box::new(pwd::Pwd)), ("open", Box::new(open::Open)), ("fetch", Box::new(fetch::Fetch)), + ("ls", Box::new(ls::Ls)), ] });