Tunal/crates/tunal-core/examples/ops.rs
astar76 c51e63a4a9 S007: file operations engine, freedesktop trash and trash:/// backend
Jobs with progress, cancel, conflict and error requests; scan pass,
copy_file_range and stream copies, rename moves; per-filesystem trash
with .trashinfo, restore and empty; ops smoke example.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:04:31 -06:00

359 lines
12 KiB
Rust

//! Smoke run of the job engine and the trash inside a scratch folder.
//! `XDG_DATA_HOME=<dir>/data cargo run -p tunal-core --example ops -- <dir>`
//! (refuses to run unless `XDG_DATA_HOME` is inside `<dir>`, so the real trash is never touched).
use std::ffi::OsStr;
use std::fs;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::Duration;
use tunal_core::ops::{
ConflictAction, ConflictChoice, ErrorAction, JobEvent, JobId, JobKind, Jobs, Report,
};
use tunal_core::{Locations, Uri, display_name, trash};
/// Makes the event sink slow (like a busy UI) so a cancel lands in the middle of a file.
static SLOW: AtomicBool = AtomicBool::new(false);
fn main() {
let Some(dir) = std::env::args().nth(1).map(PathBuf::from) else {
eprintln!("usage: XDG_DATA_HOME=<dir>/data ops <dir>");
std::process::exit(2);
};
let dir = std::path::absolute(&dir).expect("absolute dir");
let data = std::env::var_os("XDG_DATA_HOME").map(PathBuf::from);
let Some(data) = data.filter(|d| d.starts_with(&dir)) else {
eprintln!("ops: XDG_DATA_HOME must point inside {}", dir.display());
std::process::exit(2);
};
let src = dir.join("src");
let dst = dir.join("dst");
let _ = fs::remove_dir_all(&src);
let _ = fs::remove_dir_all(&dst);
fs::create_dir_all(src.join("sub")).unwrap();
fs::create_dir_all(&dst).unwrap();
fs::write(src.join("a.txt"), "new a\n").unwrap();
fs::write(src.join("big.bin"), vec![7u8; 24 << 20]).unwrap();
fs::write(src.join("sub/b.txt"), "b\n").unwrap();
std::os::unix::fs::symlink("b.txt", src.join("sub/link")).unwrap();
fs::write(dst.join("a.txt"), "old a\n").unwrap();
let (tx, events) = mpsc::channel();
let jobs = Jobs::new(Locations::with_local(), move |id, event| {
let progress = matches!(event, JobEvent::Progress(_));
let _ = tx.send((id, event));
if progress && SLOW.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(150));
}
});
let uri = |p: &Path| Uri::from_path(p);
let children = |p: &Path| -> Vec<Uri> {
let mut v: Vec<Uri> = fs::read_dir(p)
.unwrap()
.map(|e| Uri::from_path(&e.unwrap().path()))
.collect();
v.sort_by(|a, b| a.path().cmp(b.path()));
v
};
println!("== copy src/* -> dst (a.txt exists: auto-rename)");
let job = JobKind::Copy {
sources: children(&src),
dest: uri(&dst),
};
report(run(&jobs, &events, job, ConflictAction::AutoRename));
println!("== copy dst/a.txt into dst (same folder: numbered copy)");
let job = JobKind::Copy {
sources: vec![uri(&dst.join("a.txt"))],
dest: uri(&dst),
};
report(run(&jobs, &events, job, ConflictAction::Skip));
println!("== copy src into src/sub (folder into itself: refused)");
let job = JobKind::Copy {
sources: vec![uri(&src)],
dest: uri(&src.join("sub")),
};
report(run(&jobs, &events, job, ConflictAction::Skip));
println!("== move src/sub -> dst (dst/sub exists: overwrite merges)");
let job = JobKind::Move {
sources: vec![uri(&src.join("sub"))],
dest: uri(&dst),
};
report(run(&jobs, &events, job, ConflictAction::Overwrite));
println!("== trash dst/a.txt and dst/big.bin");
let job = JobKind::Trash(vec![uri(&dst.join("a.txt")), uri(&dst.join("big.bin"))]);
report(run(&jobs, &events, job, ConflictAction::Skip));
list_trash();
let info = data.join("Trash/info/a.txt.trashinfo");
println!(
" {}:\n{}",
info.display(),
fs::read_to_string(&info).unwrap_or_default()
);
println!("== restore both (dst/a.txt recreated first: rename on conflict)");
fs::write(dst.join("a.txt"), "a made after trashing\n").unwrap();
let items = trash::items().into_iter().map(|i| i.uri).collect();
report(run(
&jobs,
&events,
JobKind::Restore(items),
ConflictAction::Rename(b"a restored.txt".to_vec()),
));
list_trash();
println!("== trash dst/sub and two files both named dup.txt, then empty the trash");
let job = JobKind::Trash(vec![uri(&dst.join("sub"))]);
report(run(&jobs, &events, job, ConflictAction::Skip));
let backend = Locations::with_local().resolve(&trash::root()).unwrap();
for folder in [trash::root(), trash::root().join(b"home:sub")] {
let mut names = Vec::new();
backend
.list(&folder, &mut |chunk| {
names.extend(chunk.into_iter().map(|e| e.display_name));
std::ops::ControlFlow::Continue(())
})
.unwrap();
names.sort();
println!(" list {folder}: {names:?}");
}
for text in ["first dup\n", "second dup\n"] {
fs::write(dst.join("dup.txt"), text).unwrap();
let job = JobKind::Trash(vec![uri(&dst.join("dup.txt"))]);
report(run(&jobs, &events, job, ConflictAction::Skip));
}
list_trash();
report(run(
&jobs,
&events,
JobKind::EmptyTrash,
ConflictAction::Skip,
));
list_trash();
println!("== cancel a copy of dst/big.bin into dst/cancel");
report(run(
&jobs,
&events,
JobKind::Mkdir(uri(&dst.join("cancel"))),
ConflictAction::Skip,
));
let job = JobKind::Copy {
sources: vec![uri(&dst.join("big.bin"))],
dest: uri(&dst.join("cancel")),
};
SLOW.store(true, Ordering::Relaxed);
report(run_with(&jobs, &events, job, ConflictAction::Skip, true));
SLOW.store(false, Ordering::Relaxed);
println!(
" partial file left: {}",
dst.join("cancel/big.bin").exists()
);
println!(
"== move (rename) dst/a (3).txt into dst/cancel, rename it, link it, delete dst/cancel"
);
let job = JobKind::Move {
sources: vec![uri(&dst.join("a (3).txt"))],
dest: uri(&dst.join("cancel")),
};
report(run(&jobs, &events, job, ConflictAction::Skip));
let job = JobKind::Rename {
from: uri(&dst.join("cancel/a (3).txt")),
to: uri(&dst.join("cancel/old.txt")),
};
report(run(&jobs, &events, job, ConflictAction::Skip));
let job = JobKind::Link {
sources: vec![uri(&dst.join("cancel/old.txt"))],
dest: uri(&dst),
};
report(run(&jobs, &events, job, ConflictAction::Skip));
println!(" link: {:?}", fs::read_link(dst.join("old.txt")).ok());
let _ = fs::remove_file(dst.join("old.txt"));
report(run(
&jobs,
&events,
JobKind::Delete(vec![uri(&dst.join("cancel"))]),
ConflictAction::Skip,
));
println!(" src/sub after move: exists {}", src.join("sub").exists());
println!("== copy an unreadable file next to a readable one (partial failure)");
fs::write(src.join("locked.txt"), "secret\n").unwrap();
fs::set_permissions(src.join("locked.txt"), fs::Permissions::from_mode(0o000)).unwrap();
let job = JobKind::Copy {
sources: vec![uri(&src.join("locked.txt")), uri(&src.join("a.txt"))],
dest: uri(&dst.join("partial")),
};
report(run(
&jobs,
&events,
JobKind::Mkdir(uri(&dst.join("partial"))),
ConflictAction::Skip,
));
report(run(&jobs, &events, job, ConflictAction::Skip));
fs::set_permissions(src.join("locked.txt"), fs::Permissions::from_mode(0o644)).unwrap();
println!("== trash and restore a non-UTF-8 name with a space");
let odd = dst.join(OsStr::from_bytes(b"odd \xff name.txt"));
fs::write(&odd, "odd\n").unwrap();
report(run(
&jobs,
&events,
JobKind::Trash(vec![uri(&odd)]),
ConflictAction::Skip,
));
list_trash();
let info = data
.join("Trash/info")
.join(OsStr::from_bytes(b"odd \xff name.txt.trashinfo"));
println!(
" {}",
fs::read_to_string(&info)
.unwrap_or_default()
.replace('\n', " | ")
);
let items: Vec<Uri> = trash::items().into_iter().map(|i| i.uri).collect();
println!(" copy it out of trash:/// into dst/partial (stream path)");
let job = JobKind::Copy {
sources: items.clone(),
dest: uri(&dst.join("partial")),
};
report(run(&jobs, &events, job, ConflictAction::Skip));
report(run(
&jobs,
&events,
JobKind::Restore(items),
ConflictAction::Skip,
));
println!(" restored: {}", odd.exists());
println!("== final dst");
let mut names: Vec<_> = fs::read_dir(&dst)
.unwrap()
.map(|e| e.unwrap().file_name())
.collect();
names.sort();
for raw in names {
let path = dst.join(&raw);
let name = raw.to_string_lossy();
if path.is_dir() {
println!(
" {name}/: {} item(s)",
fs::read_dir(&path).unwrap().count()
);
continue;
}
let content = fs::read(path).unwrap_or_default();
let shown = if content.len() < 64 {
String::from_utf8_lossy(&content).trim().to_owned()
} else {
format!("{} bytes", content.len())
};
println!(" {name}: {shown}");
}
}
/// Submits a job, prints its events and answers requests until it finishes.
fn run(
jobs: &Jobs,
events: &mpsc::Receiver<(JobId, JobEvent)>,
kind: JobKind,
on_conflict: ConflictAction,
) -> Report {
run_with(jobs, events, kind, on_conflict, false)
}
/// Like `run`; with `cancel`, cancels once the first bytes were copied.
fn run_with(
jobs: &Jobs,
events: &mpsc::Receiver<(JobId, JobEvent)>,
kind: JobKind,
on_conflict: ConflictAction,
cancel: bool,
) -> Report {
let handle = jobs.submit(kind);
for (id, event) in events {
if id != handle.id() {
continue;
}
match event {
JobEvent::Progress(p) if cancel && p.done_bytes > 0 => {
println!(
" progress {}/{} bytes -> cancel",
p.done_bytes, p.total_bytes
);
handle.cancel();
}
JobEvent::Progress(p) => println!(
" progress {:?}: {}/{} files, {}/{} bytes{}",
p.phase,
p.done_files,
p.total_files,
p.done_bytes,
p.total_bytes,
p.current
.map(|c| format!(", at {}", display_name(c.file_name().unwrap_or(b"/"))))
.unwrap_or_default()
),
JobEvent::Conflict(request) => {
println!(" conflict: {} exists -> {:?}", request.target, on_conflict);
request.reply.send(ConflictChoice {
action: on_conflict.clone(),
apply_to_all: false,
});
}
JobEvent::Error(request) => {
println!(
" error at {}: {} (elevation: {}) -> Skip",
request.uri,
request.error,
request.needs_elevation()
);
request.reply.send(ErrorAction::Skip);
}
JobEvent::Finished(report) => return report,
}
}
panic!("job worker stopped");
}
fn report(report: Report) {
let failures: Vec<String> = report
.failures
.iter()
.map(|(uri, e)| format!("{} ({e})", display_name(uri.file_name().unwrap_or(b"/"))))
.collect();
println!(
" finished: {} files, {} bytes, cancelled {}, failures {failures:?}",
report.done_files, report.done_bytes, report.cancelled
);
}
fn list_trash() {
let items = trash::items();
println!(" trash: {} item(s)", items.len());
for item in items {
let date = item.deleted.map(age).unwrap_or_else(|| "no date".into());
println!(
" {} ({}) from {}, deleted {date}",
item.uri, item.entry.display_name, item.original
);
}
}
fn age(t: std::time::SystemTime) -> String {
match t.elapsed() {
Ok(age) => format!("{} s ago", age.as_secs()),
Err(_) => "in the future".into(),
}
}