//! 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: `
` or the size in bytes. On file systems
//! with Unix permissions (ext2) it also shows them, like `-rw-r--r--`, and
//! where symlinks point: `hello-link -> hello.txt`.
#![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,
link: bool,
dev: bool, // a device like /dev/fb0 (shown as )
size: u64,
mode: u64, // 0 = no permissions on this file system
target: String, // symlinks (with -l): where they point
}
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 {
let entry = Entry { name: String::from(*path), dir: false, link: false, dev: st.kind == KIND_DEVICE, size: st.size, mode: st.mode, target: String::new() };
print_entries(&[entry], 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, 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 != ".." {
let (dir, link, dev) = (d_type == 4, d_type == 10, d_type == 2); // DT_DIR, DT_LNK, DT_CHR
entries.push(Entry { name: String::from(name), dir, link, dev, size: 0, mode: 0, target: String::new() });
}
});
}
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() {
let full = format!("{}/{}", path, e.name);
if e.link {
let mut buf = [0u8; 256];
let n = readlink(&full, &mut buf);
if n >= 0 {
e.target = String::from(core::str::from_utf8(&buf[..n as usize]).unwrap_or("?"));
}
} else if stat(&full, &mut st) == 0 {
e.size = st.size;
e.mode = st.mode;
}
}
}
Ok(entries)
}
fn print_entries(entries: &[Entry], long: bool, columns: bool) {
if long {
for e in entries {
// `drwxr-xr-x ` in front if the file system has permissions.
let perms = if e.mode != 0 || e.link { format!("{} ", mode_string(e)) } else { String::new() };
if e.dir {
println!("{} {}/", perms, e.name);
} else if e.link {
println!("{} {} -> {}", perms, e.name, e.target);
} else if e.dev {
println!("{} {}", perms, e.name);
} else {
println!("{}{:>10} {}", perms, e.size, e.name);
}
}
return;
}
let shown = |e: &Entry| match (e.dir, e.link) {
(true, _) => format!("{}/", e.name),
(_, true) => format!("{}@", e.name), // like `ls -F`
_ => 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!("{: String {
if e.link {
return String::from("lrwxrwxrwx"); // symlink permissions are never used
}
let mut s = String::from(if e.dir { "d" } else if e.dev { "c" } else { "-" });
for shift in [6, 3, 0] {
let bits = (e.mode >> shift) & 7;
s.push(if bits & 4 != 0 { 'r' } else { '-' });
s.push(if bits & 2 != 0 { 'w' } else { '-' });
s.push(if bits & 1 != 0 { 'x' } else { '-' });
}
s
}