You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

58 lines
1.7 KiB

use std::{fs::metadata, 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, _: Vec<String>) -> 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(_) => {
println!("Couldn't get directory entry");
continue;
}
};
let metadata = match metadata(entry.path()) {
Ok(m) => m,
Err(_) => {
continue;
}
};
let file_name = entry.file_name().to_string_lossy().to_string();
let mut file_type = "unknown";
if metadata.file_type().is_dir() {
file_type = "dir"
} else if metadata.file_type().is_file() {
file_type = "file"
} else if metadata.file_type().is_symlink() {
file_type = "link"
}
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
}