diff --git a/src/builtins/ls.rs b/src/builtins/ls.rs index 8d79588..7822da6 100644 --- a/src/builtins/ls.rs +++ b/src/builtins/ls.rs @@ -1,4 +1,4 @@ -use std::{fs::File, io::stdout, path::PathBuf, str::FromStr}; +use std::{fs::metadata, path::PathBuf, str::FromStr}; use crate::error::ShellError; @@ -7,22 +7,48 @@ use super::{Builtin, BuiltinConfig}; pub struct Ls; impl Builtin for Ls { - fn execute(&mut self, _: &mut BuiltinConfig, args: Vec) -> Result<(), ShellError> { + fn execute(&mut self, _: &mut BuiltinConfig, _: 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.by_ref().into_iter() {} + for entry in entries { let entry = match entry { Ok(e) => e, - Err(e) => { + Err(_) => { println!("Couldn't get directory entry"); continue; } }; - println!("{}", entry.file_name().to_string_lossy()) + let file_name = entry.file_name().to_string_lossy().to_string(); + let mut file_type = "unknown"; + let tmp = entry.file_type().unwrap(); + if tmp.is_dir() { + file_type = "dir" + } else if tmp.is_file() { + file_type = "file" + } else if tmp.is_symlink() { + file_type = "link" + } + let metadata = metadata(entry.path()).unwrap(); + println!( + "{:} | {:4} | {}", + right_padding(&file_name, 16), + file_type, + metadata.len() + ) } Ok(()) } } + +fn right_padding(s: &str, max: usize) -> String { + let mut tmp = String::from_str(s).unwrap(); + for _ in tmp.len()..max { + tmp.push(' '); + } + tmp +}