exa.rs 1.5 KB
Newer Older
B
Ben S 已提交
1
extern crate getopts;
B
Ben S 已提交
2
use std::os;
B
Ben S 已提交
3 4 5
use std::io::fs;

use file::File;
B
Ben S 已提交
6
use column::defaultColumns;
B
Ben S 已提交
7

B
Ben S 已提交
8 9 10 11
pub mod colours;
pub mod column;
pub mod format;
pub mod file;
B
Ben S 已提交
12

B
Ben S 已提交
13 14 15 16
struct Options {
    showInvisibles: bool,
}

B
Ben S 已提交
17
fn main() {
B
Ben S 已提交
18 19 20 21 22 23 24 25
    let args = os::args();
    let program = args[0].as_slice();
    let opts = ~[
        getopts::optflag("a", "all", "show dot-files")
    ];

    let matches = match getopts::getopts(args.tail(), opts) {
        Ok(m) => m,
B
Ben S 已提交
26
        Err(f) => fail!("Invalid options\n{}", f.to_err_msg()),
B
Ben S 已提交
27 28 29 30 31 32
    };

    let opts = Options {
        showInvisibles: matches.opt_present("all")
    };

B
Ben S 已提交
33 34 35 36 37 38
    let strs = if matches.free.is_empty() {
        vec!("./".to_owned())
    }
    else {
        matches.free.clone()
    };
B
Ben S 已提交
39 40 41

    for dir in strs.move_iter() {
        list(opts, Path::new(dir))
B
Ben S 已提交
42 43 44
    }
}

B
Ben S 已提交
45
fn list(opts: Options, path: Path) {
46 47 48 49 50 51 52 53
    let mut files = match fs::readdir(&path) {
        Ok(files) => files,
        Err(e) => fail!("readdir: {}", e),
    };
    files.sort_by(|a, b| a.filename_str().cmp(&b.filename_str()));
    for subpath in files.iter() {
        let file = File::from_path(subpath);

B
Ben S 已提交
54
        if file.is_dotfile() && !opts.showInvisibles {
B
Ben S 已提交
55 56 57
            continue;
        }

B
Ben S 已提交
58
        let columns = defaultColumns();
B
Ben S 已提交
59

B
Ben S 已提交
60
        let mut cells = columns.iter().map(|c| file.display(c));
B
Ben S 已提交
61

B
Ben S 已提交
62 63 64 65 66 67 68 69 70 71
        let mut first = true;
        for cell in cells {
            if first {
                first = false;
            } else {
                print!(" ");
            }
            print!("{}", cell);
        }
        print!("\n");
B
Ben S 已提交
72 73
    }
}