RustForge

rust-kernel

Rustbelt: a hobby x86_64 kernel written in Rust

rust-kernel / user / ls.rs
3571 bytes ยท raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//! ls [-l] [path...] -- list directories (shell alias: dir).
//!
//! On the console the names are printed in columns; into a pipe or file
//! one per line (like the real `ls`, so `ls | wc -l` counts files).
//! -l adds sizes, DOS style: `<DIR>` or the size in bytes.
#![no_std]
#![no_main]

extern crate alloc;

#[macro_use]
#[path = "ulib.rs"]
mod ulib;

use alloc::{format, string::String, vec::Vec};
use ulib::*;

struct Entry {
    name: String,
    dir: bool,
    size: u64,
}

fn main() -> i64 {
    let mut long = false;
    let mut paths = Vec::new();
    for i in 1..argc() {
        match arg(i) {
            Some("-l") => long = true,
            Some(a) => paths.push(a),
            None => {}
        }
    }
    if paths.is_empty() {
        paths.push(".");
    }
    let mut st = Stat::default();
    let columns = !long && fstat(1, &mut st) == 0 && st.kind == KIND_CONSOLE;

    let mut status = 0;
    for (i, path) in paths.iter().enumerate() {
        let r = stat(path, &mut st);
        if r < 0 {
            eprintln!("ls: {}: {}", path, strerror(r));
            status = 1;
            continue;
        }
        if st.kind != KIND_DIR {
            print_entries(&[Entry { name: String::from(*path), dir: false, size: st.size }], long, columns);
            continue;
        }
        if paths.len() > 1 {
            println!("{}{}:", if i > 0 { "\n" } else { "" }, path);
        }
        match read_dir(path, long) {
            Ok(entries) => print_entries(&entries, long, columns),
            Err(e) => {
                eprintln!("ls: {}: {}", path, strerror(e));
                status = 1;
            }
        }
    }
    status
}

/// All entries of a directory, sorted by name.
fn read_dir(path: &str, long: bool) -> Result<Vec<Entry>, i64> {
    let fd = open(path, 0);
    if fd < 0 {
        return Err(fd);
    }
    let mut entries = Vec::new();
    let mut buf = [0u8; 1024];
    loop {
        // Each call returns as many records as fit; 0 = no more.
        let n = getdents64(fd, &mut buf);
        if n <= 0 {
            break;
        }
        for_each_dirent(&buf, n as usize, |name, d_type| {
            if name != "." && name != ".." {
                entries.push(Entry { name: String::from(name), dir: d_type == 4, size: 0 });
            }
        });
    }
    close(fd);
    entries.sort_by(|a, b| a.name.cmp(&b.name));
    if long {
        let mut st = Stat::default();
        for e in entries.iter_mut().filter(|e| !e.dir) {
            if stat(&format!("{}/{}", path, e.name), &mut st) == 0 {
                e.size = st.size;
            }
        }
    }
    Ok(entries)
}

fn print_entries(entries: &[Entry], long: bool, columns: bool) {
    if long {
        for e in entries {
            if e.dir {
                println!("     <DIR>  {}/", e.name);
            } else {
                println!("{:>10}  {}", e.size, e.name);
            }
        }
        return;
    }
    let shown = |e: &Entry| if e.dir { format!("{}/", e.name) } else { e.name.clone() };
    if !columns {
        entries.iter().for_each(|e| println!("{}", shown(e)));
        return;
    }
    // Columns across an 80-character screen.
    let width = entries.iter().map(|e| shown(e).len() + 2).max().unwrap_or(1);
    let per_line = (79 / width).max(1);
    for (i, e) in entries.iter().enumerate() {
        let last = i + 1 == entries.len() || (i + 1) % per_line == 0;
        if last {
            println!("{}", shown(e));
        } else {
            print!("{:<w$}", shown(e), w = width);
        }
    }
}