view.rs 16.6 KB
Newer Older
B
Benjamin Sago 已提交
1 2 3
use std::env::var_os;

use output::Colours;
4
use output::{View, Mode, grid, details};
5
use output::table::{TimeTypes, Environment, SizeFormat, Options as TableOptions};
6
use output::file_name::{Classify, FileStyle};
7
use output::time::TimeFormat;
B
Benjamin Sago 已提交
8 9 10 11

use options::{flags, Misfire};
use options::parser::Matches;

B
Benjamin Sago 已提交
12
use fs::feature::xattr;
B
Benjamin Sago 已提交
13
use info::filetype::FileExtensions;
B
Benjamin Sago 已提交
14 15


16 17 18
impl View {

    /// Determine which view to use and all of that view’s arguments.
B
Benjamin Sago 已提交
19
    pub fn deduce(matches: &Matches) -> Result<View, Misfire> {
20 21 22 23
        let mode = Mode::deduce(matches)?;
        let colours = Colours::deduce(matches)?;
        let style = FileStyle::deduce(matches);
        Ok(View { mode, colours, style })
24 25 26 27 28
    }
}


impl Mode {
B
Benjamin Sago 已提交
29

30
    /// Determine the mode from the command-line arguments.
B
Benjamin Sago 已提交
31
    pub fn deduce(matches: &Matches) -> Result<Mode, Misfire> {
B
Benjamin Sago 已提交
32 33 34
        use options::misfire::Misfire::*;

        let long = || {
B
Benjamin Sago 已提交
35 36
            if matches.has(&flags::ACROSS) && !matches.has(&flags::GRID) {
                Err(Useless(&flags::ACROSS, true, &flags::LONG))
B
Benjamin Sago 已提交
37
            }
B
Benjamin Sago 已提交
38 39
            else if matches.has(&flags::ONE_LINE) {
                Err(Useless(&flags::ONE_LINE, true, &flags::LONG))
B
Benjamin Sago 已提交
40 41
            }
            else {
B
Benjamin Sago 已提交
42
                Ok(details::Options {
43
                    table: Some(TableOptions::deduce(matches)?),
B
Benjamin Sago 已提交
44 45
                    header: matches.has(&flags::HEADER),
                    xattr: xattr::ENABLED && matches.has(&flags::EXTENDED),
B
Benjamin Sago 已提交
46
                })
B
Benjamin Sago 已提交
47 48 49 50
            }
        };

        let long_options_scan = || {
B
Benjamin Sago 已提交
51 52 53 54
            for option in &[ &flags::BINARY, &flags::BYTES, &flags::INODE, &flags::LINKS,
                             &flags::HEADER, &flags::BLOCKS, &flags::TIME, &flags::GROUP ] {
                if matches.has(option) {
                    return Err(Useless(*option, false, &flags::LONG));
B
Benjamin Sago 已提交
55 56 57
                }
            }

B
Benjamin Sago 已提交
58 59
            if cfg!(feature="git") && matches.has(&flags::GIT) {
                Err(Useless(&flags::GIT, false, &flags::LONG))
B
Benjamin Sago 已提交
60
            }
B
Benjamin Sago 已提交
61 62
            else if matches.has(&flags::LEVEL) && !matches.has(&flags::RECURSE) && !matches.has(&flags::TREE) {
                Err(Useless2(&flags::LEVEL, &flags::RECURSE, &flags::TREE))
B
Benjamin Sago 已提交
63
            }
B
Benjamin Sago 已提交
64 65
            else if xattr::ENABLED && matches.has(&flags::EXTENDED) {
                Err(Useless(&flags::EXTENDED, false, &flags::LONG))
B
Benjamin Sago 已提交
66 67 68 69 70 71 72
            }
            else {
                Ok(())
            }
        };

        let other_options_scan = || {
73
            if let Some(width) = TerminalWidth::deduce()?.width() {
B
Benjamin Sago 已提交
74 75 76
                if matches.has(&flags::ONE_LINE) {
                    if matches.has(&flags::ACROSS) {
                        Err(Useless(&flags::ACROSS, true, &flags::ONE_LINE))
B
Benjamin Sago 已提交
77 78
                    }
                    else {
79
                        Ok(Mode::Lines)
B
Benjamin Sago 已提交
80 81
                    }
                }
B
Benjamin Sago 已提交
82
                else if matches.has(&flags::TREE) {
B
Benjamin Sago 已提交
83
                    let details = details::Options {
84
                        table: None,
B
Benjamin Sago 已提交
85 86 87 88
                        header: false,
                        xattr: false,
                    };

89
                    Ok(Mode::Details(details))
B
Benjamin Sago 已提交
90 91
                }
                else {
B
Benjamin Sago 已提交
92
                    let grid = grid::Options {
B
Benjamin Sago 已提交
93
                        across: matches.has(&flags::ACROSS),
B
Benjamin Sago 已提交
94 95 96
                        console_width: width,
                    };

97
                    Ok(Mode::Grid(grid))
B
Benjamin Sago 已提交
98 99 100 101 102 103 104
                }
            }
            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.

B
Benjamin Sago 已提交
105
                if matches.has(&flags::TREE) {
B
Benjamin Sago 已提交
106
                    let details = details::Options {
107
                        table: None,
B
Benjamin Sago 已提交
108 109 110 111
                        header: false,
                        xattr: false,
                    };

112
                    Ok(Mode::Details(details))
B
Benjamin Sago 已提交
113 114
                }
                else {
115
                    Ok(Mode::Lines)
B
Benjamin Sago 已提交
116 117 118 119
                }
            }
        };

B
Benjamin Sago 已提交
120
        if matches.has(&flags::LONG) {
B
Benjamin Sago 已提交
121
            let details = long()?;
B
Benjamin Sago 已提交
122
            if matches.has(&flags::GRID) {
B
Benjamin Sago 已提交
123 124 125 126
                match other_options_scan()? {
                    Mode::Grid(grid)  => return Ok(Mode::GridDetails(grid, details)),
                    others            => return Ok(others),
                };
B
Benjamin Sago 已提交
127 128
            }
            else {
B
Benjamin Sago 已提交
129
                return Ok(Mode::Details(details));
B
Benjamin Sago 已提交
130 131 132
            }
        }

133
        long_options_scan()?;
B
Benjamin Sago 已提交
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

