S032: tests for core, ops, trash, dirmeta and the elevation protocol
Fixes: file over folder with Overwrite, CRLF .directory files, stray blank line after removing an added group. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
parent
70d0d2d5b1
commit
35715817aa
16 changed files with 2206 additions and 11 deletions
5
Cargo.lock
generated
5
Cargo.lock
generated
|
|
@ -7024,6 +7024,7 @@ dependencies = [
|
|||
"jiff",
|
||||
"mime_guess",
|
||||
"notify-debouncer-mini",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -7041,6 +7042,9 @@ dependencies = [
|
|||
[[package]]
|
||||
name = "tunal-dirmeta"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tunal-elevate"
|
||||
|
|
@ -7048,6 +7052,7 @@ version = "0.1.0"
|
|||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tunal-core",
|
||||
]
|
||||
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ license = "GPL-3.0-or-later"
|
|||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
tempfile = "3.27"
|
||||
slint = "1.19"
|
||||
slint-build = "1.19"
|
||||
zbus = { version = "5.19", default-features = false, features = ["async-io", "blocking-api"] }
|
||||
|
|
|
|||
|
|
@ -10,12 +10,12 @@ Test the pure logic and filesystem code of the solid app (D-013): location layer
|
|||
CLAUDE.md §3, §4; docs/PROGRESS.md (known bugs); the public APIs of these crates.
|
||||
|
||||
## Steps
|
||||
- [ ] tunal-core: URIs, listing edge cases (non-UTF-8, symlinks, permission denied, 10 000 entries), watch diffs — temp dirs only.
|
||||
- [ ] Ops: copy/move/delete with conflicts (each resolution, apply to all), cancel mid-job, partial failures, cross-device move, copy into self refused, auto-rename.
|
||||
- [ ] Trash: trash/restore/empty with `XDG_DATA_HOME` in a temp dir, `.trashinfo` encoding, name collisions.
|
||||
- [ ] dirmeta: byte-exact round trips with comments/unknown keys/localized names.
|
||||
- [ ] Elevation protocol: encode/decode, helper driven without pkexec in a temp dir.
|
||||
- [ ] Fix bugs the tests find (regression test each) or log them in PROGRESS.
|
||||
- [x] tunal-core: URIs, listing edge cases (non-UTF-8, symlinks, permission denied, 10 000 entries), watch diffs — temp dirs only.
|
||||
- [x] Ops: copy/move/delete with conflicts (each resolution, apply to all), cancel mid-job, partial failures, cross-device move, copy into self refused, auto-rename.
|
||||
- [x] Trash: trash/restore/empty with `XDG_DATA_HOME` in a temp dir, `.trashinfo` encoding, name collisions.
|
||||
- [x] dirmeta: byte-exact round trips with comments/unknown keys/localized names.
|
||||
- [x] Elevation protocol: encode/decode, helper driven without pkexec in a temp dir.
|
||||
- [x] Fix bugs the tests find (regression test each) or log them in PROGRESS.
|
||||
- [ ] PROGRESS entry, INDEX line, commit `S032: …`
|
||||
|
||||
## End criteria
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
|
|||
|
||||
## 12 Testing
|
||||
|
||||
- [ ] [S032 — Automated tests: core, ops, trash, dirmeta, elevation protocol](12%20Testing/S032-tests-core.md) · Sonnet high
|
||||
- [x] [S032 — Automated tests: core, ops, trash, dirmeta, elevation protocol](12%20Testing/S032-tests-core.md) · Sonnet high
|
||||
- [ ] [S033 — Automated tests: thumbs, tags, MusicBrainz, player, ssh, SFTP, MTP](12%20Testing/S033-tests-media-net-devices.md) · Sonnet high
|
||||
- [ ] [S034 — Screenshot matrix and UI review](12%20Testing/S034-ui-review.md) · Opus high
|
||||
- [ ] [S035 — Motion audit and visual sign-off](12%20Testing/S035-motion-audit.md) · Opus high 🧑
|
||||
|
|
|
|||
|
|
@ -9,3 +9,7 @@ publish.workspace = true
|
|||
notify-debouncer-mini.workspace = true
|
||||
mime_guess.workspace = true
|
||||
jiff.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
jiff.workspace = true
|
||||
|
|
|
|||
|
|
@ -246,9 +246,14 @@ impl Runner<'_> {
|
|||
self.step(src);
|
||||
let copied = match &entry.kind {
|
||||
Kind::Dir => return self.place_dir(sb, db, src, entry, target, mv),
|
||||
Kind::File => self
|
||||
.attempt(src, |r| r.copy_file(sb, db, src, entry, target))?
|
||||
.is_some(),
|
||||
Kind::File => {
|
||||
// A file replacing a folder: the folder goes first.
|
||||
if target.overwrite && db.stat(&target.uri).is_ok_and(|t| t.kind == Kind::Dir) {
|
||||
self.delete_tree(db, &target.uri, false)?;
|
||||
}
|
||||
self.attempt(src, |r| r.copy_file(sb, db, src, entry, target))?
|
||||
.is_some()
|
||||
}
|
||||
Kind::Symlink { target: link, .. } => {
|
||||
if target.overwrite {
|
||||
self.delete_tree(db, &target.uri, false)?;
|
||||
|
|
|
|||
251
crates/tunal-core/tests/location.rs
Normal file
251
crates/tunal-core/tests/location.rs
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
//! URIs, local listing edge cases and watching, all inside temp dirs.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::ops::ControlFlow;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tunal_core::{
|
||||
Error, Kind, LocalLocation, Location, Locations, Uri, WatchEvent, WriteMode, display_name,
|
||||
};
|
||||
|
||||
fn list(dir: &std::path::Path) -> tunal_core::Result<Vec<tunal_core::Entry>> {
|
||||
let mut all = Vec::new();
|
||||
LocalLocation.list(&Uri::from_path(dir), &mut |chunk| {
|
||||
all.extend(chunk);
|
||||
ControlFlow::Continue(())
|
||||
})?;
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uri_parse_display_round_trip() {
|
||||
let uri = Uri::new("file", "", b"/tmp/a b/\xff%.txt".to_vec());
|
||||
let text = uri.to_string();
|
||||
assert_eq!(text, "file:///tmp/a%20b/%FF%25.txt");
|
||||
assert_eq!(Uri::parse(&text), Some(uri));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uri_parts() {
|
||||
let uri = Uri::parse("SFTP://host/a/b/").unwrap();
|
||||
assert_eq!(uri.scheme(), "sftp");
|
||||
assert_eq!(uri.authority(), "host");
|
||||
assert_eq!(uri.file_name(), Some(&b"b"[..]));
|
||||
assert_eq!(uri.parent().unwrap().path(), b"/a");
|
||||
assert_eq!(uri.join(b"c").path(), b"/a/b/c");
|
||||
let root = Uri::parse("file:///").unwrap();
|
||||
assert_eq!(root.file_name(), None);
|
||||
assert_eq!(root.parent(), None);
|
||||
assert_eq!(root.join(b"x").path(), b"/x");
|
||||
// Empty path becomes the root.
|
||||
assert_eq!(Uri::parse("trash://").unwrap().path(), b"/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uri_parse_rejects_bad_input() {
|
||||
assert!(Uri::parse("no scheme").is_none());
|
||||
assert!(Uri::parse("1ab://x/").is_none());
|
||||
assert!(Uri::parse("file:///bad%2").is_none());
|
||||
assert!(Uri::parse("file:///bad%zz").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uri_path_conversion() {
|
||||
let uri = Uri::from_path(std::path::Path::new("/tmp/x"));
|
||||
assert_eq!(uri.to_path().unwrap(), std::path::Path::new("/tmp/x"));
|
||||
assert!(Uri::new("sftp", "h", "/x").to_path().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_resolves_by_scheme() {
|
||||
let locations = Locations::with_local();
|
||||
assert!(locations.resolve(&Uri::parse("file:///").unwrap()).is_ok());
|
||||
assert!(locations.resolve(&Uri::parse("TRASH:///").unwrap()).is_ok());
|
||||
assert_eq!(
|
||||
locations.resolve(&Uri::parse("sftp://h/").unwrap()).err(),
|
||||
Some(Error::Unsupported)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_non_utf8_names_and_hidden() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let odd = OsStr::from_bytes(b"odd \xff name");
|
||||
fs::write(dir.path().join(odd), "x").unwrap();
|
||||
fs::write(dir.path().join(".hidden"), "x").unwrap();
|
||||
let mut entries = list(dir.path()).unwrap();
|
||||
entries.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
assert_eq!(entries.len(), 2);
|
||||
assert!(entries[0].hidden && entries[0].name == b".hidden");
|
||||
assert_eq!(entries[1].name, b"odd \xff name");
|
||||
assert_eq!(entries[1].display_name, display_name(b"odd \xff name"));
|
||||
assert!(!entries[1].hidden);
|
||||
// stat through a URI built from the raw name finds it.
|
||||
let uri = Uri::from_path(dir.path()).join(b"odd \xff name");
|
||||
assert_eq!(LocalLocation.stat(&uri).unwrap().size, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symlinks_are_not_followed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::create_dir(dir.path().join("folder")).unwrap();
|
||||
std::os::unix::fs::symlink("folder", dir.path().join("to-dir")).unwrap();
|
||||
std::os::unix::fs::symlink("missing", dir.path().join("broken")).unwrap();
|
||||
let entries = list(dir.path()).unwrap();
|
||||
let find = |n: &[u8]| entries.iter().find(|e| e.name == n).unwrap();
|
||||
assert!(matches!(
|
||||
&find(b"to-dir").kind,
|
||||
Kind::Symlink { target, target_type: Some(_) } if target == b"folder"
|
||||
));
|
||||
assert!(find(b"to-dir").kind.is_dir());
|
||||
assert!(matches!(
|
||||
&find(b"broken").kind,
|
||||
Kind::Symlink {
|
||||
target_type: None,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(!find(b"broken").kind.is_dir());
|
||||
assert_eq!(find(b"folder").kind, Kind::Dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permission_denied_folder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let locked = dir.path().join("locked");
|
||||
fs::create_dir(&locked).unwrap();
|
||||
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
|
||||
let result = list(&locked);
|
||||
fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
// Root ignores modes; only check when the kernel really denied it.
|
||||
if let Err(e) = result {
|
||||
assert_eq!(e, Error::PermissionDenied);
|
||||
assert!(e.needs_elevation());
|
||||
}
|
||||
// The folder itself is still listed and stat-able from its parent.
|
||||
assert!(
|
||||
list(dir.path())
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|e| e.name == b"locked")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_folder_is_not_found() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(list(&dir.path().join("nope")).err(), Some(Error::NotFound));
|
||||
assert_eq!(
|
||||
LocalLocation
|
||||
.stat(&Uri::from_path(&dir.path().join("nope")))
|
||||
.err(),
|
||||
Some(Error::NotFound)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ten_thousand_entries_arrive_in_chunks() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for i in 0..10_000 {
|
||||
fs::File::create(dir.path().join(format!("f{i:05}"))).unwrap();
|
||||
}
|
||||
let mut chunks = 0;
|
||||
let mut total = 0;
|
||||
LocalLocation
|
||||
.list(&Uri::from_path(dir.path()), &mut |chunk| {
|
||||
chunks += 1;
|
||||
total += chunk.len();
|
||||
ControlFlow::Continue(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(total, 10_000);
|
||||
assert!(chunks > 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn breaking_the_sink_cancels_the_listing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for i in 0..1000 {
|
||||
fs::File::create(dir.path().join(format!("f{i}"))).unwrap();
|
||||
}
|
||||
let mut calls = 0;
|
||||
let result = LocalLocation.list(&Uri::from_path(dir.path()), &mut |_| {
|
||||
calls += 1;
|
||||
ControlFlow::Break(())
|
||||
});
|
||||
assert_eq!(result.err(), Some(Error::Cancelled));
|
||||
assert_eq!(calls, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_modes_rename_and_delete() {
|
||||
use std::io::Write;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let a = Uri::from_path(&dir.path().join("a"));
|
||||
let b = Uri::from_path(&dir.path().join("b"));
|
||||
let mut w = LocalLocation.open_write(&a, WriteMode::CreateNew).unwrap();
|
||||
w.write_all(b"one").unwrap();
|
||||
drop(w);
|
||||
assert_eq!(
|
||||
LocalLocation.open_write(&a, WriteMode::CreateNew).err(),
|
||||
Some(Error::Exists)
|
||||
);
|
||||
let mut w = LocalLocation.open_write(&a, WriteMode::Overwrite).unwrap();
|
||||
w.write_all(b"2").unwrap();
|
||||
drop(w);
|
||||
assert_eq!(fs::read(dir.path().join("a")).unwrap(), b"2");
|
||||
fs::write(dir.path().join("b"), "keep").unwrap();
|
||||
assert_eq!(LocalLocation.rename(&a, &b).err(), Some(Error::Exists));
|
||||
assert_eq!(fs::read(dir.path().join("b")).unwrap(), b"keep");
|
||||
LocalLocation.delete(&b).unwrap();
|
||||
assert_eq!(LocalLocation.delete(&b).err(), Some(Error::NotFound));
|
||||
let sub = Uri::from_path(&dir.path().join("sub"));
|
||||
LocalLocation.mkdir(&sub).unwrap();
|
||||
assert_eq!(LocalLocation.mkdir(&sub).err(), Some(Error::Exists));
|
||||
fs::write(dir.path().join("sub/x"), "").unwrap();
|
||||
assert_eq!(LocalLocation.delete(&sub).err(), Some(Error::NotEmpty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watch_reports_created_and_removed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let _watch = LocalLocation
|
||||
.watch(
|
||||
&Uri::from_path(dir.path()),
|
||||
Box::new(move |event| {
|
||||
let _ = tx.send(event);
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
let file = dir.path().join("new.txt");
|
||||
fs::write(&file, "x").unwrap();
|
||||
let expect = |rx: &mpsc::Receiver<WatchEvent>| loop {
|
||||
match rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("watch event")
|
||||
{
|
||||
WatchEvent::Changed(uris)
|
||||
if uris.iter().any(|u| u.to_path().as_deref() == Some(&file)) =>
|
||||
{
|
||||
return;
|
||||
}
|
||||
WatchEvent::Changed(_) => {}
|
||||
WatchEvent::Error(e) => panic!("watch error: {e}"),
|
||||
}
|
||||
};
|
||||
expect(&rx);
|
||||
fs::remove_file(&file).unwrap();
|
||||
expect(&rx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watch_of_missing_folder_fails() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let result = LocalLocation.watch(&Uri::from_path(&dir.path().join("nope")), Box::new(|_| {}));
|
||||
assert!(result.is_err());
|
||||
}
|
||||
702
crates/tunal-core/tests/ops.rs
Normal file
702
crates/tunal-core/tests/ops.rs
Normal file
|
|
@ -0,0 +1,702 @@
|
|||
//! The job engine on real files in temp dirs: conflicts, errors, cancel, cross-device moves.
|
||||
|
||||
use std::fs;
|
||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::Duration;
|
||||
|
||||
use tunal_core::ops::{
|
||||
ConflictAction, ConflictChoice, ErrorAction, JobEvent, JobId, JobKind, Jobs, Report,
|
||||
auto_rename, is_inside, numbered,
|
||||
};
|
||||
use tunal_core::{LocalLocation, Locations, Uri};
|
||||
|
||||
fn uri(p: &Path) -> Uri {
|
||||
Uri::from_path(p)
|
||||
}
|
||||
|
||||
type ErrorHook = Box<dyn FnMut(&Uri)>;
|
||||
|
||||
/// What the "UI" answers while a job runs.
|
||||
struct Policy {
|
||||
conflict: ConflictChoice,
|
||||
error: ErrorAction,
|
||||
/// Called with the failing path before the error answer is sent.
|
||||
on_error: Option<ErrorHook>,
|
||||
/// Cancel at the first conflict instead of answering.
|
||||
cancel_on_conflict: bool,
|
||||
/// Cancel once bytes were copied.
|
||||
cancel_on_bytes: bool,
|
||||
}
|
||||
|
||||
impl Policy {
|
||||
fn new(action: ConflictAction) -> Self {
|
||||
Self {
|
||||
conflict: ConflictChoice {
|
||||
action,
|
||||
apply_to_all: false,
|
||||
},
|
||||
error: ErrorAction::Skip,
|
||||
on_error: None,
|
||||
cancel_on_conflict: false,
|
||||
cancel_on_bytes: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn all(mut self) -> Self {
|
||||
self.conflict.apply_to_all = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
struct Outcome {
|
||||
report: Report,
|
||||
conflicts: usize,
|
||||
errors: usize,
|
||||
}
|
||||
|
||||
struct Engine {
|
||||
jobs: Jobs,
|
||||
events: mpsc::Receiver<(JobId, JobEvent)>,
|
||||
slow: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
fn engine() -> Engine {
|
||||
let (tx, events) = mpsc::channel();
|
||||
let slow = Arc::new(AtomicBool::new(false));
|
||||
let slow_sink = slow.clone();
|
||||
let jobs = Jobs::new(Locations::with_local(), move |id, event| {
|
||||
let progress = matches!(event, JobEvent::Progress(_));
|
||||
let _ = tx.send((id, event));
|
||||
// A busy UI: lets a cancel land in the middle of a big file.
|
||||
if progress && slow_sink.load(Ordering::Relaxed) {
|
||||
std::thread::sleep(Duration::from_millis(150));
|
||||
}
|
||||
});
|
||||
Engine { jobs, events, slow }
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
fn run(&self, kind: JobKind, mut policy: Policy) -> Outcome {
|
||||
let handle = self.jobs.submit(kind);
|
||||
let (mut conflicts, mut errors) = (0, 0);
|
||||
for (id, event) in &self.events {
|
||||
if id != handle.id() {
|
||||
continue;
|
||||
}
|
||||
match event {
|
||||
JobEvent::Progress(p) if policy.cancel_on_bytes && p.done_bytes > 0 => {
|
||||
handle.cancel();
|
||||
}
|
||||
JobEvent::Progress(_) => {}
|
||||
JobEvent::Conflict(request) => {
|
||||
conflicts += 1;
|
||||
if policy.cancel_on_conflict {
|
||||
handle.cancel();
|
||||
continue;
|
||||
}
|
||||
request.reply.send(policy.conflict.clone());
|
||||
}
|
||||
JobEvent::Error(request) => {
|
||||
errors += 1;
|
||||
if let Some(f) = policy.on_error.as_mut() {
|
||||
f(&request.uri);
|
||||
}
|
||||
request.reply.send(policy.error);
|
||||
}
|
||||
JobEvent::Finished(report) => {
|
||||
return Outcome {
|
||||
report,
|
||||
conflicts,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("job worker stopped");
|
||||
}
|
||||
}
|
||||
|
||||
fn read(p: impl AsRef<Path>) -> String {
|
||||
fs::read_to_string(p).unwrap()
|
||||
}
|
||||
|
||||
fn names(dir: &Path) -> Vec<String> {
|
||||
let mut v: Vec<String> = fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// `src/{a,b,c}.txt = "src <name>"` and `dst/{a,b,c}.txt = "dst <name>"`.
|
||||
fn conflicted() -> (tempfile::TempDir, PathBuf, PathBuf) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (src, dst) = (dir.path().join("src"), dir.path().join("dst"));
|
||||
fs::create_dir(&src).unwrap();
|
||||
fs::create_dir(&dst).unwrap();
|
||||
for n in ["a", "b", "c"] {
|
||||
fs::write(src.join(format!("{n}.txt")), format!("src {n}")).unwrap();
|
||||
fs::write(dst.join(format!("{n}.txt")), format!("dst {n}")).unwrap();
|
||||
}
|
||||
(dir, src, dst)
|
||||
}
|
||||
|
||||
fn copy_all(src: &Path, dst: &Path) -> JobKind {
|
||||
JobKind::Copy {
|
||||
sources: ["a", "b", "c"]
|
||||
.iter()
|
||||
.map(|n| uri(&src.join(format!("{n}.txt"))))
|
||||
.collect(),
|
||||
dest: uri(dst),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_without_conflict_reports_totals_and_keeps_mtime() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (src, dst) = (dir.path().join("src"), dir.path().join("dst"));
|
||||
fs::create_dir_all(src.join("sub")).unwrap();
|
||||
fs::create_dir(&dst).unwrap();
|
||||
fs::write(src.join("a.txt"), "hello").unwrap();
|
||||
fs::write(src.join("sub/b.txt"), "abc").unwrap();
|
||||
std::os::unix::fs::symlink("b.txt", src.join("sub/link")).unwrap();
|
||||
let old = std::time::SystemTime::now() - Duration::from_secs(86_400 * 30);
|
||||
fs::File::options()
|
||||
.write(true)
|
||||
.open(src.join("a.txt"))
|
||||
.unwrap()
|
||||
.set_modified(old)
|
||||
.unwrap();
|
||||
let e = engine();
|
||||
let out = e.run(
|
||||
JobKind::Copy {
|
||||
sources: vec![uri(&src.join("a.txt")), uri(&src.join("sub"))],
|
||||
dest: uri(&dst),
|
||||
},
|
||||
Policy::new(ConflictAction::Skip),
|
||||
);
|
||||
assert!(out.report.failures.is_empty() && !out.report.cancelled);
|
||||
assert_eq!(out.conflicts, 0);
|
||||
assert_eq!(out.report.done_bytes, 8);
|
||||
assert_eq!(read(dst.join("a.txt")), "hello");
|
||||
assert_eq!(read(dst.join("sub/b.txt")), "abc");
|
||||
assert_eq!(
|
||||
fs::read_link(dst.join("sub/link")).unwrap(),
|
||||
Path::new("b.txt")
|
||||
);
|
||||
assert_eq!(
|
||||
fs::metadata(dst.join("a.txt")).unwrap().modified().unwrap(),
|
||||
old
|
||||
);
|
||||
// The source is untouched.
|
||||
assert!(src.join("a.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflict_skip() {
|
||||
let (_dir, src, dst) = conflicted();
|
||||
let out = engine().run(copy_all(&src, &dst), Policy::new(ConflictAction::Skip));
|
||||
assert_eq!(out.conflicts, 3);
|
||||
assert_eq!(read(dst.join("a.txt")), "dst a");
|
||||
assert_eq!(names(&dst).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflict_overwrite() {
|
||||
let (_dir, src, dst) = conflicted();
|
||||
let out = engine().run(copy_all(&src, &dst), Policy::new(ConflictAction::Overwrite));
|
||||
assert_eq!(out.conflicts, 3);
|
||||
assert_eq!(read(dst.join("b.txt")), "src b");
|
||||
assert_eq!(names(&dst).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflict_auto_rename() {
|
||||
let (_dir, src, dst) = conflicted();
|
||||
let out = engine().run(
|
||||
copy_all(&src, &dst),
|
||||
Policy::new(ConflictAction::AutoRename),
|
||||
);
|
||||
assert_eq!(out.conflicts, 3);
|
||||
assert_eq!(read(dst.join("a.txt")), "dst a");
|
||||
assert_eq!(read(dst.join("a (2).txt")), "src a");
|
||||
assert_eq!(read(dst.join("c (2).txt")), "src c");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflict_rename_asks_again_when_the_new_name_exists() {
|
||||
let (_dir, src, dst) = conflicted();
|
||||
// "b.txt" is taken too, so the engine asks a second time.
|
||||
let kind = JobKind::Copy {
|
||||
sources: vec![uri(&src.join("a.txt"))],
|
||||
dest: uri(&dst),
|
||||
};
|
||||
let e = engine();
|
||||
let handle = e.jobs.submit(kind);
|
||||
let mut answers = vec![b"b.txt".to_vec(), b"fresh.txt".to_vec()].into_iter();
|
||||
for (id, event) in &e.events {
|
||||
assert_eq!(id, handle.id());
|
||||
match event {
|
||||
JobEvent::Conflict(request) => request.reply.send(ConflictChoice {
|
||||
action: ConflictAction::Rename(answers.next().expect("asked twice")),
|
||||
apply_to_all: true,
|
||||
}),
|
||||
JobEvent::Finished(report) => {
|
||||
assert!(report.failures.is_empty());
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(answers.next().is_none());
|
||||
assert_eq!(read(dst.join("fresh.txt")), "src a");
|
||||
assert_eq!(read(dst.join("b.txt")), "dst b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_to_all_asks_once() {
|
||||
let (_dir, src, dst) = conflicted();
|
||||
let out = engine().run(
|
||||
copy_all(&src, &dst),
|
||||
Policy::new(ConflictAction::Overwrite).all(),
|
||||
);
|
||||
assert_eq!(out.conflicts, 1);
|
||||
for n in ["a", "b", "c"] {
|
||||
assert_eq!(read(dst.join(format!("{n}.txt"))), format!("src {n}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unanswered_conflict_means_skip() {
|
||||
let (_dir, src, dst) = conflicted();
|
||||
let e = engine();
|
||||
let handle = e.jobs.submit(copy_all(&src, &dst));
|
||||
for (id, event) in &e.events {
|
||||
assert_eq!(id, handle.id());
|
||||
match event {
|
||||
JobEvent::Conflict(request) => drop(request.reply),
|
||||
JobEvent::Finished(report) => {
|
||||
assert!(!report.cancelled);
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(read(dst.join("a.txt")), "dst a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folder_onto_folder_merges() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (src, dst) = (dir.path().join("src"), dir.path().join("dst"));
|
||||
fs::create_dir_all(src.join("f")).unwrap();
|
||||
fs::create_dir_all(dst.join("f")).unwrap();
|
||||
fs::write(src.join("f/new.txt"), "new").unwrap();
|
||||
fs::write(src.join("f/both.txt"), "src").unwrap();
|
||||
fs::write(dst.join("f/both.txt"), "dst").unwrap();
|
||||
fs::write(dst.join("f/only-dst.txt"), "keep").unwrap();
|
||||
let out = engine().run(
|
||||
JobKind::Copy {
|
||||
sources: vec![uri(&src.join("f"))],
|
||||
dest: uri(&dst),
|
||||
},
|
||||
Policy::new(ConflictAction::Overwrite).all(),
|
||||
);
|
||||
assert!(out.report.failures.is_empty());
|
||||
assert_eq!(
|
||||
names(&dst.join("f")),
|
||||
["both.txt", "new.txt", "only-dst.txt"]
|
||||
);
|
||||
assert_eq!(read(dst.join("f/both.txt")), "src");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_over_folder_overwrite_replaces_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (src, dst) = (dir.path().join("src"), dir.path().join("dst"));
|
||||
fs::create_dir_all(&src).unwrap();
|
||||
fs::create_dir_all(dst.join("x/inner")).unwrap();
|
||||
fs::write(src.join("x"), "file").unwrap();
|
||||
engine().run(
|
||||
JobKind::Copy {
|
||||
sources: vec![uri(&src.join("x"))],
|
||||
dest: uri(&dst),
|
||||
},
|
||||
Policy::new(ConflictAction::Overwrite),
|
||||
);
|
||||
assert_eq!(read(dst.join("x")), "file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_into_own_folder_makes_numbered_copies_without_asking() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::write(dir.path().join("a.txt"), "a").unwrap();
|
||||
let kind = || JobKind::Copy {
|
||||
sources: vec![uri(&dir.path().join("a.txt"))],
|
||||
dest: uri(dir.path()),
|
||||
};
|
||||
let e = engine();
|
||||
let first = e.run(kind(), Policy::new(ConflictAction::Skip));
|
||||
let second = e.run(kind(), Policy::new(ConflictAction::Skip));
|
||||
assert_eq!(first.conflicts + second.conflicts, 0);
|
||||
assert_eq!(names(dir.path()), ["a (2).txt", "a (3).txt", "a.txt"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_folder_into_itself_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let src = dir.path().join("src");
|
||||
fs::create_dir_all(src.join("sub")).unwrap();
|
||||
fs::write(src.join("a.txt"), "a").unwrap();
|
||||
for dest in [src.clone(), src.join("sub")] {
|
||||
for mv in [false, true] {
|
||||
let sources = vec![uri(&src)];
|
||||
let kind = if mv {
|
||||
JobKind::Move {
|
||||
sources,
|
||||
dest: uri(&dest),
|
||||
}
|
||||
} else {
|
||||
JobKind::Copy {
|
||||
sources,
|
||||
dest: uri(&dest),
|
||||
}
|
||||
};
|
||||
let out = engine().run(kind, Policy::new(ConflictAction::Skip));
|
||||
// Moving a folder onto its own parent is a no-op, not an error.
|
||||
if !(mv && dest == src.parent().unwrap()) {
|
||||
assert_eq!(out.report.failures.len(), 1, "dest {dest:?} move {mv}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(names(&src), ["a.txt", "sub"]);
|
||||
assert!(names(&src.join("sub")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_removes_the_source_and_merges() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (src, dst) = (dir.path().join("src"), dir.path().join("dst"));
|
||||
fs::create_dir_all(src.join("f")).unwrap();
|
||||
fs::create_dir_all(dst.join("f")).unwrap();
|
||||
fs::write(src.join("f/a.txt"), "src").unwrap();
|
||||
fs::write(src.join("f/b.txt"), "b").unwrap();
|
||||
fs::write(dst.join("f/a.txt"), "dst").unwrap();
|
||||
fs::write(src.join("solo.txt"), "solo").unwrap();
|
||||
let out = engine().run(
|
||||
JobKind::Move {
|
||||
sources: vec![uri(&src.join("f")), uri(&src.join("solo.txt"))],
|
||||
dest: uri(&dst),
|
||||
},
|
||||
Policy::new(ConflictAction::Overwrite).all(),
|
||||
);
|
||||
assert!(out.report.failures.is_empty());
|
||||
assert_eq!(read(dst.join("f/a.txt")), "src");
|
||||
assert_eq!(read(dst.join("f/b.txt")), "b");
|
||||
assert_eq!(read(dst.join("solo.txt")), "solo");
|
||||
assert!(!src.join("f").exists() && !src.join("solo.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skipped_folder_conflict_leaves_both_sides_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (src, dst) = (dir.path().join("src"), dir.path().join("dst"));
|
||||
fs::create_dir_all(src.join("f")).unwrap();
|
||||
fs::create_dir_all(dst.join("f")).unwrap();
|
||||
fs::write(src.join("f/a.txt"), "src").unwrap();
|
||||
fs::write(dst.join("f/b.txt"), "dst").unwrap();
|
||||
let out = engine().run(
|
||||
JobKind::Move {
|
||||
sources: vec![uri(&src.join("f"))],
|
||||
dest: uri(&dst),
|
||||
},
|
||||
Policy::new(ConflictAction::Skip),
|
||||
);
|
||||
assert_eq!((out.conflicts, out.report.failures.len()), (1, 0));
|
||||
assert_eq!(names(&src.join("f")), ["a.txt"]);
|
||||
assert_eq!(names(&dst.join("f")), ["b.txt"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_to_same_folder_is_a_no_op() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::write(dir.path().join("a.txt"), "a").unwrap();
|
||||
let out = engine().run(
|
||||
JobKind::Move {
|
||||
sources: vec![uri(&dir.path().join("a.txt"))],
|
||||
dest: uri(dir.path()),
|
||||
},
|
||||
Policy::new(ConflictAction::Skip),
|
||||
);
|
||||
assert_eq!((out.conflicts, out.report.failures.len()), (0, 0));
|
||||
assert_eq!(read(dir.path().join("a.txt")), "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_device_move_copies_then_deletes() {
|
||||
let other = Path::new("/dev/shm");
|
||||
let here = tempfile::tempdir().unwrap();
|
||||
let Ok(far) = tempfile::tempdir_in(other) else {
|
||||
eprintln!("skipped: no /dev/shm");
|
||||
return;
|
||||
};
|
||||
if fs::metadata(here.path()).unwrap().dev() == fs::metadata(far.path()).unwrap().dev() {
|
||||
eprintln!("skipped: temp dir and /dev/shm share a device");
|
||||
return;
|
||||
}
|
||||
let src = here.path().join("tree");
|
||||
fs::create_dir_all(src.join("sub")).unwrap();
|
||||
fs::write(src.join("sub/big.bin"), vec![9u8; 3 << 20]).unwrap();
|
||||
fs::write(src.join("a.txt"), "a").unwrap();
|
||||
let out = engine().run(
|
||||
JobKind::Move {
|
||||
sources: vec![uri(&src)],
|
||||
dest: uri(far.path()),
|
||||
},
|
||||
Policy::new(ConflictAction::Skip),
|
||||
);
|
||||
assert!(out.report.failures.is_empty(), "{:?}", out.report.failures);
|
||||
assert!(!src.exists());
|
||||
assert_eq!(
|
||||
fs::read(far.path().join("tree/sub/big.bin")).unwrap().len(),
|
||||
3 << 20
|
||||
);
|
||||
assert_eq!(read(far.path().join("tree/a.txt")), "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_removes_trees_and_reports_missing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::create_dir_all(dir.path().join("t/deep/er")).unwrap();
|
||||
fs::write(dir.path().join("t/deep/er/f"), "x").unwrap();
|
||||
std::os::unix::fs::symlink("/", dir.path().join("t/link-to-root")).unwrap();
|
||||
fs::write(dir.path().join("keep"), "x").unwrap();
|
||||
let e = engine();
|
||||
let out = e.run(
|
||||
JobKind::Delete(vec![uri(&dir.path().join("t"))]),
|
||||
Policy::new(ConflictAction::Skip),
|
||||
);
|
||||
assert!(out.report.failures.is_empty());
|
||||
assert_eq!(names(dir.path()), ["keep"]);
|
||||
let out = e.run(
|
||||
JobKind::Delete(vec![uri(&dir.path().join("t"))]),
|
||||
Policy::new(ConflictAction::Skip),
|
||||
);
|
||||
assert_eq!(out.report.failures.len(), 1);
|
||||
assert_eq!(out.errors, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mkdir_rename_and_link_jobs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let e = engine();
|
||||
let p = dir.path();
|
||||
let skip = || Policy::new(ConflictAction::Skip);
|
||||
assert!(
|
||||
e.run(JobKind::Mkdir(uri(&p.join("d"))), skip())
|
||||
.report
|
||||
.failures
|
||||
.is_empty()
|
||||
);
|
||||
assert!(p.join("d").is_dir());
|
||||
assert_eq!(
|
||||
e.run(JobKind::Mkdir(uri(&p.join("d"))), skip())
|
||||
.report
|
||||
.failures
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
fs::write(p.join("f"), "x").unwrap();
|
||||
e.run(
|
||||
JobKind::Rename {
|
||||
from: uri(&p.join("f")),
|
||||
to: uri(&p.join("g")),
|
||||
},
|
||||
skip(),
|
||||
);
|
||||
assert!(!p.join("f").exists() && p.join("g").exists());
|
||||
// Renaming onto an existing name fails and changes nothing.
|
||||
fs::write(p.join("h"), "keep").unwrap();
|
||||
let out = e.run(
|
||||
JobKind::Rename {
|
||||
from: uri(&p.join("g")),
|
||||
to: uri(&p.join("h")),
|
||||
},
|
||||
skip(),
|
||||
);
|
||||
assert_eq!(out.report.failures.len(), 1);
|
||||
assert_eq!(read(p.join("h")), "keep");
|
||||
e.run(
|
||||
JobKind::Link {
|
||||
sources: vec![uri(&p.join("g"))],
|
||||
dest: uri(&p.join("d")),
|
||||
},
|
||||
skip(),
|
||||
);
|
||||
assert_eq!(fs::read_link(p.join("d/g")).unwrap(), p.join("g"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_failure_skips_and_continues() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (src, dst) = (dir.path().join("src"), dir.path().join("dst"));
|
||||
fs::create_dir_all(&src).unwrap();
|
||||
fs::create_dir(&dst).unwrap();
|
||||
fs::write(src.join("locked.txt"), "secret").unwrap();
|
||||
fs::write(src.join("ok.txt"), "ok").unwrap();
|
||||
fs::set_permissions(src.join("locked.txt"), fs::Permissions::from_mode(0o000)).unwrap();
|
||||
if fs::File::open(src.join("locked.txt")).is_ok() {
|
||||
eprintln!("skipped: modes are not enforced (running as root)");
|
||||
return;
|
||||
}
|
||||
let out = engine().run(
|
||||
JobKind::Copy {
|
||||
sources: vec![uri(&src.join("locked.txt")), uri(&src.join("ok.txt"))],
|
||||
dest: uri(&dst),
|
||||
},
|
||||
Policy::new(ConflictAction::Skip),
|
||||
);
|
||||
assert_eq!(out.errors, 1);
|
||||
assert_eq!(out.report.failures.len(), 1);
|
||||
assert!(out.report.failures[0].1.needs_elevation());
|
||||
assert!(!out.report.cancelled);
|
||||
assert_eq!(names(&dst), ["ok.txt"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_actions_retry_skip_all_abort() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (src, dst) = (dir.path().join("src"), dir.path().join("dst"));
|
||||
fs::create_dir_all(&src).unwrap();
|
||||
fs::create_dir(&dst).unwrap();
|
||||
for n in ["l1", "l2"] {
|
||||
fs::write(src.join(n), n).unwrap();
|
||||
fs::set_permissions(src.join(n), fs::Permissions::from_mode(0o000)).unwrap();
|
||||
}
|
||||
fs::write(src.join("ok"), "ok").unwrap();
|
||||
if fs::File::open(src.join("l1")).is_ok() {
|
||||
eprintln!("skipped: modes are not enforced (running as root)");
|
||||
return;
|
||||
}
|
||||
let kind = || JobKind::Copy {
|
||||
sources: ["l1", "l2", "ok"]
|
||||
.iter()
|
||||
.map(|n| uri(&src.join(n)))
|
||||
.collect(),
|
||||
dest: uri(&dst),
|
||||
};
|
||||
let e = engine();
|
||||
|
||||
let mut policy = Policy::new(ConflictAction::Skip);
|
||||
policy.error = ErrorAction::SkipAll;
|
||||
let out = e.run(kind(), policy);
|
||||
assert_eq!((out.errors, out.report.failures.len()), (1, 2));
|
||||
assert_eq!(names(&dst), ["ok"]);
|
||||
fs::remove_file(dst.join("ok")).unwrap();
|
||||
|
||||
let mut policy = Policy::new(ConflictAction::Skip);
|
||||
policy.error = ErrorAction::Abort;
|
||||
let out = e.run(kind(), policy);
|
||||
assert!(out.report.cancelled);
|
||||
assert_eq!(out.report.failures.len(), 1);
|
||||
assert!(names(&dst).is_empty());
|
||||
|
||||
// Retry after the "user" fixed the permission.
|
||||
let mut policy = Policy::new(ConflictAction::Skip);
|
||||
policy.error = ErrorAction::Retry;
|
||||
let fixed = src.clone();
|
||||
policy.on_error = Some(Box::new(move |failing| {
|
||||
let path = failing.to_path().unwrap();
|
||||
assert!(path.starts_with(&fixed));
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o644)).unwrap();
|
||||
}));
|
||||
let out = e.run(kind(), policy);
|
||||
assert_eq!((out.errors, out.report.failures.len()), (2, 0));
|
||||
assert_eq!(names(&dst), ["l1", "l2", "ok"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_at_a_conflict_stops_the_job() {
|
||||
let (_dir, src, dst) = conflicted();
|
||||
fs::write(src.join("0.txt"), "first").unwrap();
|
||||
let mut policy = Policy::new(ConflictAction::Skip);
|
||||
policy.cancel_on_conflict = true;
|
||||
let out = engine().run(
|
||||
JobKind::Copy {
|
||||
sources: ["0", "a", "b"]
|
||||
.iter()
|
||||
.map(|n| uri(&src.join(format!("{n}.txt"))))
|
||||
.collect(),
|
||||
dest: uri(&dst),
|
||||
},
|
||||
policy,
|
||||
);
|
||||
assert!(out.report.cancelled);
|
||||
assert_eq!(read(dst.join("0.txt")), "first");
|
||||
assert_eq!(read(dst.join("a.txt")), "dst a");
|
||||
assert_eq!(read(dst.join("b.txt")), "dst b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_in_the_middle_of_a_file_leaves_no_partial_copy() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (src, dst) = (dir.path().join("src"), dir.path().join("dst"));
|
||||
fs::create_dir_all(&src).unwrap();
|
||||
fs::create_dir(&dst).unwrap();
|
||||
fs::write(src.join("big.bin"), vec![7u8; 48 << 20]).unwrap();
|
||||
let e = engine();
|
||||
e.slow.store(true, Ordering::Relaxed);
|
||||
let mut policy = Policy::new(ConflictAction::Skip);
|
||||
policy.cancel_on_bytes = true;
|
||||
let out = e.run(
|
||||
JobKind::Copy {
|
||||
sources: vec![uri(&src.join("big.bin"))],
|
||||
dest: uri(&dst),
|
||||
},
|
||||
policy,
|
||||
);
|
||||
e.slow.store(false, Ordering::Relaxed);
|
||||
assert!(out.report.cancelled);
|
||||
assert!(!dst.join("big.bin").exists());
|
||||
assert!(src.join("big.bin").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn naming_helpers() {
|
||||
assert_eq!(numbered(b"report.pdf", 2), b"report (2).pdf");
|
||||
assert_eq!(numbered(b"report (2).pdf", 3), b"report (3).pdf");
|
||||
assert_eq!(numbered(b"photos", 4), b"photos (4)");
|
||||
assert_eq!(numbered(b".bashrc", 2), b".bashrc (2)");
|
||||
assert_eq!(numbered(b"b.TAR.GZ", 2), b"b (2).TAR.GZ");
|
||||
assert_eq!(numbered(b"backup.tar.gz", 2), b"backup (2).tar.gz");
|
||||
assert_eq!(numbered(b"x (a).txt", 2), b"x (a) (2).txt");
|
||||
assert_eq!(numbered(b"odd \xff.txt", 2), b"odd \xff (2).txt");
|
||||
|
||||
let top = Uri::parse("file:///a/b").unwrap();
|
||||
assert!(is_inside(&top, &top));
|
||||
assert!(is_inside(&Uri::parse("file:///a/b/c/d").unwrap(), &top));
|
||||
assert!(is_inside(
|
||||
&Uri::parse("file:///a/b/c").unwrap(),
|
||||
&Uri::parse("file:///a/b/").unwrap()
|
||||
));
|
||||
assert!(!is_inside(&Uri::parse("file:///a/bc").unwrap(), &top));
|
||||
assert!(!is_inside(&Uri::parse("sftp:///a/b/c").unwrap(), &top));
|
||||
assert!(is_inside(&top, &Uri::parse("file:///").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_rename_picks_the_first_free_number() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for n in ["a.txt", "a (2).txt", "a (4).txt"] {
|
||||
fs::write(dir.path().join(n), "").unwrap();
|
||||
}
|
||||
let free = auto_rename(&LocalLocation, &uri(&dir.path().join("a.txt"))).unwrap();
|
||||
assert_eq!(free.file_name(), Some(&b"a (3).txt"[..]));
|
||||
// Also from an already numbered name.
|
||||
let free = auto_rename(&LocalLocation, &uri(&dir.path().join("a (2).txt"))).unwrap();
|
||||
assert_eq!(free.file_name(), Some(&b"a (3).txt"[..]));
|
||||
}
|
||||
442
crates/tunal-core/tests/trash.rs
Normal file
442
crates/tunal-core/tests/trash.rs
Normal file
|
|
@ -0,0 +1,442 @@
|
|||
//! The freedesktop trash with `XDG_DATA_HOME` pointing into a temp dir. The environment is
|
||||
//! process-wide, so every test holds `lock()` for its whole run.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::ops::ControlFlow;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
|
||||
use tunal_core::ops::{ConflictAction, ConflictChoice, JobEvent, JobKind, Jobs, Report};
|
||||
use tunal_core::{Error, Location, Locations, TrashLocation, Uri, trash};
|
||||
|
||||
struct Env {
|
||||
/// Holds the scratch dir; leaked on purpose so it lives for the whole run.
|
||||
data: PathBuf,
|
||||
scratch: &'static tempfile::TempDir,
|
||||
}
|
||||
|
||||
fn env() -> &'static Env {
|
||||
static ENV: OnceLock<Env> = OnceLock::new();
|
||||
ENV.get_or_init(|| {
|
||||
let scratch: &'static tempfile::TempDir = Box::leak(Box::new(tempfile::tempdir().unwrap()));
|
||||
let data = scratch.path().join("data");
|
||||
fs::create_dir(&data).unwrap();
|
||||
// SAFETY: set once, before any test of this binary reads the environment (they all
|
||||
// wait on `lock()`, which calls `env()` first).
|
||||
unsafe { std::env::set_var("XDG_DATA_HOME", &data) };
|
||||
Env { data, scratch }
|
||||
})
|
||||
}
|
||||
|
||||
/// Serialises tests and starts each with an empty trash. Skips (None) when a per-mount trash
|
||||
/// of the real user is visible, so a test can never delete real files.
|
||||
fn lock() -> Option<(MutexGuard<'static, ()>, &'static Env)> {
|
||||
static LOCK: Mutex<()> = Mutex::new(());
|
||||
let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let env = env();
|
||||
if trash::items()
|
||||
.iter()
|
||||
.any(|i| !i.uri.path().starts_with(b"/home:"))
|
||||
{
|
||||
eprintln!("skipped: a per-mount trash of this user exists");
|
||||
return None;
|
||||
}
|
||||
let _ = fs::remove_dir_all(env.data.join("Trash"));
|
||||
Some((guard, env))
|
||||
}
|
||||
|
||||
fn run(kind: JobKind, action: ConflictAction) -> Report {
|
||||
let (tx, events) = mpsc::channel();
|
||||
let jobs = Jobs::new(Locations::with_local(), move |_, event| {
|
||||
let _ = tx.send(event);
|
||||
});
|
||||
jobs.submit(kind);
|
||||
for event in events {
|
||||
match event {
|
||||
JobEvent::Conflict(request) => request.reply.send(ConflictChoice {
|
||||
action: action.clone(),
|
||||
apply_to_all: false,
|
||||
}),
|
||||
JobEvent::Error(request) => request.reply.send(tunal_core::ops::ErrorAction::Skip),
|
||||
JobEvent::Finished(report) => return report,
|
||||
JobEvent::Progress(_) => {}
|
||||
}
|
||||
}
|
||||
panic!("job worker stopped");
|
||||
}
|
||||
|
||||
fn uri(p: &Path) -> Uri {
|
||||
Uri::from_path(p)
|
||||
}
|
||||
|
||||
fn trash_files(p: &[&Path]) -> Report {
|
||||
run(
|
||||
JobKind::Trash(p.iter().map(|p| uri(p)).collect()),
|
||||
ConflictAction::Skip,
|
||||
)
|
||||
}
|
||||
|
||||
fn names(dir: &Path) -> Vec<String> {
|
||||
let mut v: Vec<String> = fs::read_dir(dir)
|
||||
.map(|d| {
|
||||
d.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
fn list(dir: &Uri) -> Vec<String> {
|
||||
let mut names = Vec::new();
|
||||
TrashLocation
|
||||
.list(dir, &mut |chunk| {
|
||||
names.extend(chunk.into_iter().map(|e| e.display_name));
|
||||
ControlFlow::Continue(())
|
||||
})
|
||||
.unwrap();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trash_writes_files_and_a_trashinfo() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let dir = env.scratch.path().join("w1");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
fs::write(dir.join("note.txt"), "hello").unwrap();
|
||||
let report = trash_files(&[&dir.join("note.txt")]);
|
||||
assert!(report.failures.is_empty());
|
||||
assert!(!dir.join("note.txt").exists());
|
||||
let trash_dir = env.data.join("Trash");
|
||||
assert_eq!(
|
||||
fs::read_to_string(trash_dir.join("files/note.txt")).unwrap(),
|
||||
"hello"
|
||||
);
|
||||
let info = fs::read_to_string(trash_dir.join("info/note.txt.trashinfo")).unwrap();
|
||||
let mut lines = info.lines();
|
||||
assert_eq!(lines.next(), Some("[Trash Info]"));
|
||||
assert_eq!(
|
||||
lines.next().unwrap(),
|
||||
format!("Path={}", dir.join("note.txt").display())
|
||||
);
|
||||
let date = lines.next().unwrap().strip_prefix("DeletionDate=").unwrap();
|
||||
// 2026-11-19T10:20:30, local time, no zone.
|
||||
assert_eq!(date.len(), 19);
|
||||
assert_eq!(date.as_bytes()[10], b'T');
|
||||
let items = trash::items();
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].entry.display_name, "note.txt");
|
||||
assert_eq!(items[0].original, uri(&dir.join("note.txt")));
|
||||
let age = items[0].deleted.unwrap().elapsed().unwrap();
|
||||
assert!(age.as_secs() < 60);
|
||||
assert!(items[0].uri.path().starts_with(b"/home:note.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trashinfo_percent_encodes_the_path() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let dir = env.scratch.path().join("w2 dir");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
let odd = dir.join(OsStr::from_bytes(b"100% odd \xff.txt"));
|
||||
fs::write(&odd, "x").unwrap();
|
||||
assert!(trash_files(&[&odd]).failures.is_empty());
|
||||
let info_path = env
|
||||
.data
|
||||
.join("Trash/info")
|
||||
.join(OsStr::from_bytes(b"100% odd \xff.txt.trashinfo"));
|
||||
let info = fs::read(&info_path).unwrap();
|
||||
let path_line = info
|
||||
.split(|&b| b == b'\n')
|
||||
.find(|l| l.starts_with(b"Path="))
|
||||
.unwrap();
|
||||
assert!(
|
||||
path_line.ends_with(b"/w2%20dir/100%25%20odd%20%FF.txt"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(path_line)
|
||||
);
|
||||
assert!(path_line.is_ascii());
|
||||
// And it reads back to the raw bytes.
|
||||
let item = &trash::items()[0];
|
||||
assert_eq!(item.original, uri(&odd));
|
||||
let report = run(
|
||||
JobKind::Restore(vec![item.uri.clone()]),
|
||||
ConflictAction::Skip,
|
||||
);
|
||||
assert!(report.failures.is_empty());
|
||||
assert_eq!(fs::read(&odd).unwrap(), b"x");
|
||||
assert!(trash::items().is_empty());
|
||||
assert!(!info_path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_name_from_two_folders_gets_two_slots() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let (a, b) = (env.scratch.path().join("c1"), env.scratch.path().join("c2"));
|
||||
for (d, text) in [(&a, "from a"), (&b, "from b")] {
|
||||
fs::create_dir(d).unwrap();
|
||||
fs::write(d.join("dup.txt"), text).unwrap();
|
||||
}
|
||||
assert!(
|
||||
trash_files(&[&a.join("dup.txt"), &b.join("dup.txt")])
|
||||
.failures
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
names(&env.data.join("Trash/files")),
|
||||
["dup (2).txt", "dup.txt"]
|
||||
);
|
||||
assert_eq!(
|
||||
names(&env.data.join("Trash/info")),
|
||||
["dup (2).txt.trashinfo", "dup.txt.trashinfo"]
|
||||
);
|
||||
let items = trash::items();
|
||||
assert_eq!(items.len(), 2);
|
||||
assert!(items.iter().all(|i| i.entry.display_name == "dup.txt"));
|
||||
let report = run(
|
||||
JobKind::Restore(items.iter().map(|i| i.uri.clone()).collect()),
|
||||
ConflictAction::Skip,
|
||||
);
|
||||
assert!(report.failures.is_empty());
|
||||
assert_eq!(fs::read_to_string(a.join("dup.txt")).unwrap(), "from a");
|
||||
assert_eq!(fs::read_to_string(b.join("dup.txt")).unwrap(), "from b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leftover_file_without_info_does_not_get_overwritten() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let dir = env.scratch.path().join("l1");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
let files = env.data.join("Trash/files");
|
||||
fs::create_dir_all(&files).unwrap();
|
||||
fs::write(files.join("x.txt"), "orphan").unwrap();
|
||||
fs::write(dir.join("x.txt"), "new").unwrap();
|
||||
assert!(trash_files(&[&dir.join("x.txt")]).failures.is_empty());
|
||||
assert_eq!(fs::read_to_string(files.join("x.txt")).unwrap(), "orphan");
|
||||
assert_eq!(fs::read_to_string(files.join("x (2).txt")).unwrap(), "new");
|
||||
// The orphan has no info, so it is not listed.
|
||||
assert_eq!(trash::items().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_recreates_the_folder_and_handles_conflicts() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let dir = env.scratch.path().join("r1");
|
||||
fs::create_dir_all(dir.join("deep")).unwrap();
|
||||
fs::write(dir.join("deep/f.txt"), "old").unwrap();
|
||||
assert!(trash_files(&[&dir.join("deep/f.txt")]).failures.is_empty());
|
||||
fs::remove_dir_all(dir.join("deep")).unwrap();
|
||||
let item = trash::items().remove(0);
|
||||
let report = run(
|
||||
JobKind::Restore(vec![item.uri.clone()]),
|
||||
ConflictAction::Skip,
|
||||
);
|
||||
assert!(report.failures.is_empty());
|
||||
assert_eq!(fs::read_to_string(dir.join("deep/f.txt")).unwrap(), "old");
|
||||
|
||||
// Trash it again, make the target exist, and try each resolution.
|
||||
assert!(trash_files(&[&dir.join("deep/f.txt")]).failures.is_empty());
|
||||
fs::write(dir.join("deep/f.txt"), "blocker").unwrap();
|
||||
let item = trash::items().remove(0);
|
||||
|
||||
let report = run(
|
||||
JobKind::Restore(vec![item.uri.clone()]),
|
||||
ConflictAction::Skip,
|
||||
);
|
||||
assert!(report.failures.is_empty());
|
||||
assert_eq!(
|
||||
fs::read_to_string(dir.join("deep/f.txt")).unwrap(),
|
||||
"blocker"
|
||||
);
|
||||
assert_eq!(trash::items().len(), 1);
|
||||
|
||||
run(
|
||||
JobKind::Restore(vec![item.uri.clone()]),
|
||||
ConflictAction::Rename(b"back.txt".to_vec()),
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(dir.join("deep/back.txt")).unwrap(),
|
||||
"old"
|
||||
);
|
||||
assert!(trash::items().is_empty());
|
||||
|
||||
// Overwrite replaces the blocker.
|
||||
assert!(
|
||||
trash_files(&[&dir.join("deep/back.txt")])
|
||||
.failures
|
||||
.is_empty()
|
||||
);
|
||||
fs::write(dir.join("deep/back.txt"), "blocker").unwrap();
|
||||
let item = trash::items().remove(0);
|
||||
run(JobKind::Restore(vec![item.uri]), ConflictAction::Overwrite);
|
||||
assert_eq!(
|
||||
fs::read_to_string(dir.join("deep/back.txt")).unwrap(),
|
||||
"old"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trashed_folder_is_browsable_and_readable() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let dir = env.scratch.path().join("b1");
|
||||
fs::create_dir_all(dir.join("album/disc")).unwrap();
|
||||
fs::write(dir.join("album/one.txt"), "1").unwrap();
|
||||
fs::write(dir.join("album/disc/two.txt"), "22").unwrap();
|
||||
assert!(trash_files(&[&dir.join("album")]).failures.is_empty());
|
||||
assert_eq!(list(&trash::root()), ["album"]);
|
||||
let top = trash::items().remove(0).uri;
|
||||
assert_eq!(list(&top), ["disc", "one.txt"]);
|
||||
let inner = top.join(b"disc").join(b"two.txt");
|
||||
assert_eq!(TrashLocation.stat(&inner).unwrap().size, 2);
|
||||
let mut text = String::new();
|
||||
std::io::Read::read_to_string(&mut TrashLocation.open_read(&inner).unwrap(), &mut text)
|
||||
.unwrap();
|
||||
assert_eq!(text, "22");
|
||||
// `..` can't climb out, odd URIs are not found.
|
||||
assert_eq!(
|
||||
TrashLocation.stat(&top.join(b"..").join(b"x")).err(),
|
||||
Some(Error::PermissionDenied)
|
||||
);
|
||||
for bad in [
|
||||
"trash:///nocolon",
|
||||
"trash:///home:",
|
||||
"trash:///nope:thing",
|
||||
"trash:///zz:thing",
|
||||
] {
|
||||
assert_eq!(
|
||||
TrashLocation.stat(&Uri::parse(bad).unwrap()).err(),
|
||||
Some(Error::NotFound),
|
||||
"{bad}"
|
||||
);
|
||||
}
|
||||
assert_eq!(trash::original(&inner).err(), Some(Error::NotFound));
|
||||
assert_eq!(trash::original(&top).unwrap(), uri(&dir.join("album")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_out_of_the_trash_uses_the_original_name() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let dir = env.scratch.path().join("o1");
|
||||
fs::create_dir_all(dir.join("out")).unwrap();
|
||||
fs::write(dir.join("a.txt"), "data").unwrap();
|
||||
assert!(trash_files(&[&dir.join("a.txt")]).failures.is_empty());
|
||||
let item = trash::items().remove(0);
|
||||
let report = run(
|
||||
JobKind::Copy {
|
||||
sources: vec![item.uri],
|
||||
dest: uri(&dir.join("out")),
|
||||
},
|
||||
ConflictAction::Skip,
|
||||
);
|
||||
assert!(report.failures.is_empty());
|
||||
assert_eq!(fs::read_to_string(dir.join("out/a.txt")).unwrap(), "data");
|
||||
assert_eq!(trash::items().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trashing_a_symlink_leaves_its_target() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let dir = env.scratch.path().join("s1");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
fs::write(dir.join("target"), "t").unwrap();
|
||||
std::os::unix::fs::symlink("target", dir.join("link")).unwrap();
|
||||
assert!(trash_files(&[&dir.join("link")]).failures.is_empty());
|
||||
assert!(!dir.join("link").is_symlink());
|
||||
assert_eq!(fs::read_to_string(dir.join("target")).unwrap(), "t");
|
||||
let item = trash::items().remove(0);
|
||||
assert_eq!(item.original, uri(&dir.join("link")));
|
||||
run(JobKind::Restore(vec![item.uri]), ConflictAction::Skip);
|
||||
assert_eq!(
|
||||
fs::read_link(dir.join("link")).unwrap(),
|
||||
Path::new("target")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trashing_a_missing_file_fails() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let report = trash_files(&[&env.scratch.path().join("nope")]);
|
||||
assert_eq!(report.failures.len(), 1);
|
||||
assert_eq!(report.failures[0].1, Error::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_from_the_trash_drops_the_info_file() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let dir = env.scratch.path().join("d1");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
fs::write(dir.join("gone.txt"), "x").unwrap();
|
||||
trash_files(&[&dir.join("gone.txt")]);
|
||||
let item = trash::items().remove(0);
|
||||
let report = run(JobKind::Delete(vec![item.uri]), ConflictAction::Skip);
|
||||
assert!(report.failures.is_empty());
|
||||
let trash_dir = env.data.join("Trash");
|
||||
assert!(names(&trash_dir.join("files")).is_empty());
|
||||
assert!(names(&trash_dir.join("info")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_trash_removes_everything() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let dir = env.scratch.path().join("e1");
|
||||
fs::create_dir_all(dir.join("folder/inner")).unwrap();
|
||||
fs::write(dir.join("folder/inner/f"), "x").unwrap();
|
||||
fs::write(dir.join("a"), "x").unwrap();
|
||||
fs::write(dir.join("b"), "x").unwrap();
|
||||
trash_files(&[&dir.join("folder"), &dir.join("a"), &dir.join("b")]);
|
||||
assert_eq!(trash::items().len(), 3);
|
||||
let report = run(JobKind::EmptyTrash, ConflictAction::Skip);
|
||||
assert!(report.failures.is_empty() && !report.cancelled);
|
||||
assert!(trash::items().is_empty());
|
||||
let trash_dir = env.data.join("Trash");
|
||||
assert!(names(&trash_dir.join("files")).is_empty());
|
||||
assert!(names(&trash_dir.join("info")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_files_are_parsed_leniently() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let root = env.data.join("Trash");
|
||||
fs::create_dir_all(root.join("files")).unwrap();
|
||||
fs::create_dir_all(root.join("info")).unwrap();
|
||||
let put = |name: &str, info: &str| {
|
||||
fs::write(root.join("files").join(name), "x").unwrap();
|
||||
fs::write(root.join("info").join(format!("{name}.trashinfo")), info).unwrap();
|
||||
};
|
||||
// CRLF, unknown keys, another group first, no date.
|
||||
put(
|
||||
"crlf",
|
||||
"[Other]\r\nPath=/wrong\r\n[Trash Info]\r\nPath=/tmp/x%20y\r\nExtra=1\r\n",
|
||||
);
|
||||
put("nopath", "[Trash Info]\nDeletionDate=2020-01-02T03:04:05\n");
|
||||
put("garbage", "not an ini file");
|
||||
let items = trash::items();
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].original, Uri::from_path(Path::new("/tmp/x y")));
|
||||
assert!(items[0].deleted.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_date_is_read_back() {
|
||||
let Some((_guard, env)) = lock() else { return };
|
||||
let root = env.data.join("Trash");
|
||||
fs::create_dir_all(root.join("files")).unwrap();
|
||||
fs::create_dir_all(root.join("info")).unwrap();
|
||||
fs::write(root.join("files/old"), "x").unwrap();
|
||||
fs::write(
|
||||
root.join("info/old.trashinfo"),
|
||||
"[Trash Info]\nPath=/tmp/old\nDeletionDate=2020-01-02T03:04:05\n",
|
||||
)
|
||||
.unwrap();
|
||||
let item = trash::items().remove(0);
|
||||
let when = jiff::Timestamp::try_from(item.deleted.unwrap())
|
||||
.unwrap()
|
||||
.to_zoned(jiff::tz::TimeZone::system());
|
||||
assert_eq!(
|
||||
when.strftime("%Y-%m-%dT%H:%M:%S").to_string(),
|
||||
"2020-01-02T03:04:05"
|
||||
);
|
||||
}
|
||||
|
|
@ -4,3 +4,6 @@ version.workspace = true
|
|||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@ pub struct DirMeta {
|
|||
lines: Vec<String>,
|
||||
/// The file ended without a newline: kept so a write doesn't change its last line.
|
||||
no_final_newline: bool,
|
||||
/// Lines ended with `\r\n`: written back the same way.
|
||||
crlf: bool,
|
||||
}
|
||||
|
||||
impl DirMeta {
|
||||
|
|
@ -27,6 +29,7 @@ impl DirMeta {
|
|||
Self {
|
||||
lines: text.lines().map(str::to_owned).collect(),
|
||||
no_final_newline: !text.is_empty() && !text.ends_with('\n'),
|
||||
crlf: text.contains("\r\n"),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -126,6 +129,12 @@ impl DirMeta {
|
|||
.all(|l| l.trim().is_empty())
|
||||
{
|
||||
self.lines.drain(start..end);
|
||||
// The blank line that separated a group added at the end goes with it.
|
||||
if start >= self.lines.len() {
|
||||
while self.lines.last().is_some_and(|l| l.trim().is_empty()) {
|
||||
self.lines.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -286,12 +295,13 @@ fn escape(value: &str) -> String {
|
|||
|
||||
impl std::fmt::Display for DirMeta {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let eol = if self.crlf { "\r\n" } else { "\n" };
|
||||
let last = self.lines.len().saturating_sub(1);
|
||||
for (i, line) in self.lines.iter().enumerate() {
|
||||
if i == last && self.no_final_newline {
|
||||
write!(f, "{line}")?;
|
||||
} else {
|
||||
writeln!(f, "{line}")?;
|
||||
write!(f, "{line}{eol}")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
|
|
|||
217
crates/tunal-dirmeta/tests/dirmeta.rs
Normal file
217
crates/tunal-dirmeta/tests/dirmeta.rs
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
//! `.directory` files: untouched text survives parse + write byte for byte.
|
||||
|
||||
use std::fs;
|
||||
|
||||
use tunal_dirmeta::{DirMeta, FILE_NAME, IconRef, View};
|
||||
|
||||
const SAMPLE: &str = "# Written by another app\n\
|
||||
[Desktop Entry]\n\
|
||||
Icon=folder-music\n\
|
||||
Name=Music\n\
|
||||
Name[de]=Musik\n\
|
||||
Name[de_DE@euro]=Musik €\n\
|
||||
Name[pt_BR]=Música\n\
|
||||
Comment=keep me\n\
|
||||
\n\
|
||||
# KDE part\n\
|
||||
[Dolphin]\n\
|
||||
Timestamp=2020,1,2,3,4,5\n\
|
||||
ViewMode=1\n\
|
||||
\n\
|
||||
[X-Other]\n\
|
||||
Custom = spaced value\n";
|
||||
|
||||
#[test]
|
||||
fn untouched_text_round_trips_exactly() {
|
||||
for text in [
|
||||
SAMPLE,
|
||||
"",
|
||||
"\n",
|
||||
"[Desktop Entry]",
|
||||
"[Desktop Entry]\nIcon=x",
|
||||
"no group at all\n\n\n",
|
||||
"[A]\n[B]\n\n\n",
|
||||
" [Indented] \n key = v \n# c\n",
|
||||
"\n\n[Desktop Entry]\nIcon=€\n",
|
||||
] {
|
||||
assert_eq!(DirMeta::parse(text).to_string(), text, "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_through_a_file_is_byte_exact() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::write(dir.path().join(FILE_NAME), SAMPLE).unwrap();
|
||||
let meta = DirMeta::load(dir.path()).unwrap();
|
||||
meta.save(dir.path()).unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(dir.path().join(FILE_NAME)).unwrap(),
|
||||
SAMPLE
|
||||
);
|
||||
// No temp file is left behind.
|
||||
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_a_key_changes_only_its_line() {
|
||||
let mut meta = DirMeta::parse(SAMPLE);
|
||||
meta.set_icon(Some("folder-pictures"));
|
||||
let expected = SAMPLE.replace("Icon=folder-music", "Icon=folder-pictures");
|
||||
assert_eq!(meta.to_string(), expected);
|
||||
assert_eq!(meta.icon(), Some("folder-pictures"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_keys_keeps_everything_else() {
|
||||
let mut meta = DirMeta::parse(SAMPLE);
|
||||
meta.set_name(Some("Songs"));
|
||||
meta.set_tunal("Sort", Some("size"));
|
||||
let out = meta.to_string();
|
||||
// `Name` already existed: replaced in place; our group appended with a blank line before.
|
||||
assert!(out.contains("Name=Songs\n"));
|
||||
assert!(
|
||||
out.ends_with("Custom = spaced value\n\n[X-Tunal]\nSort=size\n"),
|
||||
"{out}"
|
||||
);
|
||||
for kept in [
|
||||
"# Written by another app",
|
||||
"Name[de]=Musik",
|
||||
"Comment=keep me",
|
||||
"# KDE part",
|
||||
"ViewMode=1",
|
||||
] {
|
||||
assert!(out.contains(kept), "{kept}");
|
||||
}
|
||||
// Removing it again restores the original bytes.
|
||||
meta.set_tunal("Sort", None);
|
||||
meta.set_name(Some("Music"));
|
||||
assert_eq!(meta.to_string(), SAMPLE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_is_added_at_the_end_of_its_group_before_trailing_blank_lines() {
|
||||
let mut meta = DirMeta::parse("[Desktop Entry]\nName=x\n\n[Other]\na=b\n");
|
||||
meta.set_icon(Some("i"));
|
||||
assert_eq!(
|
||||
meta.to_string(),
|
||||
"[Desktop Entry]\nName=x\nIcon=i\n\n[Other]\na=b\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_last_key_drops_only_our_empty_group() {
|
||||
let mut meta = DirMeta::parse("[X-Tunal]\nView=grid\n\n[Other]\na=b\n");
|
||||
meta.set_tunal("View", None);
|
||||
assert_eq!(meta.to_string(), "[Other]\na=b\n");
|
||||
// A group that still holds a (commented) line stays.
|
||||
let mut meta = DirMeta::parse("[Desktop Entry]\nIcon=x\n# note\n");
|
||||
meta.set_icon(None);
|
||||
assert!(meta.to_string().contains("# note"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localized_names_pick_the_best_match() {
|
||||
let meta = DirMeta::parse(SAMPLE);
|
||||
assert_eq!(meta.name_for(None).as_deref(), Some("Music"));
|
||||
assert_eq!(meta.name_for(Some("C")).as_deref(), Some("Music"));
|
||||
assert_eq!(meta.name_for(Some("POSIX")).as_deref(), Some("Music"));
|
||||
assert_eq!(meta.name_for(Some("de_AT.UTF-8")).as_deref(), Some("Musik"));
|
||||
assert_eq!(
|
||||
meta.name_for(Some("de_DE.UTF-8@euro")).as_deref(),
|
||||
Some("Musik €")
|
||||
);
|
||||
assert_eq!(
|
||||
meta.name_for(Some("pt_BR.UTF-8")).as_deref(),
|
||||
Some("Música")
|
||||
);
|
||||
assert_eq!(meta.name_for(Some("pt_PT")).as_deref(), Some("Music"));
|
||||
assert_eq!(meta.name_for(Some("fr_FR.UTF-8")).as_deref(), Some("Music"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_and_edge_cases() {
|
||||
// Last duplicate wins; empty values count as unset for icon and name.
|
||||
let meta = DirMeta::parse("[Desktop Entry]\nIcon=a\nIcon=b\nName=\n");
|
||||
assert_eq!(meta.icon(), Some("b"));
|
||||
assert_eq!(meta.name_for(None), None);
|
||||
// `=` inside the value, comment lines that look like keys, and keys in another group.
|
||||
let meta = DirMeta::parse("[Desktop Entry]\n#Icon=no\nName=a=b\n[Other]\nIcon=other\n");
|
||||
assert_eq!(meta.icon(), None);
|
||||
assert_eq!(meta.name_for(None).as_deref(), Some("a=b"));
|
||||
assert_eq!(meta.get("Other", "Icon"), Some("other"));
|
||||
// A value with a newline can't smuggle in a second key.
|
||||
let mut meta = DirMeta::default();
|
||||
meta.set_name(Some("a\nIcon=evil"));
|
||||
assert_eq!(meta.icon(), None);
|
||||
assert_eq!(meta.to_string(), "[Desktop Entry]\nName=a Icon=evil\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_settings_round_trip() {
|
||||
let view = View {
|
||||
mode: Some("grid".into()),
|
||||
sort: Some("modified".into()),
|
||||
descending: Some(true),
|
||||
group: Some("type".into()),
|
||||
hidden: Some(false),
|
||||
previews: Some(true),
|
||||
playlist: Some("best of.m3u".into()),
|
||||
};
|
||||
let mut meta = DirMeta::parse(SAMPLE);
|
||||
assert!(!meta.has_view());
|
||||
meta.set_view(&view);
|
||||
assert!(meta.has_view());
|
||||
let reparsed = DirMeta::parse(&meta.to_string());
|
||||
assert_eq!(reparsed.view(), view);
|
||||
meta.set_glyph(Some('\u{e2c7}'));
|
||||
assert_eq!(meta.glyph(), Some('\u{e2c7}'));
|
||||
meta.clear_view();
|
||||
meta.set_glyph(None);
|
||||
assert!(!meta.has_view());
|
||||
assert_eq!(meta.to_string(), SAMPLE);
|
||||
assert_eq!(meta.view(), View::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_an_empty_file_removes_it_and_a_missing_one_loads_empty() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(DirMeta::load(dir.path()).unwrap(), DirMeta::default());
|
||||
let mut meta = DirMeta::default();
|
||||
meta.set_icon(Some("x"));
|
||||
meta.save(dir.path()).unwrap();
|
||||
assert!(dir.path().join(FILE_NAME).exists());
|
||||
let mut meta = DirMeta::load(dir.path()).unwrap();
|
||||
meta.set_icon(None);
|
||||
meta.save(dir.path()).unwrap();
|
||||
assert!(!dir.path().join(FILE_NAME).exists());
|
||||
// Removing what is not there is fine.
|
||||
meta.save(dir.path()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icon_refs() {
|
||||
assert_eq!(
|
||||
IconRef::parse("folder-music"),
|
||||
IconRef::Theme("folder-music".into())
|
||||
);
|
||||
assert_eq!(IconRef::parse("/a/b.png"), IconRef::File("/a/b.png".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_files_survive_an_edit_of_one_key() {
|
||||
let text = "[Desktop Entry]\r\nIcon=a\r\nComment=c\r\n";
|
||||
let mut meta = DirMeta::parse(text);
|
||||
assert_eq!(meta.icon(), Some("a"));
|
||||
meta.set_icon(Some("b"));
|
||||
assert_eq!(
|
||||
meta.to_string(),
|
||||
"[Desktop Entry]\r\nIcon=b\r\nComment=c\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_utf8_file_is_an_error_not_a_panic() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
fs::write(dir.path().join(FILE_NAME), b"[Desktop Entry]\nName=\xff\n").unwrap();
|
||||
assert!(DirMeta::load(dir.path()).is_err());
|
||||
}
|
||||
|
|
@ -9,3 +9,6 @@ publish.workspace = true
|
|||
tunal-core = { path = "../tunal-core" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
|
|
|||
343
crates/tunal-elevate/tests/helper.rs
Normal file
343
crates/tunal-elevate/tests/helper.rs
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
//! The root helper driven as the normal user (no pkexec): the `helper_smoke` example doubles
|
||||
//! as the helper binary (`<exe> --elevated-helper`).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::ops::ControlFlow;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
|
||||
use tunal_core::{Error, Location, Uri, WriteMode};
|
||||
use tunal_elevate::protocol::{self, Reply, Request};
|
||||
use tunal_elevate::{ElevatedLocal, Elevation, HELPER_ARG};
|
||||
|
||||
/// `target/<profile>/examples/helper_smoke`, built by `cargo test` before the tests run.
|
||||
fn helper_exe() -> PathBuf {
|
||||
let mut dir = std::env::current_exe().unwrap();
|
||||
dir.pop();
|
||||
if dir.ends_with("deps") {
|
||||
dir.pop();
|
||||
}
|
||||
let exe = dir.join("examples/helper_smoke");
|
||||
assert!(
|
||||
exe.exists(),
|
||||
"{} is missing: run through `cargo test`",
|
||||
exe.display()
|
||||
);
|
||||
exe
|
||||
}
|
||||
|
||||
fn at(dir: &Path, name: &str) -> Uri {
|
||||
Uri::from_path(&dir.join(name))
|
||||
}
|
||||
|
||||
fn start() -> ElevatedLocal {
|
||||
ElevatedLocal::spawn_unelevated(&helper_exe()).expect("launch helper")
|
||||
}
|
||||
|
||||
struct Raw {
|
||||
child: std::process::Child,
|
||||
input: Option<std::process::ChildStdin>,
|
||||
output: std::process::ChildStdout,
|
||||
}
|
||||
|
||||
impl Raw {
|
||||
fn new() -> Self {
|
||||
let mut child = Command::new(helper_exe())
|
||||
.arg(HELPER_ARG)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
Self {
|
||||
input: child.stdin.take(),
|
||||
output: child.stdout.take().unwrap(),
|
||||
child,
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, request: &Request) -> Reply {
|
||||
protocol::send(self.input.as_mut().unwrap(), request).unwrap();
|
||||
protocol::recv::<Reply>(&mut self.output)
|
||||
.unwrap()
|
||||
.expect("reply")
|
||||
}
|
||||
|
||||
fn hello(&mut self) {
|
||||
let reply = self.call(&Request::Hello {
|
||||
version: protocol::VERSION,
|
||||
});
|
||||
assert!(matches!(reply, Reply::Hello { version } if version == protocol::VERSION));
|
||||
}
|
||||
|
||||
/// Closes stdin and waits for the helper to exit.
|
||||
fn finish(mut self) -> std::process::ExitStatus {
|
||||
drop(self.input.take());
|
||||
self.child.wait().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_operations_through_the_helper() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let d = dir.path();
|
||||
let helper = start();
|
||||
helper.mkdir(&at(d, "sub")).unwrap();
|
||||
assert_eq!(helper.mkdir(&at(d, "sub")), Err(Error::Exists));
|
||||
let data: Vec<u8> = (0..700_000u32).map(|i| (i % 251) as u8).collect();
|
||||
let mut w = helper
|
||||
.open_write(&at(d, "sub/a.bin"), WriteMode::CreateNew)
|
||||
.unwrap();
|
||||
w.write_all(&data).unwrap();
|
||||
drop(w);
|
||||
assert_eq!(std::fs::read(d.join("sub/a.bin")).unwrap(), data);
|
||||
assert!(matches!(
|
||||
helper.open_write(&at(d, "sub/a.bin"), WriteMode::CreateNew),
|
||||
Err(Error::Exists)
|
||||
));
|
||||
let mut back = Vec::new();
|
||||
helper
|
||||
.open_read(&at(d, "sub/a.bin"))
|
||||
.unwrap()
|
||||
.read_to_end(&mut back)
|
||||
.unwrap();
|
||||
assert_eq!(back, data);
|
||||
|
||||
let mut steps = 0;
|
||||
helper
|
||||
.copy_file(
|
||||
&at(d, "sub/a.bin"),
|
||||
&at(d, "sub/b.bin"),
|
||||
WriteMode::CreateNew,
|
||||
|_| steps += 1,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read(d.join("sub/b.bin")).unwrap(), data);
|
||||
assert_eq!(
|
||||
helper.copy_file(
|
||||
&at(d, "sub/a.bin"),
|
||||
&at(d, "sub/b.bin"),
|
||||
WriteMode::CreateNew,
|
||||
|_| ()
|
||||
),
|
||||
Err(Error::Exists)
|
||||
);
|
||||
helper
|
||||
.copy_file(
|
||||
&at(d, "sub/a.bin"),
|
||||
&at(d, "sub/b.bin"),
|
||||
WriteMode::Overwrite,
|
||||
|_| (),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
helper
|
||||
.rename(&at(d, "sub/b.bin"), &at(d, "sub/c.bin"))
|
||||
.unwrap();
|
||||
helper.symlink(&at(d, "sub/link"), b"c.bin").unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_link(d.join("sub/link")).unwrap(),
|
||||
Path::new("c.bin")
|
||||
);
|
||||
|
||||
let mut listed = Vec::new();
|
||||
helper
|
||||
.list(&at(d, "sub"), &mut |chunk| {
|
||||
listed.extend(chunk.into_iter().map(|e| (e.display_name, e.size)));
|
||||
ControlFlow::Continue(())
|
||||
})
|
||||
.unwrap();
|
||||
listed.sort();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
("a.bin".to_string(), 700_000),
|
||||
("c.bin".to_string(), 700_000),
|
||||
("link".to_string(), 5)
|
||||
]
|
||||
);
|
||||
assert_eq!(helper.stat(&at(d, "sub/a.bin")).unwrap().size, 700_000);
|
||||
|
||||
for name in ["sub/a.bin", "sub/c.bin", "sub/link", "sub"] {
|
||||
helper.delete(&at(d, name)).unwrap();
|
||||
}
|
||||
assert_eq!(helper.stat(&at(d, "sub")), Err(Error::NotFound));
|
||||
assert_eq!(helper.delete(&at(d, "sub")), Err(Error::NotFound));
|
||||
assert!(std::fs::read_dir(d).unwrap().next().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_cross_the_pipe_as_the_same_kind() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let helper = start();
|
||||
let missing = at(dir.path(), "nope/deeper");
|
||||
assert_eq!(helper.stat(&missing), Err(Error::NotFound));
|
||||
assert!(matches!(helper.open_read(&missing), Err(Error::NotFound)));
|
||||
assert_eq!(helper.mkdir(&missing), Err(Error::NotFound));
|
||||
let mut seen = 0;
|
||||
let result = helper.list(&missing, &mut |_| {
|
||||
seen += 1;
|
||||
ControlFlow::Continue(())
|
||||
});
|
||||
assert_eq!((result, seen), (Err(Error::NotFound), 0));
|
||||
std::fs::create_dir_all(dir.path().join("full/x")).unwrap();
|
||||
assert_eq!(helper.delete(&at(dir.path(), "full")), Err(Error::NotEmpty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_helper_lists_big_folders_in_chunks() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for i in 0..1000 {
|
||||
std::fs::File::create(dir.path().join(format!("f{i}"))).unwrap();
|
||||
}
|
||||
let helper = start();
|
||||
let (mut total, mut chunks) = (0, 0);
|
||||
helper
|
||||
.list(&Uri::from_path(dir.path()), &mut |chunk| {
|
||||
total += chunk.len();
|
||||
chunks += 1;
|
||||
ControlFlow::Continue(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(total, 1000);
|
||||
assert!(chunks >= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_and_relative_paths() {
|
||||
let mut raw = Raw::new();
|
||||
raw.hello();
|
||||
let reply = raw.call(&Request::Mkdir {
|
||||
path: b"relative".to_vec(),
|
||||
});
|
||||
assert!(matches!(reply, Reply::Error(_)), "{reply:?}");
|
||||
for bad in [b"/with\0nul".to_vec(), b"".to_vec()] {
|
||||
let reply = raw.call(&Request::Stat { path: bad });
|
||||
assert!(matches!(reply, Reply::Error(_)));
|
||||
}
|
||||
// Unknown handles are refused, not panics.
|
||||
assert!(matches!(
|
||||
raw.call(&Request::Close { handle: 99 }),
|
||||
Reply::Error(_)
|
||||
));
|
||||
assert!(raw.finish().success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_protocol_version_is_refused() {
|
||||
let mut raw = Raw::new();
|
||||
let reply = raw.call(&Request::Hello { version: 99 });
|
||||
assert!(matches!(reply, Reply::Error(_)), "{reply:?}");
|
||||
// The helper stops after refusing.
|
||||
assert!(raw.finish().success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eof_before_the_handshake_ends_quietly() {
|
||||
assert!(Raw::new().finish().success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helper_exits_when_the_client_is_dropped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let helper = start();
|
||||
helper.mkdir(&at(dir.path(), "x")).unwrap();
|
||||
// Dropping closes stdin; the Drop impl waits for the helper, so this must return.
|
||||
drop(helper);
|
||||
assert!(dir.path().join("x").is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elevation_switches_only_the_elevated_thread() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let d = dir.path().to_path_buf();
|
||||
let exe = helper_exe();
|
||||
let launches = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let counted = launches.clone();
|
||||
let elevation = Arc::new(Elevation::with_launcher(move || {
|
||||
counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
ElevatedLocal::spawn_unelevated(&exe)
|
||||
}));
|
||||
let me = std::thread::current().id();
|
||||
|
||||
// Not elevated: local, no helper started.
|
||||
elevation.mkdir(&at(&d, "plain")).unwrap();
|
||||
assert_eq!(launches.load(std::sync::atomic::Ordering::Relaxed), 0);
|
||||
|
||||
elevation.elevate(me);
|
||||
elevation.mkdir(&at(&d, "via-helper")).unwrap();
|
||||
elevation.mkdir(&at(&d, "via-helper-2")).unwrap();
|
||||
assert_eq!(
|
||||
launches.load(std::sync::atomic::Ordering::Relaxed),
|
||||
1,
|
||||
"one shared helper"
|
||||
);
|
||||
let other = elevation.clone();
|
||||
let target = at(&d, "other-thread");
|
||||
std::thread::spawn(move || other.mkdir(&target).unwrap())
|
||||
.join()
|
||||
.unwrap();
|
||||
assert_eq!(launches.load(std::sync::atomic::Ordering::Relaxed), 1);
|
||||
|
||||
elevation
|
||||
.write_file(
|
||||
&at(&d, "via-helper/.directory"),
|
||||
b"[Desktop Entry]\nIcon=folder\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(d.join("via-helper/.directory")).unwrap(),
|
||||
"[Desktop Entry]\nIcon=folder\n"
|
||||
);
|
||||
|
||||
// Released: the helper stops and the next call is local again.
|
||||
elevation.release(me);
|
||||
elevation.mkdir(&at(&d, "after")).unwrap();
|
||||
assert_eq!(launches.load(std::sync::atomic::Ordering::Relaxed), 1);
|
||||
for n in ["plain", "via-helper-2", "other-thread", "after"] {
|
||||
assert!(d.join(n).is_dir(), "{n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_file_without_elevated_threads_starts_and_stops_a_helper() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = helper_exe();
|
||||
let elevation = Elevation::with_launcher(move || ElevatedLocal::spawn_unelevated(&exe));
|
||||
elevation.write_file(&at(dir.path(), "f"), b"data").unwrap();
|
||||
assert_eq!(std::fs::read(dir.path().join("f")).unwrap(), b"data");
|
||||
elevation.write_file(&at(dir.path(), "f"), b"new").unwrap();
|
||||
assert_eq!(std::fs::read(dir.path().join("f")).unwrap(), b"new");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_prompt_drops_the_elevation_so_the_next_try_asks_again() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = helper_exe();
|
||||
let fail = Arc::new(std::sync::atomic::AtomicBool::new(true));
|
||||
let flag = fail.clone();
|
||||
let elevation = Elevation::with_launcher(move || {
|
||||
if flag.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
Err(Error::Remote("password prompt cancelled".into()))
|
||||
} else {
|
||||
ElevatedLocal::spawn_unelevated(&exe)
|
||||
}
|
||||
});
|
||||
elevation.elevate(std::thread::current().id());
|
||||
assert_eq!(
|
||||
elevation.mkdir(&at(dir.path(), "a")),
|
||||
Err(Error::Remote("password prompt cancelled".into()))
|
||||
);
|
||||
// The thread is local again: this call must not need the helper at all.
|
||||
elevation.mkdir(&at(dir.path(), "b")).unwrap();
|
||||
assert!(dir.path().join("b").is_dir() && !dir.path().join("a").exists());
|
||||
fail.store(false, std::sync::atomic::Ordering::Relaxed);
|
||||
elevation.elevate(std::thread::current().id());
|
||||
elevation.mkdir(&at(dir.path(), "c")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_helper_program_is_a_clear_error() {
|
||||
let result = ElevatedLocal::spawn_unelevated(Path::new("/nonexistent/tunal-helper"));
|
||||
assert!(matches!(result, Err(Error::Remote(_))));
|
||||
}
|
||||
203
crates/tunal-elevate/tests/protocol.rs
Normal file
203
crates/tunal-elevate/tests/protocol.rs
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
//! Wire format: frames, messages, errors and entries survive the pipe.
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
use tunal_core::{Entry, Error, FileType, Kind};
|
||||
use tunal_elevate::protocol::{
|
||||
Frame, Reply, Request, VERSION, WireEntry, WireError, read_frame, recv, recv_data, send,
|
||||
send_data,
|
||||
};
|
||||
|
||||
fn entry(name: &[u8], kind: Kind) -> Entry {
|
||||
Entry {
|
||||
display_name: tunal_core::display_name(name),
|
||||
hidden: name.first() == Some(&b'.'),
|
||||
mime: tunal_core::mime::mime_type(name, &kind),
|
||||
kind,
|
||||
name: name.to_vec(),
|
||||
size: 1234,
|
||||
mtime: Some(UNIX_EPOCH + Duration::new(1_700_000_000, 123_456_789)),
|
||||
mode: 0o640,
|
||||
uid: 1000,
|
||||
gid: 100,
|
||||
}
|
||||
}
|
||||
|
||||
fn round_trip(e: Entry) -> Entry {
|
||||
let mut buf = Vec::new();
|
||||
send(&mut buf, &Reply::Entry(e.into())).unwrap();
|
||||
match recv::<Reply>(&mut Cursor::new(buf)).unwrap().unwrap() {
|
||||
Reply::Entry(w) => w.into(),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_round_trip_with_raw_paths() {
|
||||
let mut buf = Vec::new();
|
||||
let request = Request::Rename {
|
||||
from: b"/a/\xff odd".to_vec(),
|
||||
to: b"/b".to_vec(),
|
||||
};
|
||||
send(&mut buf, &request).unwrap();
|
||||
send(&mut buf, &Request::Hello { version: VERSION }).unwrap();
|
||||
let mut input = Cursor::new(buf);
|
||||
match recv::<Request>(&mut input).unwrap().unwrap() {
|
||||
Request::Rename { from, to } => {
|
||||
assert_eq!((from, to), (b"/a/\xff odd".to_vec(), b"/b".to_vec()))
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(matches!(
|
||||
recv::<Request>(&mut input).unwrap().unwrap(),
|
||||
Request::Hello { version } if version == VERSION
|
||||
));
|
||||
// Clean end of stream.
|
||||
assert!(recv::<Request>(&mut input).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_frames_keep_every_byte() {
|
||||
let bytes: Vec<u8> = (0..=255).collect();
|
||||
let mut buf = Vec::new();
|
||||
send_data(&mut buf, &bytes).unwrap();
|
||||
send_data(&mut buf, &[]).unwrap();
|
||||
let mut input = Cursor::new(buf);
|
||||
assert_eq!(recv_data(&mut input).unwrap(), bytes);
|
||||
assert!(recv_data(&mut input).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_layout_is_length_kind_payload() {
|
||||
let mut buf = Vec::new();
|
||||
send_data(&mut buf, b"abc").unwrap();
|
||||
assert_eq!(buf, [0, 0, 0, 4, 1, b'a', b'b', b'c']);
|
||||
match read_frame(&mut Cursor::new(buf)).unwrap().unwrap() {
|
||||
Frame::Data(d) => assert_eq!(d, b"abc"),
|
||||
Frame::Message(_) => panic!("kind"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_frames_are_errors_not_panics() {
|
||||
let bad = |bytes: Vec<u8>| read_frame(&mut Cursor::new(bytes)).err().map(|e| e.kind());
|
||||
use std::io::ErrorKind::{InvalidData, UnexpectedEof};
|
||||
// Zero length, oversized length, unknown kind.
|
||||
assert_eq!(bad(vec![0, 0, 0, 0]), Some(InvalidData));
|
||||
assert_eq!(bad(vec![0xff, 0xff, 0xff, 0xff, 0]), Some(InvalidData));
|
||||
assert_eq!(bad(vec![0, 0, 0, 1, 9]), Some(InvalidData));
|
||||
// Cut off in the middle of a frame.
|
||||
assert_eq!(bad(vec![0, 0, 0, 10, 0, b'x']), Some(UnexpectedEof));
|
||||
// A short header is a clean end.
|
||||
assert!(read_frame(&mut Cursor::new(vec![0, 0])).unwrap().is_none());
|
||||
assert!(
|
||||
read_frame(&mut Cursor::new(Vec::<u8>::new()))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_frame_kind_for_the_caller_is_rejected() {
|
||||
let mut buf = Vec::new();
|
||||
send_data(&mut buf, b"x").unwrap();
|
||||
assert!(recv::<Reply>(&mut Cursor::new(buf)).is_err());
|
||||
let mut buf = Vec::new();
|
||||
send(&mut buf, &Reply::Done).unwrap();
|
||||
assert!(recv_data(&mut Cursor::new(buf)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_json_is_an_error() {
|
||||
let mut buf = Vec::new();
|
||||
let payload = b"{not json";
|
||||
buf.extend_from_slice(&(payload.len() as u32 + 1).to_be_bytes());
|
||||
buf.push(0);
|
||||
buf.extend_from_slice(payload);
|
||||
assert!(recv::<Request>(&mut Cursor::new(buf)).is_err());
|
||||
// Valid JSON, unknown message.
|
||||
let mut buf = Vec::new();
|
||||
send(&mut buf, &"Teleport").unwrap();
|
||||
assert!(recv::<Request>(&mut Cursor::new(buf)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_error_survives_the_wire() {
|
||||
for e in [
|
||||
Error::NotFound,
|
||||
Error::PermissionDenied,
|
||||
Error::Exists,
|
||||
Error::NotEmpty,
|
||||
Error::Unsupported,
|
||||
Error::Cancelled,
|
||||
Error::Io("disk \"full\"\n".into()),
|
||||
Error::Remote("héllo".into()),
|
||||
] {
|
||||
let mut buf = Vec::new();
|
||||
send(&mut buf, &Reply::Error(WireError::from(e.clone()))).unwrap();
|
||||
match recv::<Reply>(&mut Cursor::new(buf)).unwrap().unwrap() {
|
||||
Reply::Error(w) => assert_eq!(Error::from(w), e),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_survive_the_wire() {
|
||||
for kind in [
|
||||
Kind::File,
|
||||
Kind::Dir,
|
||||
Kind::Special,
|
||||
Kind::Symlink {
|
||||
target: b"../t\xff".to_vec(),
|
||||
target_type: Some(FileType::Dir),
|
||||
},
|
||||
Kind::Symlink {
|
||||
target: b"x".to_vec(),
|
||||
target_type: Some(FileType::Special),
|
||||
},
|
||||
Kind::Symlink {
|
||||
target: b"gone".to_vec(),
|
||||
target_type: None,
|
||||
},
|
||||
] {
|
||||
let original = entry(b".odd \xff name.txt", kind);
|
||||
let back = round_trip(original.clone());
|
||||
assert_eq!(back, original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn special_mime_types_are_kept_and_others_recomputed() {
|
||||
let mut fifo = entry(b"pipe", Kind::Special);
|
||||
fifo.mime = "inode/fifo";
|
||||
assert_eq!(round_trip(fifo).mime, "inode/fifo");
|
||||
let file = entry(b"song.mp3", Kind::File);
|
||||
assert_eq!(round_trip(file.clone()).mime, file.mime);
|
||||
// A made-up MIME on the wire is not trusted.
|
||||
let mut buf = Vec::new();
|
||||
send(&mut buf, &Reply::Entry(entry(b"a.txt", Kind::File).into())).unwrap();
|
||||
let text = String::from_utf8_lossy(&buf[5..]).replace("\"mime\":null", "\"mime\":\"x/evil\"");
|
||||
let mut forged = Vec::new();
|
||||
forged.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes());
|
||||
forged.push(0);
|
||||
forged.extend_from_slice(text.as_bytes());
|
||||
match recv::<Reply>(&mut Cursor::new(forged)).unwrap().unwrap() {
|
||||
Reply::Entry(w) => assert_ne!(Entry::from(w).mime, "x/evil"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_mtime_stays_missing() {
|
||||
let mut e = entry(b"a", Kind::File);
|
||||
e.mtime = None;
|
||||
assert_eq!(round_trip(e).mtime, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_and_version_constants_are_sane() {
|
||||
assert_eq!(VERSION, 1);
|
||||
let _ = WireEntry::from(entry(b"x", Kind::File));
|
||||
}
|
||||
|
|
@ -253,6 +253,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
|
|||
- Verified: build, clippy -D warnings, fmt; Xvfb `:97` with `WAYLAND_DISPLAY` unset: drag of notes.txt out of the window → app logs start_drag + XdndEnter sent + dropped (copy), probe got the uri-list; probe dropping a file on the Music row → status accept after the list was read, XdndFinished accept=1.
|
||||
- Not done: clipboard copy/paste not exercised (no key injection set up); no drag icon on X11; real apps in S036.
|
||||
|
||||
## S032 — Tests: core, ops, trash, dirmeta, elevation protocol
|
||||
- Done: `tests/` in `tunal-core` (`location.rs` URIs, registry, non-UTF-8/symlink/denied/10 000-entry listing, write modes, watch; `ops.rs` copy/move/delete/mkdir/rename/link, every conflict resolution + apply-to-all, error Retry/SkipAll/Abort, cancel at a conflict and mid-file, cross-device move via /dev/shm, copy into self, naming helpers; `trash.rs` with `XDG_DATA_HOME` in a temp dir: `.trashinfo` encoding, collisions, restore conflicts, browsing, empty), `tunal-dirmeta` (`dirmeta.rs` byte-exact round trips, localized names, view keys), `tunal-elevate` (`protocol.rs` frames/messages/errors/entries; `helper.rs` drives the `helper_smoke` example as helper without pkexec, handshake, relative paths, Elevation thread switching). `tempfile` workspace dev-dep.
|
||||
- Bugs fixed (each with a regression test): a file copied/moved over a folder with Overwrite failed with "Is a directory" (`ops/run.rs`, `file_over_folder_overwrite_replaces_it`); a `.directory` with CRLF line ends was rewritten with LF; removing the last key of a group appended at the end of the file left a stray blank line (`tunal-dirmeta`).
|
||||
- Safety: trash tests hold one lock, and skip when a per-mount trash of the user is visible (`EmptyTrash` would delete it); none found on this machine.
|
||||
- Not done: permission tests skip as root; cross-device test skips when /dev/shm shares the temp device; no pkexec/polkit run; per-mount (`.Trash-$uid`) trash paths untested.
|
||||
|
||||
## Later
|
||||
- (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034.
|
||||
-
|
||||
|
|
|
|||
Loading…
Reference in a new issue