exa.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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::optopt("s", "sort", "field to sort by", "WORD"),
  23. ];
  24. let matches = match getopts::getopts(args.tail(), opts) {
  25. Ok(m) => m,
  26. Err(f) => fail!("Invalid options\n{}", f.to_err_msg()),
  27. };
  28. let opts = Options {
  29. showInvisibles: matches.opt_present("all"),
  30. sortField: matches.opt_str("sort").map(|word| SortField::from_word(word)).unwrap_or(Name),
  31. };
  32. let strs = if matches.free.is_empty() {
  33. vec!("./".to_strbuf())
  34. }
  35. else {
  36. matches.free.clone()
  37. };
  38. for dir in strs.move_iter() {
  39. list(opts, Path::new(dir))
  40. }
  41. }
  42. fn list(options: Options, path: Path) {
  43. let paths = match fs::readdir(&path) {
  44. Ok(paths) => paths,
  45. Err(e) => fail!("readdir: {}", e),
  46. };
  47. let mut files = paths.iter().map(|path| File::from_path(path)).collect();
  48. options.sort(&mut files);
  49. let columns = defaultColumns();
  50. let table: Vec<Vec<StrBuf>> = files.iter()
  51. .filter(|&f| options.show(f))
  52. .map(|f| columns.iter().map(|c| f.display(c)).collect())
  53. .collect();
  54. let maxes: Vec<uint> = range(0, columns.len())
  55. .map(|n| table.iter().map(|row| colours::strip_formatting(row.get(n)).len()).max().unwrap())
  56. .collect();
  57. for row in table.iter() {
  58. let mut first = true;
  59. for (length, cell) in maxes.iter().zip(row.iter()) {
  60. if first {
  61. first = false;
  62. } else {
  63. print!(" ");
  64. }
  65. print!("{}", cell.as_slice());
  66. for _ in range(cell.len(), *length) {
  67. print!(" ");
  68. }
  69. }
  70. print!("\n");
  71. }
  72. }