exa.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #![feature(phase)]
  2. extern crate regex;
  3. #[phase(syntax)] extern crate regex_macros;
  4. extern crate getopts;
  5. use std::os;
  6. use std::io::fs;
  7. use file::File;
  8. use column::defaultColumns;
  9. use options::{Options, SortField, Name};
  10. pub mod colours;
  11. pub mod column;
  12. pub mod format;
  13. pub mod file;
  14. pub mod unix;
  15. pub mod options;
  16. fn main() {
  17. let args: Vec<StrBuf> = os::args().iter()
  18. .map(|x| x.to_strbuf())
  19. .collect();
  20. let opts = ~[
  21. getopts::optflag("a", "all", "show dot-files"),
  22. getopts::optflag("r", "reverse", "reverse order of files"),
  23. getopts::optopt("s", "sort", "field to sort by", "WORD"),
  24. ];
  25. let matches = match getopts::getopts(args.tail(), opts) {
  26. Ok(m) => m,
  27. Err(f) => fail!("Invalid options\n{}", f.to_err_msg()),
  28. };
  29. let opts = Options {
  30. showInvisibles: matches.opt_present("all"),
  31. reverse: matches.opt_present("reverse"),
  32. sortField: matches.opt_str("sort").map(|word| SortField::from_word(word)).unwrap_or(Name),
  33. };
  34. let strs = if matches.free.is_empty() {
  35. vec!("./".to_strbuf())
  36. }
  37. else {
  38. matches.free.clone()
  39. };
  40. for dir in strs.move_iter() {
  41. list(opts, Path::new(dir))
  42. }
  43. }
  44. fn list(options: Options, path: Path) {
  45. let paths = match fs::readdir(&path) {
  46. Ok(paths) => paths,
  47. Err(e) => fail!("readdir: {}", e),
  48. };
  49. let mut files = paths.iter().map(|path| File::from_path(path)).collect();
  50. options.sort(&mut files);
  51. if options.reverse {
  52. files.reverse();
  53. }
  54. let columns = defaultColumns();
  55. let table: Vec<Vec<StrBuf>> = files.iter()
  56. .filter(|&f| options.show(f))
  57. .map(|f| columns.iter().map(|c| f.display(c)).collect())
  58. .collect();
  59. let maxes: Vec<uint> = range(0, columns.len())
  60. .map(|n| table.iter().map(|row| colours::strip_formatting(row.get(n)).len()).max().unwrap())
  61. .collect();
  62. for row in table.iter() {
  63. let mut first = true;
  64. for (length, cell) in maxes.iter().zip(row.iter()) {
  65. if first {
  66. first = false;
  67. } else {
  68. print!(" ");
  69. }
  70. print!("{}", cell.as_slice());
  71. for _ in range(cell.len(), *length) {
  72. print!(" ");
  73. }
  74. }
  75. print!("\n");
  76. }
  77. }