options.rs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. extern crate getopts;
  2. use file::File;
  3. use std::cmp::lexical_ordering;
  4. use column::{Column, Permissions, FileName, FileSize, User, Group};
  5. use unix::get_current_user_id;
  6. use std::ascii::StrAsciiExt;
  7. pub enum SortField {
  8. Name, Extension, Size
  9. }
  10. pub struct Options {
  11. pub showInvisibles: bool,
  12. pub sortField: SortField,
  13. pub reverse: bool,
  14. pub dirs: Vec<String>,
  15. pub columns: Vec<Column>,
  16. }
  17. impl SortField {
  18. fn from_word(word: String) -> SortField {
  19. match word.as_slice() {
  20. "name" => Name,
  21. "size" => Size,
  22. "ext" => Extension,
  23. _ => fail!("Invalid sorting order"),
  24. }
  25. }
  26. }
  27. impl Options {
  28. pub fn getopts(args: Vec<String>) -> Result<Options, getopts::Fail_> {
  29. let opts = [
  30. getopts::optflag("a", "all", "show dot-files"),
  31. getopts::optflag("b", "binary", "use binary prefixes in file sizes"),
  32. getopts::optflag("g", "group", "show group as well as user"),
  33. getopts::optflag("r", "reverse", "reverse order of files"),
  34. getopts::optopt("s", "sort", "field to sort by", "WORD"),
  35. ];
  36. match getopts::getopts(args.tail(), opts) {
  37. Err(f) => Err(f),
  38. Ok(matches) => Ok(Options {
  39. showInvisibles: matches.opt_present("all"),
  40. reverse: matches.opt_present("reverse"),
  41. sortField: matches.opt_str("sort").map(|word| SortField::from_word(word)).unwrap_or(Name),
  42. dirs: matches.free.clone(),
  43. columns: Options::columns(matches),
  44. })
  45. }
  46. }
  47. fn columns(matches: getopts::Matches) -> Vec<Column> {
  48. let mut columns = vec![
  49. Permissions,
  50. FileSize(matches.opt_present("binary")),
  51. User(get_current_user_id()),
  52. ];
  53. if matches.opt_present("group") {
  54. columns.push(Group);
  55. }
  56. columns.push(FileName);
  57. return columns;
  58. }
  59. fn should_display(&self, f: &File) -> bool {
  60. if self.showInvisibles {
  61. true
  62. } else {
  63. !f.name.starts_with(".")
  64. }
  65. }
  66. pub fn transform_files<'a>(&self, unordered_files: &'a Vec<File<'a>>) -> Vec<&'a File<'a>> {
  67. let mut files: Vec<&'a File<'a>> = unordered_files.iter()
  68. .filter(|&f| self.should_display(f))
  69. .collect();
  70. match self.sortField {
  71. Name => files.sort_by(|a, b| a.parts.cmp(&b.parts)),
  72. Size => files.sort_by(|a, b| a.stat.size.cmp(&b.stat.size)),
  73. Extension => files.sort_by(|a, b| {
  74. let exts = a.ext.map(|e| e.to_ascii_lower()).cmp(&b.ext.map(|e| e.to_ascii_lower()));
  75. let names = a.name.to_ascii_lower().cmp(&b.name.to_ascii_lower());
  76. lexical_ordering(exts, names)
  77. }),
  78. }
  79. if self.reverse {
  80. files.reverse();
  81. }
  82. return files;
  83. }
  84. }