        other_options_scan()
    }
}


/// The width of the terminal requested by the user.
#[derive(PartialEq, Debug)]
enum TerminalWidth {

    /// The user requested this specific number of columns.
    Set(usize),

    /// The terminal was found to have this number of columns.
    Terminal(usize),

    /// The user didn’t request any particular terminal width.
    Unset,
}

impl TerminalWidth {

    /// Determine a requested terminal width from the command-line arguments.
    ///
    /// Returns an error if a requested width doesn’t parse to an integer.
B
Benjamin Sago 已提交
159
    fn deduce() -> Result<TerminalWidth, Misfire> {
B
Benjamin Sago 已提交
160 161 162 163 164 165
        if let Some(columns) = var_os("COLUMNS").and_then(|s| s.into_string().ok()) {
            match columns.parse() {
                Ok(width)  => Ok(TerminalWidth::Set(width)),
                Err(e)     => Err(Misfire::FailedParse(e)),
            }
        }
166
        else if let Some(width) = *TERM_WIDTH {
B
Benjamin Sago 已提交
167 168 169 170 171 172 173
            Ok(TerminalWidth::Terminal(width))
        }
        else {
            Ok(TerminalWidth::Unset)
        }
    }

B
Benjamin Sago 已提交
174
    fn width(&self) -> Option<usize> {
B
Benjamin Sago 已提交
175
        match *self {
B
Benjamin Sago 已提交
176 177 178
            TerminalWidth::Set(width)       |
            TerminalWidth::Terminal(width)  => Some(width),
            TerminalWidth::Unset            => None,
B
Benjamin Sago 已提交
179 180 181 182 183
        }
    }
}


B
Benjamin Sago 已提交
184
impl TableOptions {
B
Benjamin Sago 已提交
185
    fn deduce(matches: &Matches) -> Result<Self, Misfire> {
B
Benjamin Sago 已提交
186
        Ok(TableOptions {
187
            env:         Environment::load_all(),
B
Benjamin Sago 已提交
188
            time_format: TimeFormat::deduce(matches)?,
189 190
            size_format: SizeFormat::deduce(matches)?,
            time_types:  TimeTypes::deduce(matches)?,
B
Benjamin Sago 已提交
191 192 193 194 195
            inode:  matches.has(&flags::INODE),
            links:  matches.has(&flags::LINKS),
            blocks: matches.has(&flags::BLOCKS),
            group:  matches.has(&flags::GROUP),
            git:    cfg!(feature="git") && matches.has(&flags::GIT),
B
Benjamin Sago 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        })
    }
}


