exa.rs 2.0 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. pub mod colours;
  10. pub mod column;
  11. pub mod format;
  12. pub mod file;
  13. pub mod unix;
  14. struct Options {
  15. showInvisibles: bool,
  16. }
  17. fn main() {
  18. let args: Vec<StrBuf> = os::args().iter()
  19. .map(|x| x.to_strbuf())
  20. .collect();
  21. let opts = ~[
  22. getopts::optflag("a", "all", "show dot-files")
  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. };
  31. let strs = if matches.free.is_empty() {
  32. vec!("./".to_strbuf())
  33. }
  34. else {
  35. matches.free.clone()
  36. };
  37. for dir in strs.move_iter() {
  38. list(opts, Path::new(dir))
  39. }
  40. }
  41. fn list(opts: Options, path: Path) {
  42. let mut files = match fs::readdir(&path) {
  43. Ok(files) => files,
  44. Err(e) => fail!("readdir: {}", e),
  45. };
  46. files.sort_by(|a, b| a.filename_str().cmp(&b.filename_str()));
  47. let columns = defaultColumns();
  48. let table: Vec<Vec<StrBuf>> = files.iter()
  49. .map(|p| File::from_path(p))
  50. .filter(|f| !f.is_dotfile() || opts.showInvisibles )
  51. .map(|f| columns.iter().map(|c| f.display(c)).collect())
  52. .collect();
  53. let maxes: Vec<uint> = range(0, columns.len())
  54. .map(|n| table.iter().map(|row| colours::strip_formatting(row.get(n)).len()).max().unwrap())
  55. .collect();
  56. for row in table.iter() {
  57. let mut first = true;
  58. for (length, cell) in maxes.iter().zip(row.iter()) {
  59. if first {
  60. first = false;
  61. } else {
  62. print!(" ");
  63. }
  64. print!("{}", cell.as_slice());
  65. for _ in range(cell.len(), *length) {
  66. print!(" ");
  67. }
  68. }
  69. print!("\n");
  70. }
  71. }