options.rs 15.3 KB
Newer Older
B
Ben S 已提交
1
use dir::Dir;
B
Ben S 已提交
2
use file::File;
3
use column::Column;
B
Ben S 已提交
4
use column::Column::*;
5
use output::{Grid, Details};
B
Ben S 已提交
6 7 8
use term::dimensions;

use std::ascii::AsciiExt;
B
Ben S 已提交
9
use std::cmp::Ordering;
10
use std::fmt;
B
Ben S 已提交
11

12 13 14
use getopts;
use natord;

B
Ben S 已提交
15
use self::Misfire::*;
16

B
Ben S 已提交
17 18
/// The *Options* struct represents a parsed version of the user's
/// command-line options.
19
#[derive(PartialEq, Debug, Copy)]
B
Ben S 已提交
20
pub struct Options {
21
    pub dir_action: DirAction,
22
    pub filter: FileFilter,
23
    pub view: View,
24 25 26 27
}

#[derive(PartialEq, Debug, Copy)]
pub struct FileFilter {
B
Benjamin Sago 已提交
28 29 30
    reverse: bool,
    show_invisibles: bool,
    sort_field: SortField,
B
Ben S 已提交
31 32
}

33 34 35 36 37 38 39
#[derive(PartialEq, Copy, Debug)]
pub enum View {
    Details(Details),
    Lines,
    Grid(Grid),
}

B
Ben S 已提交
40
impl Options {
B
Ben S 已提交
41 42

    /// Call getopts on the given slice of command-line strings.
43
    pub fn getopts(args: &[String]) -> Result<(Options, Vec<String>), Misfire> {
B
Ben S 已提交
44 45 46 47 48 49 50 51 52 53
        let mut opts = getopts::Options::new();
        opts.optflag("1", "oneline",   "display one entry per line");
        opts.optflag("a", "all",       "show dot-files");
        opts.optflag("b", "binary",    "use binary prefixes in file sizes");
        opts.optflag("B", "bytes",     "list file sizes in bytes, without prefixes");
        opts.optflag("d", "list-dirs", "list directories as regular files");
        opts.optflag("g", "group",     "show group as well as user");
        opts.optflag("h", "header",    "show a header row at the top");
        opts.optflag("H", "links",     "show number of hard links");
        opts.optflag("i", "inode",     "show each file's inode number");
B
Ben S 已提交
54
        opts.optflag("l", "long",      "display extended details and attributes");
B
Ben S 已提交
55 56 57 58
        opts.optflag("r", "reverse",   "reverse order of files");
        opts.optflag("R", "recurse",   "recurse into directories");
        opts.optopt ("s", "sort",      "field to sort by", "WORD");
        opts.optflag("S", "blocks",    "show number of file system blocks");
B
Ben S 已提交
59
        opts.optopt ("t", "time",      "which timestamp to show for a file", "WORD");
B
Ben S 已提交
60 61 62
        opts.optflag("T", "tree",      "recurse into subdirectories in a tree view");
        opts.optflag("x", "across",    "sort multi-column view entries across");
        opts.optflag("?", "help",      "show list of command-line options");
B
Ben S 已提交
63

B
Ben S 已提交
64
        let matches = match opts.parse(args) {
65
            Ok(m) => m,
B
Ben S 已提交
66
            Err(e) => return Err(Misfire::InvalidOptions(e)),
B
Ben S 已提交
67
        };
B
Ben S 已提交
68

B
Ben S 已提交
69
        if matches.opt_present("help") {
B
Ben S 已提交
70
            return Err(Misfire::Help(opts.usage("Usage:\n  exa [options] [files...]")));
B
Ben S 已提交
71
        }
B
Ben S 已提交
72

73 74 75 76 77
        let sort_field = match matches.opt_str("sort") {
            Some(word) => try!(SortField::from_word(word)),
            None => SortField::Name,
        };

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        let filter = FileFilter {
            reverse:         matches.opt_present("reverse"),
            show_invisibles: matches.opt_present("all"),
            sort_field:      sort_field,
        };

        let path_strs = if matches.free.is_empty() {
            vec![ ".".to_string() ]
        }
        else {
            matches.free.clone()
        };

        Ok((Options {
            dir_action: try!(DirAction::deduce(&matches)),
            view:       try!(View::deduce(&matches, filter)),
            filter:     filter,
        }, path_strs))
B
Ben S 已提交
96
    }
B
Ben S 已提交
97

B
Ben S 已提交
98
    pub fn transform_files<'a>(&self, files: &mut Vec<File<'a>>) {
99 100 101
        self.filter.transform_files(files)
    }
}
B
Ben S 已提交
102