impl SizeFormat {

    /// Determine which file size to use in the file size column based on
    /// the user’s options.
    ///
    /// The default mode is to use the decimal prefixes, as they are the
    /// most commonly-understood, and don’t involve trying to parse large
    /// strings of digits in your head. Changing the format to anything else
    /// involves the `--binary` or `--bytes` flags, and these conflict with
    /// each other.
B
Benjamin Sago 已提交
211 212 213
    fn deduce(matches: &Matches) -> Result<SizeFormat, Misfire> {
        let binary = matches.has(&flags::BINARY);
        let bytes  = matches.has(&flags::BYTES);
B
Benjamin Sago 已提交
214 215

        match (binary, bytes) {
B
Benjamin Sago 已提交
216
            (true,  true )  => Err(Misfire::Conflict(&flags::BINARY, &flags::BYTES)),
B
Benjamin Sago 已提交
217 218 219 220 221 222 223 224
            (true,  false)  => Ok(SizeFormat::BinaryBytes),
            (false, true )  => Ok(SizeFormat::JustBytes),
            (false, false)  => Ok(SizeFormat::DecimalBytes),
        }
    }
}


B
Benjamin Sago 已提交
225 226 227
impl TimeFormat {

    /// Determine how time should be formatted in timestamp columns.
B
Benjamin Sago 已提交
228
    fn deduce(matches: &Matches) -> Result<TimeFormat, Misfire> {
B
Benjamin Sago 已提交
229 230
        pub use output::time::{DefaultFormat, ISOFormat};
        const STYLES: &[&str] = &["default", "long-iso", "full-iso", "iso"];
231

B
Benjamin Sago 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        let word = match matches.get(&flags::TIME_STYLE) {
            Some(w) => w,
            None    => return Ok(TimeFormat::DefaultFormat(DefaultFormat::new())),
        };

        if word == "default" {
            Ok(TimeFormat::DefaultFormat(DefaultFormat::new()))
        }
        else if word == "iso" {
            Ok(TimeFormat::ISOFormat(ISOFormat::new()))
        }
        else if word == "long-iso" {
            Ok(TimeFormat::LongISO)
        }
        else if word == "full-iso" {
            Ok(TimeFormat::FullISO)
248 249
        }
        else {
B
Benjamin Sago 已提交
250
            Err(Misfire::bad_argument(&flags::TIME_STYLE, word, STYLES))
251
        }
B
Benjamin Sago 已提交
252 253 254 255
    }
}


256 257
static TIMES: &[&str] = &["modified", "accessed", "created"];

B
Benjamin Sago 已提交
258 259 260 261 262 263 264 265 266 267 268 269
impl TimeTypes {

    /// Determine which of a file’s time fields should be displayed for it
    /// based on the user’s options.
    ///
    /// There are two separate ways to pick which fields to show: with a
    /// flag (such as `--modified`) or with a parameter (such as
    /// `--time=modified`). An error is signaled if both ways are used.
    ///
    /// It’s valid to show more than one column by passing in more than one
    /// option, but passing *no* options means that the user just wants to
    /// see the default set.
B
Benjamin Sago 已提交
270 271 272 273 274
    fn deduce(matches: &Matches) -> Result<TimeTypes, Misfire> {
        let possible_word = matches.get(&flags::TIME);
        let modified = matches.has(&flags::MODIFIED);
        let created  = matches.has(&flags::CREATED);
        let accessed = matches.has(&flags::ACCESSED);
B
Benjamin Sago 已提交
275 276 277

        if let Some(word) = possible_word {
            if modified {
B
Benjamin Sago 已提交
278
                Err(Misfire::Useless(&flags::MODIFIED, true, &flags::TIME))
B
Benjamin Sago 已提交
279 280
            }
            else if created {
B
Benjamin Sago 已提交
281
                Err(Misfire::Useless(&flags::CREATED, true, &flags::TIME))
B
Benjamin Sago 已提交
282 283
            }
            else if accessed {
B
Benjamin Sago 已提交
284
                Err(Misfire::Useless(&flags::ACCESSED, true, &flags::TIME))
B
Benjamin Sago 已提交
285
            }
B
Benjamin Sago 已提交
286
            else if word == "mod" || word == "modified" {
B
Benjamin Sago 已提交
287 288 289 290 291 292 293 294 295 296
                Ok(TimeTypes { accessed: false, modified: true,  created: false })
            }
            else if word == "acc" || word == "accessed" {
                Ok(TimeTypes { accessed: true,  modified: false, created: false })
            }
            else if word == "cr" || word == "created" {
                Ok(TimeTypes { accessed: false, modified: false, created: true  })
            }
            else {
                Err(Misfire::bad_argument(&flags::TIME, word, TIMES))
B
Benjamin Sago 已提交
297 298 299
            }
        }
        else if modified || created || accessed {
300
            Ok(TimeTypes { accessed, modified, created })
B
Benjamin Sago 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        }
        else {
            Ok(TimeTypes::default())
        }
    }
}


