exa.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. fn main() {
  15. let args = os::args().iter()
  16. .map(|x| x.to_strbuf())
  17. .collect();
  18. match Options::getopts(args) {
  19. Err(err) => println!("Invalid options:\n{}", err.to_err_msg()),
  20. Ok(opts) => {
  21. let strs = if opts.dirs.is_empty() {
  22. vec!("./".to_strbuf())
  23. }
  24. else {
  25. opts.dirs.clone()
  26. };
  27. for dir in strs.move_iter() {
  28. exa(&opts, Path::new(dir))
  29. }
  30. }
  31. };
  32. }
  33. fn exa(options: &Options, path: Path) {
  34. let paths = match fs::readdir(&path) {
  35. Ok(paths) => paths,
  36. Err(e) => fail!("readdir: {}", e),
  37. };
  38. let files: Vec<File> = options.transform_files(paths.iter().map(|path| File::from_path(path)).collect());
  39. let columns = options.columns();
  40. let table: Vec<Vec<String>> = files.iter()
  41. .filter(|&f| options.show(f))
  42. .map(|f| columns.iter().map(|c| f.display(c)).collect())
  43. .collect();
  44. let lengths: Vec<Vec<uint>> = table.iter()
  45. .map(|row| row.iter().map(|col| colours::strip_formatting(col).len()).collect())
  46. .collect();
  47. let maxes: Vec<uint> = range(0, columns.len())
  48. .map(|n| lengths.iter().map(|row| *row.get(n)).max().unwrap())
  49. .collect();
  50. for (field_lengths, row) in lengths.iter().zip(table.iter()) {
  51. let mut first = true;
  52. for ((column_length, cell), field_length) in maxes.iter().zip(row.iter()).zip(field_lengths.iter()) {
  53. if first {
  54. first = false;
  55. } else {
  56. print!(" ");
  57. }
  58. print!("{}", cell.as_slice());
  59. for _ in range(*field_length, *column_length) {
  60. print!(" ");
  61. }
  62. }
  63. print!("\n");
  64. }
  65. }