103
impl FileFilter {
B
Ben S 已提交
104
    /// Transform the files (sorting, reversing, filtering) before listing them.
B
Ben S 已提交
105
    pub fn transform_files<'a>(&self, files: &mut Vec<File<'a>>) {
B
Ben S 已提交
106 107

        if !self.show_invisibles {
B
Ben S 已提交
108
            files.retain(|f| !f.is_dotfile());
B
Ben S 已提交
109
        }
110 111 112

        match self.sort_field {
            SortField::Unsorted => {},
B
Ben S 已提交
113
            SortField::Name => files.sort_by(|a, b| natord::compare(&*a.name, &*b.name)),
114 115 116
            SortField::Size => files.sort_by(|a, b| a.stat.size.cmp(&b.stat.size)),
            SortField::FileInode => files.sort_by(|a, b| a.stat.unstable.inode.cmp(&b.stat.unstable.inode)),
            SortField::Extension => files.sort_by(|a, b| {
B
Ben S 已提交
117 118 119 120 121 122
                if a.ext.cmp(&b.ext) == Ordering::Equal {
                    Ordering::Equal
                }
                else {
                    a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase())
                }
123
            }),
B
Ben S 已提交
124
        }
125 126 127 128 129 130

        if self.reverse {
            files.reverse();
        }
    }
}
B
Ben S 已提交
131

132
/// User-supplied field to sort by.
B
Ben S 已提交
133
#[derive(PartialEq, Debug, Copy)]
B
Ben S 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
pub enum SortField {
    Unsorted, Name, Extension, Size, FileInode
}

impl SortField {

    /// Find which field to use based on a user-supplied word.
    fn from_word(word: String) -> Result<SortField, Misfire> {
        match word.as_slice() {
            "name"  => Ok(SortField::Name),
            "size"  => Ok(SortField::Size),
            "ext"   => Ok(SortField::Extension),
            "none"  => Ok(SortField::Unsorted),
            "inode" => Ok(SortField::FileInode),
            field   => Err(SortField::none(field))
        }
    }

    /// How to display an error when the word didn't match with anything.
    fn none(field: &str) -> Misfire {
        Misfire::InvalidOptions(getopts::Fail::UnrecognizedOption(format!("--sort {}", field)))
    }
}

/// One of these things could happen instead of listing files.
#[derive(PartialEq, Debug)]
pub enum Misfire {

    /// The getopts crate didn't like these arguments.
    InvalidOptions(getopts::Fail),

    /// The user asked for help. This isn't strictly an error, which is why
    /// this enum isn't named Error!
    Help(String),

    /// Two options were given that conflict with one another
    Conflict(&'static str, &'static str),

    /// An option was given that does nothing when another one either is or
    /// isn't present.
    Useless(&'static str, bool, &'static str),
}

impl Misfire {
    /// The OS return code this misfire should signify.
B
Ben S 已提交
179
    pub fn error_code(&self) -> i32 {
B
Ben S 已提交
180 181 182 183 184 185 186 187 188 189
        if let Help(_) = *self { 2 }
                          else { 3 }
    }
}

impl fmt::Display for Misfire {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            InvalidOptions(ref e) => write!(f, "{}", e),
            Help(ref text)        => write!(f, "{}", text),
B
Benjamin Sago 已提交
190 191 192
            Conflict(a, b)        => write!(f, "Option --{} conflicts with option {}.", a, b),
            Useless(a, false, b)  => write!(f, "Option --{} is useless without option --{}.", a, b),
            Useless(a, true, b)   => write!(f, "Option --{} is useless given option --{}.", a, b),
B
Ben S 已提交
193 194 195 196
        }
    }
}

197 198 199 200 201 202 203 204 205 206 207 208
impl View {
    pub fn deduce(matches: &getopts::Matches, filter: FileFilter) -> Result<View, Misfire> {
        if matches.opt_present("long") {
            if matches.opt_present("across") {
                Err(Misfire::Useless("across", true, "long"))
            }
            else if matches.opt_present("oneline") {
                Err(Misfire::Useless("oneline", true, "long"))
            }
            else {
                let details = Details {
                        columns: try!(Columns::deduce(matches)),
209
                        header: matches.opt_present("header"),
210 211 212 213 214 215
                        tree: matches.opt_present("recurse"),
                        filter: filter,
                };

                Ok(View::Details(details))
            }
B
Ben S 已提交
216
        }
217 218
        else if matches.opt_present("binary") {
            Err(Misfire::Useless("binary", false, "long"))
B
Ben S 已提交
219
        }
220 221
        else if matches.opt_present("bytes") {
            Err(Misfire::Useless("bytes", false, "long"))
222
        }
223 224
        else if matches.opt_present("inode") {
            Err(Misfire::Useless("inode", false, "long"))
225
        }
226 227
        else if matches.opt_present("links") {
            Err(Misfire::Useless("links", false, "long"))
228
        }
229 230 231 232 233 234
        else if matches.opt_present("header") {
            Err(Misfire::Useless("header", false, "long"))
        }
        else if matches.opt_present("blocks") {
            Err(Misfire::Useless("blocks", false, "long"))
        }
B
Ben S 已提交
235 236 237
        else if matches.opt_present("time") {
            Err(Misfire::Useless("time", false, "long"))
        }
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        else if matches.opt_present("oneline") {
            if matches.opt_present("across") {
                Err(Misfire::Useless("across", true, "oneline"))
            }
            else {
                Ok(View::Lines)
            }
        }
        else {
            if let Some((width, _)) = dimensions() {
                let grid = Grid {
                    across: matches.opt_present("across"),
                    console_width: width
                };

                Ok(View::Grid(grid))
            }
            else {
                // If the terminal width couldn't be matched for some reason, such
                // as the program's stdout being connected to a file, then
                // fallback to the lines view.
                Ok(View::Lines)
            }
B
Ben S 已提交
261
        }
262 263
    }
}
B
Ben S 已提交
264