/// Under what circumstances we should display coloured, rather than plain,
/// output to the terminal.
///
/// By default, we want to display the colours when stdout can display them.
/// Turning them on when output is going to, say, a pipe, would make programs
/// such as `grep` or `more` not work properly. So the `Automatic` mode does
/// this check and only displays colours when they can be truly appreciated.
#[derive(PartialEq, Debug)]
enum TerminalColours {

    /// Display them even when output isn’t going to a terminal.
    Always,

    /// Display them when output is going to a terminal, but not otherwise.
    Automatic,

    /// Never display them, even when output is going to a terminal.
    Never,
}

impl Default for TerminalColours {
    fn default() -> TerminalColours {
        TerminalColours::Automatic
    }
}

impl TerminalColours {

    /// Determine which terminal colour conditions to use.
B
Benjamin Sago 已提交
338
    fn deduce(matches: &Matches) -> Result<TerminalColours, Misfire> {
339 340
        const COLOURS: &[&str] = &["always", "auto", "never"];

B
Benjamin Sago 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353
        let word = match matches.get(&flags::COLOR).or_else(|| matches.get(&flags::COLOUR)) {
            Some(w) => w,
            None    => return Ok(TerminalColours::default()),
        };

        if word == "always" {
            Ok(TerminalColours::Always)
        }
        else if word == "auto" || word == "automatic" {
            Ok(TerminalColours::Automatic)
        }
        else if word == "never" {
            Ok(TerminalColours::Never)
B
Benjamin Sago 已提交
354 355
        }
        else {
B
Benjamin Sago 已提交
356
            Err(Misfire::bad_argument(&flags::COLOR, word, COLOURS))
B
Benjamin Sago 已提交
357 358 359
        }
    }
}
360 361


362
impl Colours {
B
Benjamin Sago 已提交
363
    fn deduce(matches: &Matches) -> Result<Colours, Misfire> {
364 365 366 367
        use self::TerminalColours::*;

        let tc = TerminalColours::deduce(matches)?;
        if tc == Always || (tc == Automatic && TERM_WIDTH.is_some()) {
B
Benjamin Sago 已提交
368
            let scale = matches.has(&flags::COLOR_SCALE) || matches.has(&flags::COLOUR_SCALE);
369 370 371 372 373 374 375 376 377
            Ok(Colours::colourful(scale))
        }
        else {
            Ok(Colours::plain())
        }
    }
}


378

379
impl FileStyle {
B
Benjamin Sago 已提交
380
    fn deduce(matches: &Matches) -> FileStyle {
381
        let classify = Classify::deduce(matches);
382 383
        let exts = FileExtensions;
        FileStyle { classify, exts }
384 385 386
    }
}

387
impl Classify {
B
Benjamin Sago 已提交
388 389 390
    fn deduce(matches: &Matches) -> Classify {
        if matches.has(&flags::CLASSIFY) { Classify::AddFileIndicators }
                                    else { Classify::JustFilenames }
391 392
    }
}
393 394 395 396 397 398 399 400 401 402 403


// Gets, then caches, the width of the terminal that exa is running in.
// This gets used multiple times above, with no real guarantee of order,
// so it’s easier to just cache it the first time it runs.
lazy_static! {
    static ref TERM_WIDTH: Option<usize> = {
        use term::dimensions;
        dimensions().map(|t| t.0)
    };
}
B
Benjamin Sago 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422



