exa.rs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #![feature(phase)]
  2. extern crate regex;
  3. #[phase(syntax)] extern crate regex_macros;
  4. use std::os;
  5. use std::io::fs;
  6. use file::File;
  7. use options::Options;
  8. pub mod colours;
  9. pub mod column;
  10. pub mod format;
  11. pub mod file;
  12. pub mod unix;
  13. pub mod options;
  14. pub mod sort;
  15. fn main() {
  16. let args = os::args();
  17. match Options::getopts(args) {
  18. Err(err) => println!("Invalid options:\n{}", err.to_err_msg()),
  19. Ok(opts) => {
  20. // Default to listing the current directory when a target
  21. // isn't specified (mimic the behaviour of ls)
  22. let strs = if opts.dirs.is_empty() {
  23. vec!(".".to_string())
  24. }
  25. else {
  26. opts.dirs.clone()
  27. };
  28. for dir in strs.move_iter() {
  29. exa(&opts, Path::new(dir))
  30. }
  31. }
  32. };
  33. }
  34. fn exa(options: &Options, path: Path) {
  35. let paths = match fs::readdir(&path) {
  36. Ok(paths) => paths,
  37. Err(e) => fail!("readdir: {}", e),
  38. };
  39. let unordered_files: Vec<File> = paths.iter().map(|path| File::from_path(path)).collect();
  40. let files: Vec<&File> = options.transform_files(&unordered_files);
  41. // The output gets formatted into columns, which looks nicer. To
  42. // do this, we have to write the results into a table, instead of
  43. // displaying each file immediately, then calculating the maximum
  44. // width of each column based on the length of the results and
  45. // padding the fields during output.
  46. let table: Vec<Vec<String>> = files.iter()
  47. .map(|f| options.columns.iter().map(|c| f.display(c)).collect())
  48. .collect();
  49. // Each column needs to have its invisible colour-formatting
  50. // characters stripped before it has its width calculated, or the
  51. // width will be incorrect and the columns won't line up properly.
  52. // This is fairly expensive to do (it uses a regex), so the
  53. // results are cached.
  54. let lengths: Vec<Vec<uint>> = table.iter()
  55. .map(|row| row.iter().map(|col| colours::strip_formatting(col).len()).collect())
  56. .collect();
  57. let column_widths: Vec<uint> = range(0, options.columns.len())
  58. .map(|n| lengths.iter().map(|row| *row.get(n)).max().unwrap())
  59. .collect();
  60. for (field_lengths, row) in lengths.iter().zip(table.iter()) {
  61. let mut first = true;
  62. for (((column_length, cell), field_length), column) in column_widths.iter().zip(row.iter()).zip(field_lengths.iter()).zip(options.columns.iter()) { // this is getting messy
  63. if first {
  64. first = false;
  65. } else {
  66. print!(" ");
  67. }
  68. print!("{}", column.alignment().pad_string(cell, *field_length, *column_length));
  69. }
  70. print!("\n");
  71. }
  72. }