265 266 267 268 269 270
#[derive(PartialEq, Debug, Copy)]
pub enum SizeFormat {
    DecimalBytes,
    BinaryBytes,
    JustBytes,
}
B
Ben S 已提交
271

272 273 274 275 276 277 278 279 280 281 282
impl SizeFormat {
    pub fn deduce(matches: &getopts::Matches) -> Result<SizeFormat, Misfire> {
        let binary = matches.opt_present("binary");
        let bytes  = matches.opt_present("bytes");

        match (binary, bytes) {
            (true,  true ) => Err(Misfire::Conflict("binary", "bytes")),
            (true,  false) => Ok(SizeFormat::BinaryBytes),
            (false, true ) => Ok(SizeFormat::JustBytes),
            (false, false) => Ok(SizeFormat::DecimalBytes),
        }
283 284 285
    }
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
#[derive(PartialEq, Debug, Copy)]
pub enum TimeType {
    FileAccessed,
    FileModified,
    FileCreated,
}

impl TimeType {

    /// Find which field to use based on a user-supplied word.
    fn deduce(matches: &getopts::Matches) -> Result<TimeType, Misfire> {
        let possible_word = matches.opt_str("time");

        if let Some(word) = possible_word {
            match word.as_slice() {
                "mod" | "modified"  => Ok(TimeType::FileModified),
                "acc" | "accessed"  => Ok(TimeType::FileAccessed),
                "cr"  | "created"   => Ok(TimeType::FileCreated),
                field   => Err(TimeType::none(field)),
            }
        }
        else {
            Ok(TimeType::FileModified)
        }
    }

    /// How to display an error when the word didn't match with anything.
    fn none(field: &str) -> Misfire {
        Misfire::InvalidOptions(getopts::Fail::UnrecognizedOption(format!("--time {}", field)))
    }

    pub fn header(&self) -> &'static str {
        match *self {
            TimeType::FileAccessed => "Date Accessed",
            TimeType::FileModified => "Date Modified",
            TimeType::FileCreated  => "Date Created",
        }
    }
}
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
/// What to do when encountering a directory?
#[derive(PartialEq, Debug, Copy)]
pub enum DirAction {
    AsFile, List, Recurse, Tree
}

impl DirAction {
    pub fn deduce(matches: &getopts::Matches) -> Result<DirAction, Misfire> {
        let recurse = matches.opt_present("recurse");
        let list    = matches.opt_present("list-dirs");
        let tree    = matches.opt_present("tree");

        match (recurse, list, tree) {
            (true,  true,  _    ) => Err(Misfire::Conflict("recurse", "list-dirs")),
            (true,  false, false) => Ok(DirAction::Recurse),
            (true,  false, true ) => Ok(DirAction::Tree),
            (false, true,  _    ) => Ok(DirAction::AsFile),
            (false, false, _    ) => Ok(DirAction::List),
        }
344 345 346
    }
}

B
Ben S 已提交
347 348 349
#[derive(PartialEq, Copy, Debug)]
pub struct Columns {
    size_format: SizeFormat,
350
    time_type: TimeType,
B
Ben S 已提交
351 352 353 354 355
    inode: bool,
    links: bool,
    blocks: bool,
    group: bool,
}
B
Ben S 已提交
356

