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

  1. use std::{fs::metadata, path::PathBuf, str::FromStr};
  2. use crate::error::ShellError;
  3. use super::{Builtin, BuiltinConfig};
  4. pub struct Ls;
  5. impl Builtin for Ls {
  6. fn execute(&mut self, _: &mut BuiltinConfig, _: Vec<String>) -> Result<(), ShellError> {
  7. let dir = std::env::current_dir().unwrap_or(PathBuf::from_str("/").unwrap());
  8. let entries = match std::fs::read_dir(dir) {
  9. Ok(e) => e,
  10. Err(e) => return Err(ShellError::ExecuteFailure(e.to_string())),
  11. };
  12. //for entry in entries.by_ref().into_iter() {}
  13. for entry in entries {
  14. let entry = match entry {
  15. Ok(e) => e,
  16. Err(_) => {
  17. println!("Couldn't get directory entry");
  18. continue;
  19. }
  20. };
  21. let metadata = match metadata(entry.path()) {
  22. Ok(m) => m,
  23. Err(_) => {
  24. continue;
  25. }
  26. };
  27. let file_name = entry.file_name().to_string_lossy().to_string();
  28. let mut file_type = "unknown";
  29. if metadata.file_type().is_dir() {
  30. file_type = "dir"
  31. } else if metadata.file_type().is_file() {
  32. file_type = "file"
  33. } else if metadata.file_type().is_symlink() {
  34. file_type = "link"
  35. }
  36. println!(
  37. "{:} | {:4} | {}",
  38. right_padding(&file_name, 16),
  39. file_type,
  40. metadata.len()
  41. )
  42. }
  43. Ok(())
  44. }
  45. }
  46. fn right_padding(s: &str, max: usize) -> String {
  47. let mut tmp = String::from_str(s).unwrap();
  48. for _ in tmp.len()..max {
  49. tmp.push(' ');
  50. }
  51. tmp
  52. }