options.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. extern crate getopts;
  2. use file::File;
  3. use std::cmp::lexical_ordering;
  4. use column::{Column, Permissions, FileName, FileSize, User, Group};
  5. pub enum SortField {
  6. Name, Extension, Size
  7. }
  8. pub struct Options {
  9. pub showInvisibles: bool,
  10. pub sortField: SortField,
  11. pub reverse: bool,
  12. pub dirs: Vec<StrBuf>,
  13. }
  14. impl SortField {
  15. pub fn from_word(word: StrBuf) -> SortField {
  16. match word.as_slice() {
  17. "name" => Name,
  18. "size" => Size,
  19. "ext" => Extension,
  20. _ => fail!("Invalid sorting order"),
  21. }
  22. }
  23. fn sort(&self, files: &mut Vec<File>) {
  24. match *self {
  25. Name => files.sort_by(|a, b| a.name.cmp(&b.name)),
  26. Size => files.sort_by(|a, b| a.stat.size.cmp(&b.stat.size)),
  27. Extension => files.sort_by(|a, b| {
  28. let exts = a.ext.cmp(&b.ext);
  29. let names = a.name.cmp(&b.name);
  30. lexical_ordering(exts, names)
  31. }),
  32. }
  33. }
  34. }
  35. impl Options {
  36. pub fn getopts(args: Vec<StrBuf>) -> Result<Options, getopts::Fail_> {
  37. let opts = ~[
  38. getopts::optflag("a", "all", "show dot-files"),
  39. getopts::optflag("r", "reverse", "reverse order of files"),
  40. getopts::optopt("s", "sort", "field to sort by", "WORD"),
  41. ];
  42. match getopts::getopts(args.tail(), opts) {
  43. Err(f) => Err(f),
  44. Ok(matches) => Ok(Options {
  45. showInvisibles: matches.opt_present("all"),
  46. reverse: matches.opt_present("reverse"),
  47. sortField: matches.opt_str("sort").map(|word| SortField::from_word(word)).unwrap_or(Name),
  48. dirs: matches.free,
  49. })
  50. }
  51. }
  52. pub fn sort(&self, files: &mut Vec<File>) {
  53. self.sortField.sort(files);
  54. }
  55. pub fn show(&self, f: &File) -> bool {
  56. if self.showInvisibles {
  57. true
  58. } else {
  59. !f.name.starts_with(".")
  60. }
  61. }
  62. pub fn columns(&self) -> ~[Column] {
  63. return ~[
  64. Permissions,
  65. FileSize(false),
  66. User,
  67. Group,
  68. FileName,
  69. ];
  70. }
  71. }