B
Ben S 已提交
357
impl Columns {
358
    pub fn deduce(matches: &getopts::Matches) -> Result<Columns, Misfire> {
B
Ben S 已提交
359
        Ok(Columns {
360
            size_format: try!(SizeFormat::deduce(matches)),
361
            time_type:   try!(TimeType::deduce(matches)),
B
Ben S 已提交
362 363 364 365 366
            inode:  matches.opt_present("inode"),
            links:  matches.opt_present("links"),
            blocks: matches.opt_present("blocks"),
            group:  matches.opt_present("group"),
        })
B
Ben S 已提交
367 368
    }

B
Ben S 已提交
369 370
    pub fn for_dir(&self, dir: Option<&Dir>) -> Vec<Column> {
        let mut columns = vec![];
371

B
Ben S 已提交
372 373 374
        if self.inode {
            columns.push(Inode);
        }
B
Ben S 已提交
375

B
Ben S 已提交
376
        columns.push(Permissions);
377

B
Ben S 已提交
378 379 380
        if self.links {
            columns.push(HardLinks);
        }
381

B
Ben S 已提交
382
        columns.push(FileSize(self.size_format));
383

B
Ben S 已提交
384 385 386
        if self.blocks {
            columns.push(Blocks);
        }
387

B
Ben S 已提交
388 389 390 391 392 393
        columns.push(User);

        if self.group {
            columns.push(Group);
        }

394 395
        columns.push(Timestamp(self.time_type));

B
Ben S 已提交
396 397 398 399 400 401 402
        if cfg!(feature="git") {
            if let Some(d) = dir {
                if d.has_git_repo() {
                    columns.push(GitStatus);
                }
            }
        }
403

B
Ben S 已提交
404 405
        columns
    }
B
Ben S 已提交
406
}
407 408 409 410

#[cfg(test)]
mod test {
    use super::Options;
B
Ben S 已提交
411 412
    use super::Misfire;
    use super::Misfire::*;
413

414
    fn is_helpful<T>(misfire: Result<T, Misfire>) -> bool {
B
Ben S 已提交
415
        match misfire {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
            Err(Help(_)) => true,
            _            => false,
        }
    }

    #[test]
    fn help() {
        let opts = Options::getopts(&[ "--help".to_string() ]);
        assert!(is_helpful(opts))
    }

    #[test]
    fn help_with_file() {
        let opts = Options::getopts(&[ "--help".to_string(), "me".to_string() ]);
        assert!(is_helpful(opts))
    }

    #[test]
    fn files() {
435
        let args = Options::getopts(&[ "this file".to_string(), "that file".to_string() ]).unwrap().1;
B
Ben S 已提交
436
        assert_eq!(args, vec![ "this file".to_string(), "that file".to_string() ])
437 438 439 440
    }

    #[test]
    fn no_args() {
441
        let args = Options::getopts(&[]).unwrap().1;
B
Ben S 已提交
442
        assert_eq!(args, vec![ ".".to_string() ])
443 444 445
    }

    #[test]
446 447
    fn file_sizes() {
        let opts = Options::getopts(&[ "--long".to_string(), "--binary".to_string(), "--bytes".to_string() ]);
B
Ben S 已提交
448
        assert_eq!(opts.unwrap_err(), Misfire::Conflict("binary", "bytes"))
449 450 451 452 453
    }

    #[test]
    fn just_binary() {
        let opts = Options::getopts(&[ "--binary".to_string() ]);
B
Ben S 已提交
454
        assert_eq!(opts.unwrap_err(), Misfire::Useless("binary", false, "long"))
455
    }
456 457 458 459

    #[test]
    fn just_bytes() {
        let opts = Options::getopts(&[ "--bytes".to_string() ]);
B
Ben S 已提交
460
        assert_eq!(opts.unwrap_err(), Misfire::Useless("bytes", false, "long"))
461 462 463 464 465
    }

    #[test]
    fn long_across() {
        let opts = Options::getopts(&[ "--long".to_string(), "--across".to_string() ]);
B
Ben S 已提交
466
        assert_eq!(opts.unwrap_err(), Misfire::Useless("across", true, "long"))
467 468 469 470 471
    }

    #[test]
    fn oneline_across() {
        let opts = Options::getopts(&[ "--oneline".to_string(), "--across".to_string() ]);
B
Ben S 已提交
472
        assert_eq!(opts.unwrap_err(), Misfire::Useless("across", true, "oneline"))
473
    }
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497

    #[test]
    fn just_header() {
        let opts = Options::getopts(&[ "--header".to_string() ]);
        assert_eq!(opts.unwrap_err(), Misfire::Useless("header", false, "long"))
    }

    #[test]
    fn just_inode() {
        let opts = Options::getopts(&[ "--inode".to_string() ]);
        assert_eq!(opts.unwrap_err(), Misfire::Useless("inode", false, "long"))
    }

    #[test]
    fn just_links() {
        let opts = Options::getopts(&[ "--links".to_string() ]);
        assert_eq!(opts.unwrap_err(), Misfire::Useless("links", false, "long"))
    }

    #[test]
    fn just_blocks() {
        let opts = Options::getopts(&[ "--blocks".to_string() ]);
        assert_eq!(opts.unwrap_err(), Misfire::Useless("blocks", false, "long"))
    }
498
}