#[cfg(test)]
mod test {
    use super::*;
    use std::ffi::OsString;
    use options::flags;

    pub fn os(input: &'static str) -> OsString {
        let mut os = OsString::new();
        os.push(input);
        os
    }

    macro_rules! test {
        ($name:ident: $type:ident <- $inputs:expr => $result:expr) => {
            #[test]
            fn $name() {
423
                use options::parser::{Args, Arg};
B
Benjamin Sago 已提交
424 425
                use std::ffi::OsString;

426 427
                static TEST_ARGS: &[&Arg] = &[ &flags::BINARY, &flags::BYTES,
                                               &flags::TIME, &flags::MODIFIED, &flags::CREATED, &flags::ACCESSED ];
B
Benjamin Sago 已提交
428 429

                let bits = $inputs.as_ref().into_iter().map(|&o| os(o)).collect::<Vec<OsString>>();
430
                let results = Args(TEST_ARGS).parse(bits.iter());
B
Benjamin Sago 已提交
431 432 433 434 435
                assert_eq!($type::deduce(results.as_ref().unwrap()), $result);
            }
        };
    }

436

B
Benjamin Sago 已提交
437 438 439 440 441 442 443 444
    mod size_formats {
        use super::*;

        test!(empty:   SizeFormat <- []                       => Ok(SizeFormat::DecimalBytes));
        test!(binary:  SizeFormat <- ["--binary"]             => Ok(SizeFormat::BinaryBytes));
        test!(bytes:   SizeFormat <- ["--bytes"]              => Ok(SizeFormat::JustBytes));
        test!(both:    SizeFormat <- ["--binary", "--bytes"]  => Err(Misfire::Conflict(&flags::BINARY, &flags::BYTES)));
    }
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476


    mod time_types {
        use super::*;

        // Default behaviour
        test!(empty:     TimeTypes <- []                      => Ok(TimeTypes::default()));
        test!(modified:  TimeTypes <- ["--modified"]          => Ok(TimeTypes { accessed: false,  modified: true,   created: false }));
        test!(m:         TimeTypes <- ["-m"]                  => Ok(TimeTypes { accessed: false,  modified: true,   created: false }));
        test!(time_mod:  TimeTypes <- ["--time=modified"]     => Ok(TimeTypes { accessed: false,  modified: true,   created: false }));
        test!(time_m:    TimeTypes <- ["-tmod"]               => Ok(TimeTypes { accessed: false,  modified: true,   created: false }));

        test!(acc:       TimeTypes <- ["--accessed"]          => Ok(TimeTypes { accessed: true,   modified: false,  created: false }));
        test!(a:         TimeTypes <- ["-u"]                  => Ok(TimeTypes { accessed: true,   modified: false,  created: false }));
        test!(time_acc:  TimeTypes <- ["--time", "accessed"]  => Ok(TimeTypes { accessed: true,   modified: false,  created: false }));
        test!(time_a:    TimeTypes <- ["-t", "acc"]           => Ok(TimeTypes { accessed: true,   modified: false,  created: false }));

        test!(cr:        TimeTypes <- ["--created"]           => Ok(TimeTypes { accessed: false,  modified: false,  created: true  }));
        test!(c:         TimeTypes <- ["-U"]                  => Ok(TimeTypes { accessed: false,  modified: false,  created: true  }));
        test!(time_cr:   TimeTypes <- ["--time=created"]      => Ok(TimeTypes { accessed: false,  modified: false,  created: true  }));
        test!(time_c:    TimeTypes <- ["-tcr"]                => Ok(TimeTypes { accessed: false,  modified: false,  created: true  }));

        // Multiples
        test!(time_uu:    TimeTypes <- ["-uU"]                => Ok(TimeTypes { accessed: true,   modified: false,  created: true  }));

        // Overriding
        test!(time_mc:    TimeTypes <- ["-tcr", "-tmod"]      => Ok(TimeTypes { accessed: false,  modified: true,   created: false }));

        // Errors
        test!(time_tea:  TimeTypes <- ["--time=tea"]  => Err(Misfire::bad_argument(&flags::TIME, &os("tea"), super::TIMES)));
        test!(time_ea:   TimeTypes <- ["-tea"]        => Err(Misfire::bad_argument(&flags::TIME, &os("ea"), super::TIMES)));
    }
B
Benjamin Sago 已提交
477
}