file.rs 25.7 KB
Newer Older
B
Ben S 已提交
1
use std::ascii::AsciiExt;
B
Benjamin Sago 已提交
2
use std::env::current_dir;
3 4
use std::fs;
use std::io;
B
Ben S 已提交
5
use std::os::unix;
6
use std::os::unix::fs::{MetadataExt, PermissionsExt};
7
use std::path::{Component, Path, PathBuf};
B
Ben S 已提交
8

9
use ansi_term::{ANSIString, ANSIStrings, Colour, Style};
B
Ben S 已提交
10 11
use ansi_term::Style::Plain;
use ansi_term::Colour::{Red, Green, Yellow, Blue, Purple, Cyan, Fixed};
12

B
Ben S 已提交
13
use users::Users;
B
Ben S 已提交
14

15
use locale;
B
Ben S 已提交
16 17

use unicode_width::UnicodeWidthStr;
18

19 20
use number_prefix::{binary_prefix, decimal_prefix, Prefixed, Standalone, PrefixNames};

B
Ben S 已提交
21
use datetime::local::{LocalDateTime, DatePiece};
22
use datetime::format::{DateFormat};
23

24
use column::{Column, Cell};
B
Ben S 已提交
25
use column::Column::*;
B
Ben S 已提交
26
use dir::Dir;
B
Ben S 已提交
27
use filetype::HasType;
28
use options::{SizeFormat, TimeType};
B
Ben S 已提交
29
use output::details::UserLocale;
30
use feature::Attribute;
B
Ben S 已提交
31

B
Ben S 已提交
32
/// This grey value is directly in between white and black, so it's guaranteed
B
Ben S 已提交
33
/// to show up on either backgrounded terminal.
B
Ben S 已提交
34
pub static GREY: Colour = Fixed(244);
35

B
Ben S 已提交
36 37 38 39 40 41 42
/// A **File** is a wrapper around one of Rust's Path objects, along with
/// associated data about the file.
///
/// Each file is definitely going to have its filename displayed at least
/// once, have its file extension extracted at least once, and have its stat
/// information queried at least once, so it makes sense to do all this at the
/// start and hold on to all the information.
B
Ben S 已提交
43
pub struct File<'a> {
B
Ben S 已提交
44
    pub name:  String,
B
Ben S 已提交
45
    pub dir:   Option<&'a Dir>,
B
Ben S 已提交
46
    pub ext:   Option<String>,
47 48
    pub path:  PathBuf,
    pub stat:  fs::Metadata,
N
nwin 已提交
49
    pub xattrs: Vec<Attribute>,
B
Ben S 已提交
50
    pub this:  Option<Dir>,
B
Ben S 已提交
51 52 53
}

