Tunal/crates/tunal-core/examples/ls.rs
2026-11-18 09:46:28 -06:00

98 lines
3.5 KiB
Rust

//! Lists folders through the location layer and prints timing.
//! `cargo run -p tunal-core --example ls -- [--watch] <dir>...`
use std::io::{BufWriter, Write};
use std::ops::ControlFlow;
use std::path::Path;
use std::time::Instant;
use tunal_core::{Kind, Locations, Uri, WatchEvent, display_name};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let watch = args.iter().any(|a| a == "--watch");
let dirs: Vec<&String> = args.iter().filter(|a| *a != "--watch").collect();
if dirs.is_empty() {
eprintln!("usage: ls [--watch] <dir>...");
std::process::exit(2);
}
let locations = Locations::with_local();
let mut failed = false;
for dir in &dirs {
let uri = Uri::from_path(Path::new(dir));
let backend = locations.resolve(&uri).expect("file backend registered");
let start = Instant::now();
let mut out = BufWriter::new(std::io::stdout().lock());
let (mut count, mut chunks) = (0, 0);
let result = backend.list(&uri, &mut |entries| {
chunks += 1;
for e in entries {
count += 1;
let kind = match &e.kind {
Kind::File => "file".to_owned(),
Kind::Dir => "dir".to_owned(),
Kind::Special => "special".to_owned(),
Kind::Symlink {
target,
target_type,
} => format!("link -> {} ({target_type:?})", display_name(target)),
};
let _ = writeln!(
out,
"{:04o} {:>5}:{:<5} {:>10} {:<28} {}{} [{kind}]",
e.mode,
e.uid,
e.gid,
e.size,
e.mime,
e.display_name,
if e.hidden { " (hidden)" } else { "" },
);
if e.display_name.as_bytes() != e.name {
let _ = writeln!(out, " raw: {}", uri.join(&e.name));
}
}
ControlFlow::Continue(())
});
drop(out);
let elapsed = start.elapsed();
match result {
Ok(()) => eprintln!("{uri}: {count} entries in {chunks} chunks, {elapsed:.2?}"),
Err(e) => {
failed = true;
eprintln!(
"{uri}: error: {e:?} ({e}), needs elevation: {}",
e.needs_elevation()
);
}
}
}
if watch {
let uri = Uri::from_path(Path::new(dirs[0]));
let backend = locations.resolve(&uri).expect("file backend registered");
let _watch = backend
.watch(
&uri,
Box::new(|event| match event {
WatchEvent::Changed(uris) => {
let names: Vec<String> = uris
.iter()
.map(|u| display_name(u.file_name().unwrap_or(b"/")))
.collect();
eprintln!("changed ({}): {}", names.len(), names.join(", "));
}
WatchEvent::Error(e) => eprintln!("watch error: {e}"),
}),
)
.unwrap_or_else(|e| panic!("watch {uri}: {e}"));
eprintln!("watching {uri}; Ctrl+C to stop");
loop {
std::thread::park();
}
}
if failed {
std::process::exit(1);
}
}