impl<'a> File<'a> {
B
Ben S 已提交
54 55 56
    /// Create a new File object from the given Path, inside the given Dir, if
    /// appropriate. Paths specified directly on the command-line have no Dirs.
    ///
B
Ben S 已提交
57 58
    /// This uses `symlink_metadata` instead of `metadata`, which doesn't
    /// follow symbolic links.
59
    pub fn from_path(path: &Path, parent: Option<&'a Dir>, recurse: bool) -> io::Result<File<'a>> {
B
Ben S 已提交
60
        fs::symlink_metadata(path).map(|stat| File::with_stat(stat, path, parent, recurse))
B
Ben S 已提交
61
    }
B
Ben S 已提交
62

B
Ben S 已提交
63
    /// Create a new File object from the given Stat result, and other data.
64
    pub fn with_stat(stat: fs::Metadata, path: &Path, parent: Option<&'a Dir>, recurse: bool) -> File<'a> {
65
        let filename = path_filename(path);
B
Ben S 已提交
66

B
Ben S 已提交
67 68 69
        // If we are recursing, then the `this` field contains a Dir object
        // that represents the current File as a directory, if it is a
        // directory. This is used for the --tree option.
70
        let this = if recurse && stat.is_dir() {
B
Ben S 已提交
71 72 73 74 75 76
            Dir::readdir(path).ok()
        }
        else {
            None
        };

B
Ben S 已提交
77
        File {
78
            path:   path.to_path_buf(),
B
Ben S 已提交
79 80 81
            dir:    parent,
            stat:   stat,
            ext:    ext(&filename),
82
            xattrs: Attribute::llist(path).unwrap_or(Vec::new()),
B
Ben S 已提交
83 84
            name:   filename.to_string(),
            this:   this,
B
Ben S 已提交
85
        }
B
Ben S 已提交
86 87
    }

88 89 90 91 92 93 94 95 96
    pub fn is_directory(&self) -> bool {
        self.stat.is_dir()
    }

    pub fn is_file(&self) -> bool {
        self.stat.is_file()
    }

    pub fn is_link(&self) -> bool {
B
Ben S 已提交
97
        self.stat.file_type().is_symlink()
98 99 100
    }

    pub fn is_pipe(&self) -> bool {
B
Ben S 已提交
101
        false  // TODO: Still waiting on this one...
102 103
    }

B
Ben S 已提交
104
    /// Whether this file is a dotfile or not.
B
Ben S 已提交
105
    pub fn is_dotfile(&self) -> bool {
106
        self.name.starts_with(".")
B
Ben S 已提交
107 108
    }

B
Ben S 已提交
109
    /// Whether this file is a temporary file or not.
110
    pub fn is_tmpfile(&self) -> bool {
111
        let name = &self.name;
B
Ben S 已提交
112
        name.ends_with("~") || (name.starts_with("#") && name.ends_with("#"))
B
Ben S 已提交
113
    }
B
Ben S 已提交
114

B
Ben S 已提交
115
    /// Get the data for a column, formatted as a coloured string.
116
    pub fn display<U: Users>(&self, column: &Column, users_cache: &mut U, locale: &UserLocale) -> Cell {
B
Ben S 已提交
117
        match *column {
B
Ben S 已提交
118
            Permissions     => self.permissions_string(),
119 120 121
            FileSize(f)     => self.file_size(f, &locale.numeric),
            Timestamp(t, y) => self.timestamp(t, y, &locale.time),
            HardLinks       => self.hard_links(&locale.numeric),
B
Ben S 已提交
122
            Inode           => self.inode(),
123
            Blocks          => self.blocks(&locale.numeric),
B
Ben S 已提交
124 125 126
            User            => self.user(users_cache),
            Group           => self.group(users_cache),
            GitStatus       => self.git_status(),
B
Ben S 已提交
127 128
        }
    }
B
Ben S 已提交
129

B
Ben S 已提交
130 131 132
    /// The "file name view" is what's displayed in the column and lines
    /// views, but *not* in the grid view.
    ///
133 134
    /// It consists of the file name coloured in the appropriate style,
    /// with special formatting for a symlink.
B
Ben S 已提交
135
    pub fn file_name_view(&self) -> String {
136
        if self.is_link() {
137 138 139
            self.symlink_file_name_view()
        }
        else {
B
Ben S 已提交
140
            self.file_colour().paint(&*self.name).to_string()
141 142 143 144 145
        }
    }

    /// If this file is a symlink, returns a string displaying its name,
    /// and an arrow pointing to the file it links to, which is also
146 147 148 149 150 151
    /// coloured in the appropriate style.
    ///
    /// If the symlink target doesn't exist, then instead of displaying
    /// an error, highlight the target and arrow in red. The error would
    /// be shown out of context, and it's almost always because the
    /// target doesn't exist.
B
Ben S 已提交
152
    fn symlink_file_name_view(&self) -> String {
153 154 155
        let name = &*self.name;
        let style = self.file_colour();

156
        if let Ok(path) = fs::read_link(&self.path) {
157
            let target_path = match self.dir {
158
                Some(dir) => dir.join(&*path),
159 160 161 162
                None => path,
            };

            match self.target_file(&target_path) {
163 164 165 166 167 168 169 170
                Ok(file) => {

                    // Generate a preview for the path this symlink links to.
                    // The preview should consist of the directory of the file
                    // (if present) in cyan, an extra slash if necessary, then
                    // the target file, colourised in the appropriate style.
                    let mut path_prefix = String::new();

171
                    let path_bytes: Vec<Component> = file.path.components().collect();
172 173 174 175 176
                    if !path_bytes.is_empty() {
                        // Use init() to add all but the last component of the
                        // path to the prefix. init() panics when given an
                        // empty list, hence the check.
                        for component in path_bytes.init().iter() {
177
                            path_prefix.push_str(&*component.as_os_str().to_string_lossy());
B
Ben S 已提交
178 179 180 181

                            if component != &Component::RootDir {
                                path_prefix.push_str("/");
                            }
182 183 184 185 186 187 188 189 190
                        }
                    }

                    format!("{} {} {}",
                            style.paint(name),
                            GREY.paint("=>"),
                            ANSIStrings(&[ Cyan.paint(&path_prefix),
                                           file.file_colour().paint(&file.name) ]))
                },
B
Ben S 已提交
191 192 193
                Err(filename) => format!("{} {} {}",
                                         style.paint(name),
                                         Red.paint("=>"),
194
                                         Red.underline().paint(&filename)),
B
Ben S 已提交
195 196 197
            }
        }
        else {
B
Ben S 已提交
198
            style.paint(name).to_string()
B
Ben S 已提交
199 200
        }
    }
B
Ben S 已提交
201

B
Ben S 已提交
202 203 204 205 206 207 208 209 210 211
    /// The `ansi_term::Style` that this file's name should be painted.
    pub fn file_colour(&self) -> Style {
        self.get_type().style()
    }

    /// The Unicode 'display width' of the filename.
    ///
    /// This is related to the number of graphemes in the string: most
    /// characters are 1 columns wide, but in some contexts, certain
    /// characters are actually 2 columns wide.
B
Benjamin Sago 已提交
212
    pub fn file_name_width(&self) -> usize {
B
Ben S 已提交
213
        UnicodeWidthStr::width(&self.name[..])
214 215
    }

216 217 218 219 220 221 222
    /// Assuming the current file is a symlink, follows the link and
    /// returns a File object from the path the link points to.
    ///
    /// If statting the file fails (usually because the file on the
    /// other end doesn't exist), returns the *filename* of the file
    /// that should be there.
    fn target_file(&self, target_path: &Path) -> Result<File, String> {
223
        let filename = path_filename(target_path);
B
Ben S 已提交
224

B
Ben S 已提交
225
        // Use plain `metadata` instead of `symlink_metadata` - we *want* to follow links.
226
        if let Ok(stat) = fs::metadata(target_path) {
227
            Ok(File {
228
                path:   target_path.to_path_buf(),
B
Ben S 已提交
229 230 231
                dir:    self.dir,
                stat:   stat,
                ext:    ext(&filename),
232
                xattrs: Attribute::list(target_path).unwrap_or(Vec::new()),
B
Ben S 已提交
233 234
                name:   filename.to_string(),
                this:   None,
235 236 237 238
            })
        }
        else {
            Err(filename.to_string())
B
Ben S 已提交
239 240 241
        }
    }

B
Ben S 已提交
242
    /// This file's number of hard links as a coloured string.
243
    fn hard_links(&self, locale: &locale::Numeric) -> Cell {
B
Ben S 已提交
244
        let style = if self.has_multiple_links() { Red.on(Yellow) } else { Red.normal() };
245
        Cell::paint(style, &locale.format_int(self.stat.as_raw().nlink())[..])
B
Ben S 已提交
246 247 248 249 250 251 252 253
    }

    /// Whether this is a regular file with more than one link.
    ///
    /// This is important, because a file with multiple links is uncommon,
    /// while you can come across directories and other types with multiple
    /// links much more often.
    fn has_multiple_links(&self) -> bool {
254
        self.is_file() && self.stat.as_raw().nlink() > 1
B
Ben S 已提交
255 256 257
    }

    /// This file's inode as a coloured string.
258
    fn inode(&self) -> Cell {
259
        let inode = self.stat.as_raw().ino();
260
        Cell::paint(Purple.normal(), &inode.to_string()[..])
B
Ben S 已提交
261 262 263
    }

    /// This file's number of filesystem blocks (if available) as a coloured string.
264
    fn blocks(&self, locale: &locale::Numeric) -> Cell {
265
        if self.is_file() || self.is_link() {
266
            Cell::paint(Cyan.normal(), &locale.format_int(self.stat.as_raw().blocks())[..])
B
Ben S 已提交
267 268
        }
        else {
269
            Cell { text: GREY.paint("-").to_string(), length: 1 }
B
Ben S 已提交
270 271 272 273 274 275 276 277
        }
    }

    /// This file's owner's username as a coloured string.
    ///
    /// If the user is not present, then it formats the uid as a number
    /// instead. This usually happens when a user is deleted, but still owns
    /// files.
278
    fn user<U: Users>(&self, users_cache: &mut U) -> Cell {
279
        let uid = self.stat.as_raw().uid();
B
Ben S 已提交
280 281 282

        let user_name = match users_cache.get_user_by_uid(uid) {
            Some(user) => user.name,
283
            None => uid.to_string(),
B
Ben S 已提交
284 285 286
        };

        let style = if users_cache.get_current_uid() == uid { Yellow.bold() } else { Plain };
287
        Cell::paint(style, &*user_name)
B
Ben S 已提交
288 289 290 291 292
    }

    /// This file's group name as a coloured string.
    ///
    /// As above, if not present, it formats the gid as a number instead.
293
    fn group<U: Users>(&self, users_cache: &mut U) -> Cell {
294
        let gid = self.stat.as_raw().gid();
B
Ben S 已提交
295 296
        let mut style = Plain;

297
        let group_name = match users_cache.get_group_by_gid(gid as u32) {
B
Ben S 已提交
298 299 300 301 302 303 304 305 306
            Some(group) => {
                let current_uid = users_cache.get_current_uid();
                if let Some(current_user) = users_cache.get_user_by_uid(current_uid) {
                    if current_user.primary_group == group.gid || group.members.contains(&current_user.name) {
                        style = Yellow.bold();
                    }
                }
                group.name
            },
307
            None => gid.to_string(),
B
Ben S 已提交
308 309
        };

310
        Cell::paint(style, &*group_name)
B
Ben S 已提交
311 312 313 314 315 316 317 318
    }

    /// This file's size, formatted using the given way, as a coloured string.
    ///
    /// For directories, no size is given. Although they do have a size on
    /// some filesystems, I've never looked at one of those numbers and gained
    /// any information from it, so by emitting "-" instead, the table is less
    /// cluttered with numbers.
319
    fn file_size(&self, size_format: SizeFormat, locale: &locale::Numeric) -> Cell {
B
Ben S 已提交
320
        if self.is_directory() {
321
            Cell { text: GREY.paint("-").to_string(), length: 1 }
B
Ben S 已提交
322 323
        }
        else {
B
Ben S 已提交
324
            let result = match size_format {
325 326 327
                SizeFormat::DecimalBytes => decimal_prefix(self.stat.len() as f64),
                SizeFormat::BinaryBytes  => binary_prefix(self.stat.len() as f64),
                SizeFormat::JustBytes    => return Cell::paint(Green.bold(), &locale.format_int(self.stat.len())[..]),
B
Ben S 已提交
328 329 330
            };

            match result {
331
                Standalone(bytes) => Cell::paint(Green.bold(), &*bytes.to_string()),
B
Ben S 已提交
332
                Prefixed(prefix, n) => {
B
Ben S 已提交
333
                    let number = if n < 10f64 { locale.format_float(n, 1) } else { locale.format_int(n as isize) };
334 335 336
                    let symbol = prefix.symbol();

                    Cell {
B
Ben S 已提交
337
                        text: ANSIStrings( &[ Green.bold().paint(&number[..]), Green.paint(symbol) ]).to_string(),
338 339
                        length: number.len() + symbol.len(),
                    }
B
Ben S 已提交
340 341
                }
            }
342
        }
B
Ben S 已提交
343 344
    }

345
    fn timestamp(&self, time_type: TimeType, current_year: i64, locale: &locale::Time) -> Cell {
346 347 348

        // Need to convert these values from milliseconds into seconds.
        let time_in_seconds = match time_type {
B
Ben S 已提交
349 350 351
            TimeType::FileAccessed => self.stat.as_raw().atime(),
            TimeType::FileModified => self.stat.as_raw().mtime(),
            TimeType::FileCreated  => self.stat.as_raw().ctime(),
352 353
        } as i64 / 1000;

B
Ben S 已提交
354
        let date = LocalDateTime::at(time_in_seconds);
B
Ben S 已提交
355 356

        let format = if date.year() == current_year {
357
                DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap()
B
Ben S 已提交
358 359
            }
            else {
N
nwin 已提交
360
                DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap()
B
Ben S 已提交
361 362
            };

363
        Cell::paint(Blue.normal(), &format.format(date, locale))
364 365
    }

B
Ben S 已提交
366 367 368 369
    /// This file's type, represented by a coloured character.
    ///
    /// Although the file type can usually be guessed from the colour of the
    /// file, `ls` puts this character there, so people will expect it.
B
Ben S 已提交
370
    fn type_char(&self) -> ANSIString {
371 372 373 374 375 376 377 378 379 380 381 382 383 384
        if self.is_file() {
            Plain.paint(".")
        }
        else if self.is_directory() {
            Blue.paint("d")
        }
        else if self.is_pipe() {
            Yellow.paint("|")
        }
        else if self.is_link() {
            Cyan.paint("l")
        }
        else {
            Purple.paint("?")
B
Ben S 已提交
385 386 387
        }
    }

N
nwin 已提交
388 389
    /// Marker indicating that the file contains extended attributes
    ///
390
    /// Returns "@" or  " ” depending on wheter the file contains an extented
N
nwin 已提交
391 392 393
    /// attribute or not. Also returns “ ” in case the attributes cannot be read
    /// for some reason.
    fn attribute_marker(&self) -> ANSIString {
N
nwin 已提交
394
        if self.xattrs.len() > 0 { Plain.paint("@") } else { Plain.paint(" ") }
N
nwin 已提交
395 396
    }

B
Ben S 已提交
397 398 399 400 401
    /// Generate the "rwxrwxrwx" permissions string, like how ls does it.
    ///
    /// Each character is given its own colour. The first three permission
    /// bits are bold because they're the ones used most often, and executable
    /// files are underlined to make them stand out more.
402
    fn permissions_string(&self) -> Cell {
403 404 405 406

        let bits = self.stat.permissions().mode();
        let executable_colour = if self.is_file() { Green.bold().underline() }
                                                         else { Green.bold() };
B
Ben S 已提交
407

408
        let string = ANSIStrings(&[
B
Ben S 已提交
409
            self.type_char(),
B
Ben S 已提交
410 411 412 413 414 415 416 417 418
            File::permission_bit(bits, unix::fs::USER_READ,     "r", Yellow.bold()),
            File::permission_bit(bits, unix::fs::USER_WRITE,    "w", Red.bold()),
            File::permission_bit(bits, unix::fs::USER_EXECUTE,  "x", executable_colour),
            File::permission_bit(bits, unix::fs::GROUP_READ,    "r", Yellow.normal()),
            File::permission_bit(bits, unix::fs::GROUP_WRITE,   "w", Red.normal()),
            File::permission_bit(bits, unix::fs::GROUP_EXECUTE, "x", Green.normal()),
            File::permission_bit(bits, unix::fs::OTHER_READ,    "r", Yellow.normal()),
            File::permission_bit(bits, unix::fs::OTHER_WRITE,   "w", Red.normal()),
            File::permission_bit(bits, unix::fs::OTHER_EXECUTE, "x", Green.normal()),
N
nwin 已提交
419
            self.attribute_marker()
420
        ]).to_string();
421

B
Ben S 已提交
422
        Cell { text: string, length: 11 }
B
Ben S 已提交
423
    }
424

B
Ben S 已提交
425
    /// Helper method for the permissions string.
B
Ben S 已提交
426
    fn permission_bit(bits: u16, bit: u16, character: &'static str, style: Style) -> ANSIString<'static> {
B
Ben S 已提交
427
        let bi32 = bit as u16;
428
        if bits & bi32 == bi32 {
B
Ben S 已提交
429
            style.paint(character)
B
Ben S 已提交
430 431
        }
        else {
B
Ben S 已提交
432
            GREY.paint("-")
433 434
        }
    }
B
Ben S 已提交
435 436 437 438 439 440 441 442 443

    /// For this file, return a vector of alternate file paths that, if any of
    /// them exist, mean that *this* file should be coloured as `Compiled`.
    ///
    /// The point of this is to highlight compiled files such as `foo.o` when
    /// their source file `foo.c` exists in the same directory. It's too
    /// dangerous to highlight *all* compiled, so the paths in this vector
    /// are checked for existence first: for example, `foo.js` is perfectly
    /// valid without `foo.coffee`.
444
    pub fn get_source_files(&self) -> Vec<PathBuf> {
B
Ben S 已提交
445
        if let Some(ref ext) = self.ext {
446
            match &ext[..] {
B
Ben S 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
                "class" => vec![self.path.with_extension("java")],  // Java
                "css"   => vec![self.path.with_extension("sass"),   self.path.with_extension("less")],  // SASS, Less
                "elc"   => vec![self.path.with_extension("el")],    // Emacs Lisp
                "hi"    => vec![self.path.with_extension("hs")],    // Haskell
                "js"    => vec![self.path.with_extension("coffee"), self.path.with_extension("ts")],  // CoffeeScript, TypeScript
                "o"     => vec![self.path.with_extension("c"),      self.path.with_extension("cpp")], // C, C++
                "pyc"   => vec![self.path.with_extension("py")],    // Python

                "aux" => vec![self.path.with_extension("tex")],  // TeX: auxiliary file
                "bbl" => vec![self.path.with_extension("tex")],  // BibTeX bibliography file
                "blg" => vec![self.path.with_extension("tex")],  // BibTeX log file
                "lof" => vec![self.path.with_extension("tex")],  // TeX list of figures
                "log" => vec![self.path.with_extension("tex")],  // TeX log file
                "lot" => vec![self.path.with_extension("tex")],  // TeX list of tables
                "toc" => vec![self.path.with_extension("tex")],  // TeX table of contents

                _ => vec![],  // No source files if none of the above
            }
        }
        else {
            vec![]  // No source files if there's no extension, either!
        }
    }
B
Ben S 已提交
470 471

    fn git_status(&self) -> Cell {
B
Ben S 已提交
472 473
        let status = match self.dir {
            None    => GREY.paint("--").to_string(),
B
Benjamin Sago 已提交
474 475 476
            Some(d) => {
                let cwd = match current_dir() {
                    Err(_)  => Path::new(".").join(&self.path),
477
                    Ok(dir) => dir.join(&self.path),
B
Benjamin Sago 已提交
478 479 480 481
                };

                d.git_status(&cwd, self.is_directory())
            },
B
Ben S 已提交
482 483
        };

B
Ben S 已提交
484 485
        Cell { text: status, length: 2 }
    }
B
Ben S 已提交
486 487
}

488 489 490 491 492 493 494
/// Extract the filename to display from a path, converting it from UTF-8
/// lossily, into a String.
///
/// The filename to display is the last component of the path. However,
/// the path has no components for `.`, `..`, and `/`, so in these
/// cases, the entire path is used.
fn path_filename(path: &Path) -> String {
495 496 497 498
    match path.iter().last() {
        Some(os_str) => os_str.to_string_lossy().to_string(),
        None => ".".to_string(),  // can this even be reached?
    }
499 500
}

B
Ben S 已提交
501
/// Extract an extension from a string, if one is present, in lowercase.
B
Ben S 已提交
502 503 504
///
/// The extension is the series of characters after the last dot. This
/// deliberately counts dotfiles, so the ".git" folder has the extension "git".
B
Ben S 已提交
505 506 507 508
///
/// ASCII lowercasing is used because these extensions are only compared
/// against a pre-compiled list of extensions which are known to only exist
/// within ASCII, so it's alright.
B
Ben S 已提交
509
fn ext<'a>(name: &'a str) -> Option<String> {
B
Ben S 已提交
510
    name.rfind('.').map(|p| name[p+1..].to_ascii_lowercase())
B
Ben S 已提交
511
}
B
Benjamin Sago 已提交
512

B
Ben S 已提交
513
#[cfg(broken_test)]
B
Ben S 已提交
514
pub mod test {
515
    pub use super::*;
516

517
    pub use column::{Cell, Column};
518 519
    pub use output::details::UserLocale;

520 521
    pub use users::{User, Group};
    pub use users::mock::MockUsers;
B
Benjamin Sago 已提交
522

523 524
    pub use ansi_term::Style::Plain;
    pub use ansi_term::Colour::Yellow;
B
Benjamin Sago 已提交
525

B
Benjamin Sago 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    #[test]
    fn extension() {
        assert_eq!(Some("dat".to_string()), super::ext("fester.dat"))
    }

    #[test]
    fn dotfile() {
        assert_eq!(Some("vimrc".to_string()), super::ext(".vimrc"))
    }

    #[test]
    fn no_extension() {
        assert_eq!(None, super::ext("jarlsberg"))
    }

B
Ben S 已提交
541 542 543 544
    pub fn new_file(stat: io::FileStat, path: &'static str) -> File {
        File::with_stat(stat, &Path::new(path), None, false)
    }

B
Detab  
Ben S 已提交
545 546
    pub fn dummy_stat() -> io::FileStat {
        io::FileStat {
B
Benjamin Sago 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
            size: 0,
            kind: io::FileType::RegularFile,
            created: 0,
            modified: 0,
            accessed: 0,
            perm: io::USER_READ,
            unstable: io::UnstableFileStat {
                inode: 0,
                device: 0,
                rdev: 0,
                nlink: 0,
                uid: 0,
                gid: 0,
                blksize: 0,
                blocks: 0,
                flags: 0,
                gen: 0,
            }
        }
    }

568 569
    pub fn dummy_locale() -> UserLocale {
        UserLocale::default()
B
Ben S 已提交
570 571
    }

572 573
    mod users {
        use super::*;
B
Benjamin Sago 已提交
574

575 576 577 578
        #[test]
        fn named() {
            let mut stat = dummy_stat();
            stat.unstable.uid = 1000;
B
Benjamin Sago 已提交
579

B
Ben S 已提交
580
            let file = new_file(stat, "/hi");
B
Benjamin Sago 已提交
581

582 583 584 585
            let mut users = MockUsers::with_current_uid(1000);
            users.add_user(User { uid: 1000, name: "enoch".to_string(), primary_group: 100 });

            let cell = Cell::paint(Yellow.bold(), "enoch");
B
Ben S 已提交
586
            assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
587
        }
B
Benjamin Sago 已提交
588

589 590 591 592
        #[test]
        fn unnamed() {
            let mut stat = dummy_stat();
            stat.unstable.uid = 1000;
B
Benjamin Sago 已提交
593

B
Ben S 已提交
594
            let file = new_file(stat, "/hi");
B
Benjamin Sago 已提交
595

596
            let mut users = MockUsers::with_current_uid(1000);
B
Benjamin Sago 已提交
597

598
            let cell = Cell::paint(Yellow.bold(), "1000");
B
Ben S 已提交
599
            assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
600 601 602 603 604 605 606
        }

        #[test]
        fn different_named() {
            let mut stat = dummy_stat();
            stat.unstable.uid = 1000;

B
Ben S 已提交
607
            let file = new_file(stat, "/hi");
B
Benjamin Sago 已提交
608

609 610
            let mut users = MockUsers::with_current_uid(3);
            users.add_user(User { uid: 1000, name: "enoch".to_string(), primary_group: 100 });
B
Benjamin Sago 已提交
611

612
            let cell = Cell::paint(Plain, "enoch");
B
Ben S 已提交
613
            assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
614 615 616 617 618 619
        }

        #[test]
        fn different_unnamed() {
            let mut stat = dummy_stat();
            stat.unstable.uid = 1000;
B
Benjamin Sago 已提交
620

B
Ben S 已提交
621
            let file = new_file(stat, "/hi");
B
Benjamin Sago 已提交
622

623 624 625
            let mut users = MockUsers::with_current_uid(3);

            let cell = Cell::paint(Plain, "1000");
B
Ben S 已提交
626
            assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
627
        }
B
Ben S 已提交
628 629 630 631 632 633 634 635 636 637 638 639 640

        #[test]
        fn overflow() {
            let mut stat = dummy_stat();
            stat.unstable.uid = 2_147_483_648;

            let file = new_file(stat, "/hi");

            let mut users = MockUsers::with_current_uid(3);

            let cell = Cell::paint(Plain, "2147483648");
            assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
        }
B
Benjamin Sago 已提交
641 642
    }

643 644 645 646 647 648 649 650
    mod groups {
        use super::*;

        #[test]
        fn named() {
            let mut stat = dummy_stat();
            stat.unstable.gid = 100;

B
Ben S 已提交
651
            let file = new_file(stat, "/hi");
652 653 654

            let mut users = MockUsers::with_current_uid(3);
            users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![] });
B
Benjamin Sago 已提交
655

656
            let cell = Cell::paint(Plain, "folk");
B
Ben S 已提交
657
            assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
658 659 660 661 662 663 664
        }

        #[test]
        fn unnamed() {
            let mut stat = dummy_stat();
            stat.unstable.gid = 100;

B
Ben S 已提交
665
            let file = new_file(stat, "/hi");
666 667 668 669

            let mut users = MockUsers::with_current_uid(3);

            let cell = Cell::paint(Plain, "100");
B
Ben S 已提交
670
            assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
671 672 673 674 675 676
        }

        #[test]
        fn primary() {
            let mut stat = dummy_stat();
            stat.unstable.gid = 100;
B
Benjamin Sago 已提交
677

B
Ben S 已提交
678
            let file = new_file(stat, "/hi");
B
Benjamin Sago 已提交
679

680 681 682 683 684
            let mut users = MockUsers::with_current_uid(3);
            users.add_user(User { uid: 3, name: "eve".to_string(), primary_group: 100 });
            users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![] });

            let cell = Cell::paint(Yellow.bold(), "folk");
B
Ben S 已提交
685
            assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
686 687 688 689 690 691 692
        }

        #[test]
        fn secondary() {
            let mut stat = dummy_stat();
            stat.unstable.gid = 100;

B
Ben S 已提交
693
            let file = new_file(stat, "/hi");
694 695 696 697 698 699

            let mut users = MockUsers::with_current_uid(3);
            users.add_user(User { uid: 3, name: "eve".to_string(), primary_group: 12 });
            users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![ "eve".to_string() ] });

            let cell = Cell::paint(Yellow.bold(), "folk");
B
Ben S 已提交
700
            assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
701
        }
B
Ben S 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714

        #[test]
        fn overflow() {
            let mut stat = dummy_stat();
            stat.unstable.gid = 2_147_483_648;

            let file = new_file(stat, "/hi");

            let mut users = MockUsers::with_current_uid(3);

            let cell = Cell::paint(Plain, "2147483648");
            assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
        }
B
Benjamin Sago 已提交
715 716
    }
}