diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index acbd218..a7e817f 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -3279,8 +3279,8 @@ impl App { if o.cancelled && let Some(v) = &view { - // The user asked for it, so it only tells. - self.note(format!("Stopped: {}", v.job.label)); + // The user asked for it, so it only tells. A move taken back says so. + self.note(o.stopped.clone().unwrap_or_else(|| format!("Stopped: {}", v.job.label))); } if let (Some(v), [made]) = (&view, o.created.as_slice()) && v.say_made diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index e4084c7..1ebd65e 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -268,6 +268,8 @@ fn main() { app.slow_read = std::env::var("GANNET_SLOW_READ_MS").ok().and_then(|v| v.parse().ok()).map(std::time::Duration::from_millis); app.slow_preview = std::env::var("GANNET_SLOW_PREVIEW_MS").ok().and_then(|v| v.parse().ok()).map(std::time::Duration::from_millis); app.engine.slow_copy = std::env::var("GANNET_SLOW_COPY_MS").ok().and_then(|v| v.parse().ok()).map(std::time::Duration::from_millis); + // So the end-to-end checks can fill a disk partway through a move. + app.engine.skip_space_check = std::env::var_os("GANNET_SKIP_SPACE_CHECK").is_some(); // So the end-to-end checks can ask about an archive of a few MiB. if let Some(bytes) = std::env::var("GANNET_EXTRACT_ASK_AFTER").ok().and_then(|v| v.parse().ok()) { app.engine.extract_limits.ask_after = bytes; diff --git a/crates/app/tests/cli.rs b/crates/app/tests/cli.rs index c1563d5..7035363 100644 --- a/crates/app/tests/cli.rs +++ b/crates/app/tests/cli.rs @@ -96,6 +96,19 @@ fn failures_go_to_stderr_with_exit_code_1() { assert!(text(&out.stdout).ends_with(&want), "{}", text(&out.stdout)); } +#[test] +fn each_path_that_fails_gets_its_own_error() { + let h = Home::new("each-path"); + // They fail alike, which the window tells as one notice, but here each keeps its path. + let out = h.gannet(&["trash", "--json", "a", "b", "c"]); + assert_eq!(out.status.code(), Some(1)); + let json = text(&out.stdout); + for name in ["a", "b", "c"] { + assert!(json.contains(&format!("{{\"path\":\"{}\",", h.work().join(name).display())), "{name}: {json}"); + } + assert!(!json.contains("\"path\":\"\""), "no error without its path: {json}"); +} + #[test] fn help_names_the_commands() { let h = Home::new("help"); diff --git a/crates/core/src/cli.rs b/crates/core/src/cli.rs index e7f70bd..0ea291e 100644 --- a/crates/core/src/cli.rs +++ b/crates/core/src/cli.rs @@ -342,9 +342,11 @@ fn trash_record(cfg: &TrashConfig, path: &Path) -> Option> { /// Runs one job in the operations engine, as the window would, and waits for it. fn run_job(env: &Env, request: Request, report: &mut Report) -> Option { let (tx, rx) = mpsc::channel(); - let engine = Engine::new(env.trash.clone(), Arc::new(move |e| { + let mut engine = Engine::new(env.trash.clone(), Arc::new(move |e| { let _ = tx.send(e); })); + // Each path given gets its own result, not one message for all that failed alike. + engine.tell_each = true; engine.start(request); // Only the job's thread can send now, so a job that dies ends the wait instead of hanging it. drop(engine); @@ -359,7 +361,7 @@ fn run_job(env: &Env, request: Request, report: &mut Report) -> Option let _ = q.reply.send(false); } // The window's advice about Shift+Delete means nothing here. - Event::Error { path, message, .. } => report.fail(Some(&path), message.trim_end_matches(" Shift+Delete deletes for good.")), + Event::Error { path, message, .. } => report.fail(Some(path.as_path()).filter(|p| !p.as_os_str().is_empty()), message.trim_end_matches(" Shift+Delete deletes for good.")), Event::Finished(o) => return Some(o), } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 360aac5..d7d8f85 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -27,6 +27,7 @@ pub mod search; pub mod servers; pub mod settings; pub mod sort; +pub mod space; pub mod terminal; pub mod theme; pub mod thumbcache; diff --git a/crates/core/src/mounts.rs b/crates/core/src/mounts.rs index da16f85..75b1dc7 100644 --- a/crates/core/src/mounts.rs +++ b/crates/core/src/mounts.rs @@ -59,6 +59,18 @@ pub fn inodes_may_change(fs_type: &str) -> bool { ["nfs", "nfs4", "cifs", "smb3", "smbfs", "9p", "ceph", "glusterfs", "davfs"].contains(&fs_type) || fs_type.starts_with("fuse") } +/// Whether a filesystem of this kind really gives a file another inode number from one look to +/// the next: a network share, or FUSE over a network. Narrower than [`inodes_may_change`], +/// which is for telling a folder apart and so also takes in any FUSE: a local FUSE drive, as +/// ntfs-3g (`fuseblk`) or exFAT, keeps its numbers. +pub fn inodes_renumbered(fs_type: &str) -> bool { + // Plain `fuse` says nothing about what's behind it, so it's left out, and taken as stable. + const NETWORK: [&str; 24] = [ + "nfs", "nfs4", "cifs", "smb3", "smbfs", "9p", "ceph", "glusterfs", "davfs", "afs", "lustre", "vboxsf", "sshfs", "fuse.sshfs", "fuse.gvfsd-fuse", "fuse.rclone", "fuse.s3fs", "fuse.curlftpfs", "fuse.glusterfs", "fuse.ceph-fuse", "fuse.davfs", "fuse.mtpfs", "fuse.jmtpfs", "fuse.simple-mtpfs", + ]; + NETWORK.contains(&fs_type) +} + /// The mount point holding `path`, which should already be canonical. pub fn mount_point_of(mounts: &[Mount], path: &Path) -> Option { mounts.iter().filter(|m| path.starts_with(&m.point)).max_by_key(|m| m.point.as_os_str().len()).map(|m| m.point.clone()) diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index 5d9c212..b6a5184 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -6,14 +6,23 @@ //! - Nothing gets overwritten. Replace first moves the item already there to the Trash, //! and if it can't go there, both stay as they were. //! - Symlinks are copied and moved as symlinks, never followed. -//! - One item failing doesn't stop the others. Each failure gets reported. Renaming several -//! items at once is the exception: it's all or nothing, so the names never end up half -//! changed. -//! - A move across disks removes each source only after its copy succeeded. +//! - One item failing doesn't stop the others. Each failure gets reported, once per job for +//! items that failed the same way. Renaming several items at once is the exception: it's all +//! or nothing, so the names never end up half changed. +//! - A full destination is the other exception. A copy or move stops at the first "no space", +//! and everything the job made is taken away again, never anything that was there before. +//! A copy to another disk is checked for room before it starts, when that's cheap and the +//! answer is clear. A move across disks that is stopped is taken back the same way. +//! - A move across disks removes the sources only once all of it has been copied, and each +//! source only if its copy succeeded. //! - Folders never get replaced wholesale. Replace on two folders means merge. //! - Delete and cross-disk move stop at mount points inside a folder: another disk's //! contents are never removed because it happens to be mounted there. //! - A cross-disk move syncs each copy to disk before removing its source. +//! - Two known limits of taking a copy back. A move across disks notes each source it copied +//! until the end, so a tree of millions of files holds millions of paths for a while. And a +//! folder the job made goes with everything in it, which includes anything another program +//! put there while the job ran. //! - Undo and redo act only on the item a change left behind, told apart by its disk, //! inode, birth time and inode generation, never on something else that has since taken //! its name. Neither ever deletes anything but an empty folder that the change made. @@ -32,7 +41,8 @@ use std::time::{Duration, Instant}; use rustix::fs::{AtFlags, CWD, RenameFlags, StatxAttributes, StatxFlags, Timespec, Timestamps, XattrFlags, copy_file_range, fgetxattr, flistxattr, fsetxattr, futimens, renameat_with, sendfile, statx, syncfs}; use rustix::io::Errno; -use crate::listing::describe; +use crate::listing::{describe, size}; +use crate::space; use crate::trash::{self, MountCache, TrashConfig, TrashError, Trashed}; #[derive(Clone, Debug)] @@ -233,6 +243,8 @@ pub struct Outcome { pub created: Vec, /// Folders that changed, so the UI can refresh them if inotify can't see them. pub touched: Vec, + /// For a cancelled job that was taken back, what to say instead of that it stopped. + pub stopped: Option, } pub enum Event { @@ -240,7 +252,10 @@ pub enum Event { Progress(u64), Conflict(Conflict), Expands(Expands), - Error { job: u64, path: PathBuf, message: String }, + /// Something went wrong, told when the job ends, one message for each reason. `path` is + /// the item when only one failed this way, and empty when the message counts several or is + /// about no one item. `paths` holds the first few that failed this way, of `count` in all. + Error { job: u64, path: PathBuf, message: String, paths: Vec, count: usize }, Finished(Outcome), } @@ -257,6 +272,11 @@ pub struct Engine { pub force_sync_error: bool, /// Test seam: copy with read and write, as on a kernel that refuses `sendfile`. pub force_no_sendfile: bool, + /// Test seam: don't check for room before a copy, so one can fill its destination partway. + pub skip_space_check: bool, + /// Tell each failure as it happens, with its own path, rather than once per reason at the + /// end. For the command line, which reports each path it was given. + pub tell_each: bool, /// Test seam: wait this long between a file's chunks as `copy_file_range` copies it, so a /// copy lasts long enough to follow its progress without writing gigabytes. The `sendfile` /// and read-and-write fallbacks don't wait. @@ -269,7 +289,7 @@ pub struct Engine { impl Engine { pub fn new(trash: TrashConfig, sink: Sink) -> Self { - Self { trash, sink, next_id: Arc::new(AtomicU64::new(1)), force_exdev: false, force_sync_error: false, force_no_sendfile: false, slow_copy: None, extractor: crate::archive::BSDTAR.into(), extract_limits: crate::archive::Limits::default() } + Self { trash, sink, next_id: Arc::new(AtomicU64::new(1)), force_exdev: false, force_sync_error: false, force_no_sendfile: false, skip_space_check: false, tell_each: false, slow_copy: None, extractor: crate::archive::BSDTAR.into(), extract_limits: crate::archive::Limits::default() } } /// A job for work done somewhere else, like formatting a drive, so it shows and can be @@ -291,11 +311,15 @@ impl Engine { force_exdev: self.force_exdev, force_sync_error: self.force_sync_error, force_no_sendfile: self.force_no_sendfile, + skip_space_check: self.skip_space_check, slow_copy: self.slow_copy, extractor: self.extractor.clone(), extract_limits: self.extract_limits, asked_expands: false, errors: 0, + failures: Failures::default(), + tell_each: self.tell_each, + stopped: None, noted_leftovers: 0, private_seen: false, sticky_files: None, @@ -303,6 +327,19 @@ impl Engine { last_merged: false, last_replaced: None, top_dev: 0, + need: 0, + measured: Default::default(), + full: false, + made: Vec::new(), + inside_new: false, + to_delete: Vec::new(), + renamed: 0, + care: None, + looked_at: std::time::SystemTime::now(), + moving_top: None, + started: std::time::SystemTime::now(), + mount_table: None, + finished_anyway: false, steps: Vec::new(), trashed: Vec::new(), mounts: MountCache::default(), @@ -319,16 +356,18 @@ impl Engine { run.execute(request); let trashed = std::mem::take(&mut run.trashed); run.sync_trash(&trashed); + run.tell_failures(); let steps = std::mem::take(&mut run.steps); let outcome = Outcome { job: run.job.id, - cancelled: run.job.is_cancelled(), + cancelled: run.job.is_cancelled() && !run.finished_anyway, errors: run.errors, skipped: run.noted_leftovers, undo: (!steps.is_empty()).then_some(Undo(steps)), reversed: run.reversed, created: std::mem::take(&mut run.created), touched: std::mem::take(&mut run.touched), + stopped: run.stopped.take(), }; (run.sink)(Event::Finished(outcome)); }) @@ -495,6 +534,257 @@ enum Flow { Stop, } +/// Which side of a change an error came from, so its reason names the right thing. +#[derive(Clone, Copy)] +enum Side<'a> { + /// Reading the item. + Read, + /// Writing in this folder. + Write(&'a Path), + /// Changing the item where it is, as renaming or deleting it does. + Change, +} + +/// Which file of a copy an error came from. +enum End { + Source, + Copy, +} + +/// What went wrong, in plain words. `one` follows a single item's name, and `many` follows a +/// count of items that failed the same way. Failures with the same `key` are told as one. +#[derive(Debug, PartialEq)] +struct Reason { + key: String, + one: String, + many: String, +} + +impl Reason { + fn same(text: String) -> Reason { + Reason { key: text.clone(), one: text.clone(), many: text } + } +} + +/// `“name”`, for a path in a message. +fn quoted(p: &Path) -> String { + format!("“{}”", p.file_name().unwrap_or(p.as_os_str()).to_string_lossy()) +} + +/// Says why `item` failed, by the kind of error rather than the system's words for it, which +/// stay for kinds not listed here. +fn reason(e: &io::Error, item: &Path, side: Side) -> Reason { + let folder = match side { + Side::Read => None, + Side::Write(f) => Some(f), + Side::Change => item.parent().filter(|p| !p.as_os_str().is_empty()), + }; + let kind = e.raw_os_error().map(Errno::from_raw_os_error); + let fixed = |key: &str, one: &str, many: &str| Reason { key: key.into(), one: one.into(), many: many.into() }; + match (kind, folder) { + (Some(Errno::NOSPC | Errno::DQUOT), Some(f)) => { + let short = format!("There isn't enough space in {}", quoted(f)); + // Asking a share costs a round trip that can hang. + let free = if space::is_remote(f) { None } else { space::free(f) }; + let text = match free { + Some(free) => format!("{short}, which has {} free", size(free)), + None => short, + }; + Reason { key: format!("no space {}", f.display()), one: text.clone(), many: text } + } + (Some(Errno::ACCESS | Errno::PERM), Some(f)) => Reason::same(format!("You don't have permission to change {}", quoted(f))), + (Some(Errno::ACCESS | Errno::PERM), None) => fixed("read permission", "You don't have permission to read it", "You don't have permission to read them"), + (Some(Errno::ROFS), Some(f)) => Reason::same(format!("{} is on a read-only drive", quoted(f))), + (Some(Errno::NAMETOOLONG), Some(f)) => Reason { key: format!("too long {}", f.display()), one: format!("The name is too long for {}", quoted(f)), many: format!("The names are too long for {}", quoted(f)) }, + (Some(Errno::IO), _) => Reason { + key: "io".into(), + one: "The drive couldn't read or write it. It may be failing or have been unplugged".into(), + many: "The drive couldn't read or write them. It may be failing or have been unplugged".into(), + }, + // The folder being written in has gone. + (Some(Errno::NOENT), Some(f)) if matches!(side, Side::Write(_)) => Reason::same(format!("{} is no longer there", quoted(f))), + (Some(Errno::NOENT), _) => fixed("gone", "It's no longer there", "They're no longer there"), + _ => Reason::same(describe(e)), + } +} + +/// Whether an error means the destination has no room left, on the disk or in the user's quota. +fn is_full(e: &io::Error) -> bool { + matches!(e.raw_os_error().map(Errno::from_raw_os_error), Some(Errno::NOSPC | Errno::DQUOT)) +} + +/// `20000` as `20,000`. +fn thousands(n: usize) -> String { + let digits = n.to_string(); + let mut out = String::with_capacity(digits.len() + digits.len() / 3); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + out +} + +/// How many of a group's paths are kept to tell, however many failed. +const NAMED: usize = 5; + +/// Failures with one reason, told together when the job ends. Only the first few paths are +/// kept, so a job where every file fails holds a count, not a list of them all. +struct Group { + one: String, + many: String, + paths: Vec, + count: usize, + folders: bool, +} + +/// What a job has failed at so far, by reason, in the order each reason first came up. +#[derive(Default)] +struct Failures { + groups: Vec, + by_key: std::collections::HashMap, +} + +impl Failures { + fn add(&mut self, path: &Path, reason: Reason) { + let i = match self.by_key.get(&reason.key) { + Some(&i) => i, + None => { + self.by_key.insert(reason.key.clone(), self.groups.len()); + self.groups.push(Group { one: reason.one.clone(), many: String::new(), paths: Vec::new(), count: 0, folders: false }); + self.groups.len() - 1 + } + }; + let g = &mut self.groups[i]; + g.count += 1; + // The newest words, as how much space is free changes as a job goes on. + g.many = reason.many; + if g.paths.len() < NAMED { + g.folders |= fs::symlink_metadata(path).is_ok_and(|m| m.is_dir()); + g.paths.push(path.to_path_buf()); + } + } + + /// One message for each reason. A reason only one item had keeps the item's name first; + /// several items with the same reason are counted instead of named, and the first few + /// of them go with the message. + fn told(self) -> Vec { + self.groups + .into_iter() + .map(|g| { + if g.count == 1 { + return Told { path: g.paths[0].clone(), message: g.one, paths: g.paths, count: 1 }; + } + let noun = if g.folders { "items" } else { "files" }; + Told { path: PathBuf::new(), message: format!("{} {noun}: {}", thousands(g.count), g.many), paths: g.paths, count: g.count } + }) + .collect() + } +} + +/// One message about a job's failures. See [`Event::Error`]. +#[derive(Debug, PartialEq)] +struct Told { + path: PathBuf, + message: String, + paths: Vec, + count: usize, +} + +/// A top-level item placed by a copy or move, noted once the job settles. +struct Top { + src: PathBuf, + target: Option, + merged: bool, + replaced: Option, +} + +/// What a copy or move made, so a full destination can take it away again. +enum Made { + /// A file, link or folder that wasn't there before. A folder is taken away with + /// everything in it, which this job put there. + Item(PathBuf), + /// What a Replace moved to the Trash, to put back. + Replaced(Trashed), +} + +/// What a source was when it was copied, to tell whether it has changed since. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Seen { + ino: u64, + len: u64, + mtime: (i64, i64), + /// 0 where the filesystem doesn't say. + ctime: (i64, i64), +} + +/// How a filesystem's files can be told apart over time. See [`Seen::unchanged`]. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Care { + /// A local disk with fine times: the inode, size and time say. + Strict, + /// A local disk with coarse times (vfat, exFAT and msdos keep 2 s, ext3 1 s), where a + /// change soon after a look can leave the time the same. + Coarse, + /// A share whose inode numbers change between looks, and whose times come from another + /// machine's clock. + Loose, +} + +/// How far around the reference time a file's time is taken as too close to tell. Wide +/// enough for coarse clocks and for a server's clock a little off from this one's. +const WINDOW: i64 = 10; + +impl Seen { + fn of(m: &Metadata) -> Seen { + Seen { ino: m.ino(), len: m.len(), mtime: (m.mtime(), m.mtime_nsec()), ctime: (m.ctime(), m.ctime_nsec()) } + } + + /// Whether `now` is still the file as it was. `reference` is when it was looked at before + /// copying, or the job's start if earlier, in seconds since the epoch. + /// + /// On a local disk with fine times the inode, size and time say. Where the times are coarse, + /// or on a share, a change soon after the look can leave the times as they were, so the + /// change time is compared too where the filesystem keeps one, and a file whose time is + /// at or after 10 s before the reference is taken as changed, which keeps the original. + /// That also covers a server whose clock runs ahead of this one. A share's inode numbers + /// can change between looks, so there they aren't compared. + /// + /// The limit: a server whose clock is more than 10 s behind can stamp a change made during + /// the job with a time before the window, and then only the size and change time can tell. + fn unchanged(&self, now: &Seen, care: Care, reference: i64) -> bool { + let same_times = self.len == now.len && self.mtime == now.mtime; + if care == Care::Strict { + return self.ino == now.ino && same_times; + } + let ctime_same = self.ctime == (0, 0) || now.ctime == (0, 0) || self.ctime == now.ctime; + let recent = now.mtime.0 >= reference - WINDOW; + let ino_same = care == Care::Loose || self.ino == now.ino; + ino_same && same_times && ctime_same && !recent + } +} + +/// How the files on the filesystem `path` is on, as the mount table has it, can be told apart. +/// See [`crate::mounts::inodes_renumbered`]. +fn care_in(all: &[crate::mounts::Mount], path: &Path) -> Care { + let point = crate::mounts::mount_point_of(all, path); + match all.iter().rev().find(|m| Some(&m.point) == point.as_ref()).map(|m| m.fs_type.as_str()) { + Some(t) if crate::mounts::inodes_renumbered(t) => Care::Loose, + Some("vfat" | "exfat" | "msdos" | "ext3") => Care::Coarse, + _ => Care::Strict, + } +} + +/// A source a move across disks has copied, removed once everything has been. +enum Moved { + /// With what it was before it was copied, and the reference time for that (see + /// [`Seen::unchanged`]), so a file changed since is kept. + File { src: PathBuf, was: Seen, reference: i64, care: Care }, + /// Removed once empty. `clean` if nothing in it failed or was left on purpose. + Folder { src: PathBuf, clean: bool }, +} + struct Run { job: Job, sink: Sink, @@ -509,6 +799,11 @@ struct Run { /// once: Keep going covers the rest of the job's archives too. asked_expands: bool, errors: usize, + /// What went wrong, told when the job ends. See [`Failures`]. + failures: Failures, + tell_each: bool, + /// Said instead of "Stopped" when a cancelled move was taken back. + stopped: Option, /// Items left in place on purpose, so a folder that won't empty isn't a surprise. noted_leftovers: usize, /// Whether `scan` met anything other users can't read. @@ -523,6 +818,34 @@ struct Run { /// a hard link of the same file can be what it replaces. last_replaced: Option, top_dev: u64, + /// What the scanned files will take on a disk. + need: u64, + /// Sources scanned before a move, so they aren't again when the move turns out to cross disks. + measured: std::collections::HashSet, + /// The destination filled up, so the copy or move stops and is undone. + full: bool, + /// What this copy or move made, outside the folders it made. See [`Made`]. + made: Vec, + /// Inside a folder this job made, whose contents go with it. + inside_new: bool, + /// What a move across disks has copied, for removing once it all has. + to_delete: Vec, + /// Top-level items this move renamed on their own disk, which a full disk or a stop doesn't + /// take back. + renamed: usize, + /// Whether the top-level item being moved, `moving_top`, is on a share whose inode numbers + /// can change. See [`Seen::unchanged`]. + care: Option, + /// When the item being placed was last looked at, before it's copied. + looked_at: std::time::SystemTime, + moving_top: Option, + /// When the job started, as the clock has it, for telling a source changed during it. + started: std::time::SystemTime, + /// The mount table, read once a move needs it. + mount_table: Option>, + /// A stop came once every copy had arrived, so the move was finished. + finished_anyway: bool, + skip_space_check: bool, /// What this job changed, for its undo. steps: Vec, /// Everything this job moved to the Trash, to save to disk at the end. @@ -542,12 +865,21 @@ impl Run { fn execute(&mut self, request: Request) { match request { Request::Copy { sources, dest } => { - self.scan(&sources); - self.place_all(&sources, &dest, Mode::Copy); + let (need, away) = self.measure(&sources, &dest, Mode::Copy); + if self.room_for(&away, &dest, need) { + self.place_all(&sources, &dest, Mode::Copy); + } } Request::Move { sources, dest } => { self.job.progress.total_items.store(sources.len() as u64, Ordering::Relaxed); - self.place_all(&sources, &dest, Mode::Move); + // What goes to another disk is copied, so it's measured first, as a copy is. + let dest_dev = fs::metadata(&dest).map(|m| m.dev()).ok(); + let copied: Vec = sources.iter().filter(|s| self.force_exdev || fs::symlink_metadata(s).is_ok_and(|m| Some(m.dev()) != dest_dev)).cloned().collect(); + let (need, away) = self.measure(&copied, &dest, Mode::Move); + self.measured = copied.into_iter().collect(); + if self.room_for(&away, &dest, need) { + self.place_all(&sources, &dest, Mode::Move); + } } Request::Link { sources, dest } => { self.job.progress.total_items.store(sources.len() as u64, Ordering::Relaxed); @@ -555,7 +887,7 @@ impl Run { } Request::Trash { paths } => self.trash_all(paths), Request::Delete { paths } => { - self.scan(&paths); + self.scan(&paths, true); for p in &paths { if self.job.is_cancelled() { break; @@ -645,7 +977,7 @@ impl Run { let Some(parent) = archive.parent() else { return }; let file = match File::open(archive) { Ok(f) => f, - Err(e) => return self.fail(archive, &e), + Err(e) => return self.fail_as(archive, &e, Side::Read), }; let tmp = temp_name(archive); if let Err(e) = fs::create_dir(&tmp) { @@ -755,7 +1087,7 @@ impl Run { let Some(place) = zip_place(&items).map(|p| through_links(p, &items)) else { return }; self.touched.push(place.folder.clone()); let full: Vec = place.names.iter().map(|n| place.folder.join(n)).collect(); - self.scan(&full); + self.scan(&full, false); if self.job.is_cancelled() { return; } @@ -1101,7 +1433,9 @@ impl Run { Step::Moved { from, to } => { self.last_target = None; let flow = self.place(&to.path, from.clone(), Mode::Move); - self.record_top_level(&to.path, Mode::Move); + let top = self.top(&to.path); + let back_in = from.parent().unwrap_or(&from).to_path_buf(); + self.settle(vec![top], std::slice::from_ref(&to.path), &back_in, Mode::Move); self.touch_parent(&from); self.touch_parent(&to.path); return flow; @@ -1161,12 +1495,45 @@ impl Run { } fn fail(&mut self, path: &Path, e: &io::Error) { - self.report(path, describe(e)); + self.fail_as(path, e, Side::Change); } + fn fail_as(&mut self, path: &Path, e: &io::Error, side: Side) { + let r = reason(e, path, side); + self.note_failure(path, r); + } + + /// Notes a failure, told when the job ends. An empty path is a message about no one item. fn report(&mut self, path: &Path, message: String) { + self.note_failure(path, Reason::same(message)); + } + + fn note_failure(&mut self, path: &Path, reason: Reason) { self.errors += 1; - (self.sink)(Event::Error { job: self.job.id, path: path.to_path_buf(), message }); + if self.tell_each { + (self.sink)(Event::Error { job: self.job.id, path: path.to_path_buf(), message: reason.one, paths: vec![path.to_path_buf()], count: 1 }); + } else { + self.failures.add(path, reason); + } + } + + /// Tells the job's failures, one message for each reason, so a folder of files that all + /// failed the same way gives one notice and one announcement, not one for each file. + fn tell_failures(&mut self) { + for t in std::mem::take(&mut self.failures).told() { + (self.sink)(Event::Error { job: self.job.id, path: t.path, message: t.message, paths: t.paths, count: t.count }); + } + } + + /// A copy failed. A full destination stops the whole job, which is then undone, and says + /// so once; anything else is reported and the job goes on. + fn copy_failed(&mut self, item: &Path, e: &io::Error, side: Side) -> Flow { + if is_full(e) { + self.full = true; + return Flow::Stop; + } + self.fail_as(item, e, side); + Flow::Go } fn tick(&mut self) { @@ -1182,26 +1549,84 @@ impl Run { } } + /// Scans the sources for progress, and says which are on another device than `dest` and + /// what they take: the blocks allocated to them on their own disk, so a sparse file counts + /// only what it holds. Sources on the same device as `dest` aren't counted. A copy there + /// shares blocks only on a filesystem with reflinks, but a disk that fills is caught as the + /// copy goes, and the copy is taken back. + fn measure(&mut self, sources: &[PathBuf], dest: &Path, mode: Mode) -> (u64, Vec) { + let dest_dev = fs::metadata(dest).map(|m| m.dev()).ok(); + let mut need = 0; + let mut away = Vec::new(); + for src in sources { + let before = self.need; + // A move leaves a disk mounted inside a folder where it is, so it isn't counted. + self.scan(std::slice::from_ref(src), mode == Mode::Move); + if fs::symlink_metadata(src).is_ok_and(|m| Some(m.dev()) != dest_dev) { + need += self.need - before; + away.push(src.clone()); + } + } + (need, away) + } + + /// Whether `dest` has room for `away`, the sources from other devices, which take `need`. + /// If clearly not, says so and nothing starts. Anything that makes the need unclear skips + /// the check, and a disk that fills anyway is caught as the copy goes: + /// - something with a source's name is already in `dest`, to be merged into or asked about; + /// - `dest` is on a network share or FUSE, where asking costs a round trip; + /// - `dest` is on btrfs, zfs or bcachefs, which can compress, share blocks with other + /// subvolumes of one pool, or dedupe. See [`space::worth_checking`]. + fn room_for(&mut self, away: &[PathBuf], dest: &Path, need: u64) -> bool { + if need == 0 || self.skip_space_check || self.job.is_cancelled() { + return true; + } + // In this order, so nothing on a share is looked up. + if !space::worth_checking(dest) || away.iter().any(|s| s.file_name().is_some_and(|n| fs::symlink_metadata(dest.join(n)).is_ok())) { + return true; + } + let Some(free) = space::free(dest) else { return true }; + if need <= free { + return true; + } + let what = match away { + [one] => format!("{} needs", quoted(one)), + many => format!("These {} items need", thousands(many.len())), + }; + self.report(Path::new(""), format!("{what} {}, but {} only has {} free", size(need), quoted(dest), size(free))); + false + } + /// Adds up the bytes and items so progress has totals. - fn scan(&mut self, paths: &[PathBuf]) { + /// With `stop_at_mounts`, as for a move or a delete, which leave another disk mounted inside + /// a folder alone, what's on it isn't counted either. + fn scan(&mut self, paths: &[PathBuf], stop_at_mounts: bool) { let progress = self.job.progress.clone(); progress.scanning.store(true, Ordering::Relaxed); - let mut stack: Vec = paths.to_vec(); - while let Some(p) = stack.pop() { + // Each with the device of the item it's inside, given, or None for one given. + let mut stack: Vec<(PathBuf, Option)> = paths.iter().map(|p| (p.clone(), None)).collect(); + while let Some((p, top)) = stack.pop() { if self.job.is_cancelled() { break; } let Ok(m) = fs::symlink_metadata(&p) else { continue }; + let top = top.unwrap_or(m.dev()); + if stop_at_mounts && m.is_dir() && is_mount_boundary(&p, &m, top) { + continue; + } progress.total_items.fetch_add(1, Ordering::Relaxed); // A folder others can see into but not enter keeps what's in it from them too. let open_to_others = if m.is_dir() { 0o005 } else { 0o004 }; self.private_seen |= !m.is_symlink() && m.mode() & open_to_others != open_to_others; if m.is_dir() { if let Ok(rd) = fs::read_dir(&p) { - stack.extend(rd.flatten().map(|e| e.path())); + stack.extend(rd.flatten().map(|e| (e.path(), Some(top)))); } } else { progress.total_bytes.fetch_add(m.len(), Ordering::Relaxed); + // Allocated blocks count only what a sparse file holds, and the size rounded up + // to whole blocks leaves out space a file has reserved but not used. + self.need += (m.blocks() * 512).min(m.len().div_ceil(4096) * 4096); } self.tick(); } @@ -1270,9 +1695,10 @@ impl Run { } fn place_all(&mut self, sources: &[PathBuf], dest: &Path, mode: Mode) { + let mut tops = Vec::with_capacity(sources.len()); for src in sources { if self.job.is_cancelled() { - return; + break; } let Some(name) = src.file_name() else { self.report(src, "This can't be copied or moved".into()); @@ -1285,7 +1711,7 @@ impl Run { let target = dest.join(name); self.last_target = None; let flow = self.place(src, target, mode); - self.record_top_level(src, mode); + tops.push(self.top(src)); if mode == Mode::Move { self.touch_parent(src); self.job.progress.done_items.fetch_add(1, Ordering::Relaxed); @@ -1295,26 +1721,156 @@ impl Run { } self.tick(); if let Flow::Stop = flow { - return; + break; + } + } + self.settle(tops, sources, dest, mode); + } + + /// How files where `src` is can be told apart. Its folder is resolved for the mount table; + /// the item itself isn't followed. + fn care_at(&mut self, src: &Path) -> Care { + let real = src.parent().and_then(|d| fs::canonicalize(d).ok()).map(|d| src.file_name().map_or(d.clone(), |n| d.join(n))); + let table = self.mount_table.get_or_insert_with(crate::mounts::read_mounts); + real.map_or(Care::Strict, |r| care_in(table, &r)) + } + + /// What `place` noted about the top-level item it just placed. + fn top(&mut self, src: &Path) -> Top { + Top { src: src.to_path_buf(), target: self.last_target.take(), merged: std::mem::take(&mut self.last_merged), replaced: self.last_replaced.take() } + } + + /// Ends a copy or move. If the destination filled up, everything the job made is taken away + /// and the sources are left as they were. If not, the sources of what was copied to another + /// disk are removed, now that all of it is there. + fn settle(&mut self, tops: Vec, sources: &[PathBuf], dest: &Path, mode: Mode) { + let full = std::mem::take(&mut self.full); + // A move stopped partway across disks is taken back too, so nothing is half moved: + // no original goes until all of it has arrived. + // Only copies are taken back: what was renamed on its own disk is where it was asked to go. + let copied = !self.made.is_empty() || self.to_delete.iter().any(|m| matches!(m, Moved::File { .. })); + let cancelled_before = self.job.is_cancelled(); + let stopped = mode == Mode::Move && cancelled_before && copied; + if !full && !stopped { + self.made.clear(); + self.delete_moved(); + // A stop that came while the originals were being removed is too late: every copy + // had arrived, so the move is finished rather than left half done. + self.finished_anyway = !cancelled_before && self.job.is_cancelled(); + self.renamed = 0; + for top in tops { + self.record_top_level(top, mode); + } + return; + } + self.undo_made(); + self.to_delete.clear(); + // Renamed on the same disk, so they took no room. They keep their undo and are selected. + for top in tops { + if mode == Mode::Move && (is_gone(&top.src) || top.merged) { + self.record_top_level(top, mode); + } + } + let moved = std::mem::take(&mut self.renamed); + let what = match sources { + [one] => quoted(one), + many => format!("{} items", thousands(many.len())), + }; + let (verb, done) = if mode == Mode::Copy { ("copy", "copied") } else { ("move", "moved") }; + let rest = match moved { + 0 => format!("Nothing was {done}"), + 1 => format!("1 on the same drive was {done}, and the rest were left where they were"), + n => format!("{} on the same drive were {done}, and the rest were left where they were", thousands(n)), + }; + if full { + self.report(Path::new(""), format!("Couldn't {verb} {what}: there isn't enough space in {}. {rest}", quoted(dest))); + } else { + self.stopped = Some(format!("Stopped moving {what}. {rest}")); + } + } + + /// Takes away what this copy or move made, newest first, and puts back what it replaced. + fn undo_made(&mut self) { + for m in std::mem::take(&mut self.made).into_iter().rev() { + match m { + Made::Item(p) => { + remove_partial(&p); + self.touch_parent(&p); + } + Made::Replaced(t) => { + self.steps.retain(|s| !matches!(s, Step::Trashed { item, .. } if *item == t)); + self.trashed.retain(|x| *x != t); + self.touch_parent(&t.original); + self.put_back(t); + } + } + } + } + + /// Removes the sources a move across disks copied, in the order they were noted: each + /// folder after everything in it, so it's empty by the time it's reached. A file that changed + /// since it was copied stays, as does anything that couldn't be checked or removed, and the + /// folders holding them. + fn delete_moved(&mut self) { + let mut kept: Vec = Vec::new(); + let pending = std::mem::take(&mut self.to_delete); + // Removing them is part of the move, so the bar goes on until they're gone. + let progress = self.job.progress.clone(); + progress.total_items.fetch_add(pending.len() as u64, Ordering::Relaxed); + for m in pending { + progress.done_items.fetch_add(1, Ordering::Relaxed); + self.tick(); + match m { + Moved::File { src, was, reference, care } => match fs::symlink_metadata(&src) { + Ok(now) if was.unchanged(&Seen::of(&now), care, reference) => { + if let Err(e) = fs::remove_file(&src) { + self.fail(&src, &e); + kept.push(src); + } + } + Ok(_) => { + self.report(&src, "This changed while it was being moved, so the original was kept as well".into()); + kept.push(src); + } + // Gone already, which is what was wanted. + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => { + self.fail_as(&src, &e, Side::Read); + kept.push(src); + } + }, + Moved::Folder { src, clean } => match fs::remove_dir(&src) { + Ok(()) => {} + // Expected if something in it stayed. If not, something new appeared while + // the move went on, and that deserves a mention. + Err(e) if e.raw_os_error() == Some(Errno::NOTEMPTY.raw_os_error()) => { + if clean && !kept.iter().any(|k| k.starts_with(&src)) { + self.report(&src, "Something new appeared here during the move, so the folder was kept".into()); + } + kept.push(src); + } + Err(e) => { + self.fail(&src, &e); + kept.push(src); + } + }, } } } /// Notes where a top-level item ended up. Only top-level items are steps and things to /// select: undoing a folder's move or copy takes its contents with it. - fn record_top_level(&mut self, src: &Path, mode: Mode) { - let merged = std::mem::take(&mut self.last_merged); - let replaced = self.last_replaced.take(); - let Some(target) = self.last_target.take() else { return }; + fn record_top_level(&mut self, top: Top, mode: Mode) { + let Some(target) = top.target else { return }; let Some(stamp) = Stamp::of(&target) else { return }; - if replaced == Some(false) { + if top.replaced == Some(false) { return; } // Undoing a merge would also take what was in the destination before, so it has no undo. - if !merged { + if !top.merged { match mode { // A move that left its source behind went only partway, and isn't undone as a whole. - Mode::Move if fs::symlink_metadata(src).is_err() => self.steps.push(Step::Moved { from: src.to_path_buf(), to: stamp }), + Mode::Move if is_gone(&top.src) => self.steps.push(Step::Moved { from: top.src, to: stamp }), Mode::Move => {} Mode::Copy => self.steps.push(Step::Made(stamp)), } @@ -1328,15 +1884,22 @@ impl Run { return Flow::Stop; } self.set_current(src); + // Taken before the look, so a change right after it falls inside the window. + self.looked_at = std::time::SystemTime::now(); let smeta = match fs::symlink_metadata(src) { Ok(m) => m, Err(e) => { - self.fail(src, &e); + self.fail_as(src, &e, Side::Read); return Flow::Go; } }; if self.depth == 0 { self.top_dev = smeta.dev(); + if mode == Mode::Move { + // Worked out only once something of it is copied: a rename doesn't need it. + self.care = None; + self.moving_top = Some(src.to_path_buf()); + } } else if mode == Mode::Move && smeta.is_dir() && is_mount_boundary(src, &smeta, self.top_dev) { self.report(src, "This is a mount point, so it was left where it is".into()); return Flow::Go; @@ -1401,6 +1964,7 @@ impl Run { if let Some(t) = old { self.kept_replaced(t); } + self.renamed += usize::from(self.depth == 0); self.job.progress.done_bytes.fetch_add(if smeta.is_dir() { 0 } else { smeta.len() }, Ordering::Relaxed); return Flow::Go; } @@ -1411,26 +1975,33 @@ impl Run { } // Across disks: copy then remove, measuring what's about to move. The // top item's scan covers everything below it. - if self.depth == 0 { - self.scan(&[src.to_path_buf()]); + if self.depth == 0 && !self.measured.contains(src) { + self.scan(&[src.to_path_buf()], true); } } Err(e) => { if let Some(t) = old { self.put_back(t); } - self.fail(src, &e); + let into = parent_of(&target); + // Renaming can need room for the name, which is the destination's. + if is_full(&e) { + return self.copy_failed(src, &e, Side::Write(into)); + } + // A move changes both folders, so name the one it can't write in. + let side = if rustix::fs::access(into, rustix::fs::Access::WRITE_OK).is_err() { Side::Write(into) } else { Side::Change }; + self.fail_as(src, &e, side); return Flow::Go; } } - } else if mode == Mode::Move && !merge && self.depth == 0 { - self.scan(&[src.to_path_buf()]); + } else if mode == Mode::Move && !merge && self.depth == 0 && !self.measured.contains(src) { + self.scan(&[src.to_path_buf()], true); } let ft = smeta.file_type(); if ft.is_dir() { self.copy_dir(src, &target, &smeta, mode, merge) } else if ft.is_symlink() { - self.copy_symlink(src, &target, replace, mode) + self.copy_symlink(src, &target, &smeta, replace, mode) } else if ft.is_file() { self.copy_file(src, &target, &smeta, replace, mode) } else { @@ -1523,119 +2094,142 @@ impl Run { let mut b = fs::DirBuilder::new(); b.mode(smeta.permissions().mode() & 0o7777 | 0o700); if let Err(e) = b.create(target) { - self.fail(target, &e); - return Flow::Go; + return self.copy_failed(target, &e, Side::Write(parent_of(target))); } created = true; + if !self.inside_new { + self.made.push(Made::Item(target.to_path_buf())); + } } let entries = match fs::read_dir(src) { Ok(rd) => rd, Err(e) => { - self.fail(src, &e); + self.fail_as(src, &e, Side::Read); // Nothing went in, and an empty folder would look like a successful copy. if created { let _ = fs::remove_dir(target); + if !self.inside_new { + self.made.pop(); + } } return Flow::Go; } }; let leftovers_before = self.errors + self.noted_leftovers; + // What goes in a folder this job made goes with it, so it needn't be noted one by one. + let outer = self.inside_new; + self.inside_new |= created; + let mut flow = Flow::Go; for e in entries { let e = match e { Ok(e) => e, Err(err) => { - self.fail(src, &err); + self.fail_as(src, &err, Side::Read); continue; } }; self.depth += 1; - let flow = self.place(&e.path(), target.join(e.file_name()), mode); + flow = self.place(&e.path(), target.join(e.file_name()), mode); self.depth -= 1; if let Flow::Stop = flow { - if created { - finish_folder(target, smeta); - } - return Flow::Stop; + break; } } + self.inside_new = outer; if created { finish_folder(target, smeta); } + if let Flow::Stop = flow { + return Flow::Stop; + } if mode == Mode::Move { - // Fails only if something stayed behind (skipped or errored). That's right: it stays. - match fs::remove_dir(src) { - Ok(()) => {} - // Expected if something below was skipped or failed. If not, something - // new appeared while we worked, and that deserves a mention. - Err(e) if e.raw_os_error() == Some(Errno::NOTEMPTY.raw_os_error()) => { - if self.errors + self.noted_leftovers == leftovers_before { - self.report(src, "Something new appeared here during the move, so the folder was kept".into()); - } - } - Err(e) => self.fail(src, &e), - } + // Removed once the whole move has been copied. It stays if anything in it was + // skipped or failed, which is right. + self.to_delete.push(Moved::Folder { src: src.to_path_buf(), clean: self.errors + self.noted_leftovers == leftovers_before }); } self.job.progress.done_items.fetch_add(u64::from(mode == Mode::Copy), Ordering::Relaxed); self.tick(); Flow::Go } - fn copy_symlink(&mut self, src: &Path, target: &Path, replace: bool, mode: Mode) -> Flow { + fn copy_symlink(&mut self, src: &Path, target: &Path, smeta: &Metadata, replace: bool, mode: Mode) -> Flow { + let points_to = match fs::read_link(src) { + Ok(p) => p, + Err(e) => { + self.fail_as(src, &e, Side::Read); + return Flow::Go; + } + }; let tmp = temp_name(target); - if let Err(e) = fs::read_link(src).and_then(|dest| std::os::unix::fs::symlink(&dest, &tmp)) { - self.fail(target, &e); - return Flow::Go; + if let Err(e) = std::os::unix::fs::symlink(&points_to, &tmp) { + return self.copy_failed(target, &e, Side::Write(parent_of(target))); } - self.put_in_place(src, &tmp, target, replace, mode); - Flow::Go + self.put_in_place(src, &tmp, target, smeta, replace, mode) } /// Renames a finished copy at `tmp` to `target`, first moving what's there to the Trash /// if it replaces it. Whatever goes wrong, the copy is removed and the rest is left as it was. - fn put_in_place(&mut self, src: &Path, tmp: &Path, target: &Path, replace: bool, mode: Mode) { + fn put_in_place(&mut self, src: &Path, tmp: &Path, target: &Path, smeta: &Metadata, replace: bool, mode: Mode) -> Flow { let old = match replace { true => match self.trash_replaced(src, target) { Some(t) => Some(t), None => { let _ = fs::remove_file(tmp); - return; + return Flow::Go; } }, false => None, }; match rename_noreplace(tmp, target) { Ok(()) => { + // Noted before the copy, so undoing them puts the copy away first. if let Some(t) = old { + self.made.push(Made::Replaced(t.clone())); self.kept_replaced(t); } - self.finish_item(src, target, mode); + if !self.inside_new { + self.made.push(Made::Item(target.to_path_buf())); + } + self.finish_item(src, target, smeta, mode) } Err(e) => { let _ = fs::remove_file(tmp); if let Some(t) = old { self.put_back(t); } - self.fail(target, &e); + self.copy_failed(target, &e, Side::Write(parent_of(target))) } } } /// Bookkeeping once something is fully in place. - fn finish_item(&mut self, src: &Path, target: &Path, mode: Mode) { + fn finish_item(&mut self, src: &Path, target: &Path, smeta: &Metadata, mode: Mode) -> Flow { if mode == Mode::Move { // The name must be on disk too before the only other copy goes away. let synced = target.parent().map_or(Ok(()), |p| File::open(p).and_then(|d| self.sync_for_move(&d))); if let Err(e) = synced { + if is_full(&e) { + self.full = true; + return Flow::Stop; + } self.report(src, format!("Copied, but couldn't confirm it reached the disk, so the original stays: {}", describe(&e))); - return; - } - if let Err(e) = fs::remove_file(src) { - self.fail(src, &e); + return Flow::Go; } + let care = match self.care { + Some(c) => c, + None => { + let c = self.moving_top.clone().map_or(Care::Strict, |top| self.care_at(&top)); + self.care = Some(c); + c + } + }; + let reference = reference_time(self.looked_at, self.started); + self.to_delete.push(Moved::File { src: src.to_path_buf(), was: Seen::of(smeta), reference, care }); } else { self.job.progress.done_items.fetch_add(1, Ordering::Relaxed); } self.tick(); + Flow::Go } fn copy_file(&mut self, src: &Path, target: &Path, smeta: &Metadata, replace: bool, mode: Mode) -> Flow { @@ -1646,20 +2240,24 @@ impl Run { let _ = fs::remove_file(&tmp); return Flow::Stop; } - Err(e) => { + Err((e, end)) => { + // The part copied so far goes too, full destination or not. let _ = fs::remove_file(&tmp); - self.fail(src, &e); - return Flow::Go; + let side = match end { + End::Source => Side::Read, + End::Copy => Side::Write(parent_of(target)), + }; + return self.copy_failed(src, &e, side); } } - self.put_in_place(src, &tmp, target, replace, mode); - Flow::Go + self.put_in_place(src, &tmp, target, smeta, replace, mode) } - /// Copies bytes and metadata to `tmp`. `Ok(false)` means cancelled. - fn copy_contents(&mut self, src: &Path, tmp: &Path, smeta: &Metadata, mode: Mode) -> io::Result { - let input = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(src)?; - let output = OpenOptions::new().write(true).create_new(true).mode(0o600).open(tmp)?; + /// Copies bytes and metadata to `tmp`. `Ok(false)` means cancelled. An error says which + /// file it came from. + fn copy_contents(&mut self, src: &Path, tmp: &Path, smeta: &Metadata, mode: Mode) -> Result { + let input = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(src).map_err(|e| (e, End::Source))?; + let output = OpenOptions::new().write(true).create_new(true).mode(0o600).open(tmp).map_err(|e| (e, End::Copy))?; let mut copied = 0u64; let mut fallback = false; const CHUNK: usize = 8 * 1024 * 1024; @@ -1683,7 +2281,7 @@ impl Run { break; } Err(Errno::INTR) => continue, - Err(e) => return Err(e.into()), + Err(e) => return Err((e.into(), End::Copy)), } } // Some pseudo filesystems report no bytes from copy_file_range but have data. @@ -1694,7 +2292,8 @@ impl Run { progress.done_bytes.fetch_add(n, Ordering::Relaxed); self.tick(); !self.job.is_cancelled() - })?; + }) + .map_err(|e| (e, End::Copy))?; match sent { Sent::Cancelled => return Ok(false), Sent::Complete(n) => { @@ -1715,12 +2314,12 @@ impl Run { let n = match input.read(&mut buf) { Ok(n) => n, Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, - Err(e) => return Err(e), + Err(e) => return Err((e, End::Source)), }; if n == 0 { break; } - out.write_all(&buf[..n])?; + out.write_all(&buf[..n]).map_err(|e| (e, End::Copy))?; copied += n as u64; progress.done_bytes.fetch_add(n as u64, Ordering::Relaxed); self.tick(); @@ -1728,20 +2327,20 @@ impl Run { } } if copied < smeta.len() { - return Err(io::Error::other("The file got shorter while it was being copied")); + return Err((io::Error::other("The file got shorter while it was being copied"), End::Source)); } copy_xattrs(&input, &output); // Setuid and setgid are dropped: the copy belongs to whoever made it. Some // filesystems (FAT, some FUSE) refuse chmod, and that's no reason to fail. match output.set_permissions(fs::Permissions::from_mode(smeta.permissions().mode() & 0o777)) { - Err(e) if !matches!(e.raw_os_error().map(Errno::from_raw_os_error), Some(Errno::PERM | Errno::OPNOTSUPP)) => return Err(e), + Err(e) if !matches!(e.raw_os_error().map(Errno::from_raw_os_error), Some(Errno::PERM | Errno::OPNOTSUPP)) => return Err((e, End::Copy)), _ => {} } let _ = set_mtime(&output, smeta); if mode == Mode::Move { - self.sync_for_move(&output)?; + self.sync_for_move(&output).map_err(|e| (e, End::Copy))?; } - close_checked(output)?; + close_checked(output).map_err(|e| (e, End::Copy))?; Ok(true) } @@ -1760,7 +2359,7 @@ impl Run { let meta = match fs::symlink_metadata(path) { Ok(m) => m, Err(e) => { - self.fail(path, &e); + self.fail_as(path, &e, Side::Read); return; } }; @@ -1775,12 +2374,12 @@ impl Run { for e in rd { match e { Ok(e) => self.delete_tree(&e.path()), - Err(err) => self.fail(path, &err), + Err(err) => self.fail_as(path, &err, Side::Read), } } } Err(e) => { - self.fail(path, &e); + self.fail_as(path, &e, Side::Read); return; } } @@ -1806,6 +2405,28 @@ impl Run { } } +/// The time a source's later look is compared against: when it was looked at before being +/// copied, or the job's start if that's earlier. See [`Seen::unchanged`]. +fn reference_time(looked_at: std::time::SystemTime, started: std::time::SystemTime) -> i64 { + epoch_secs(looked_at.min(started)) +} + +/// Seconds since the epoch, as file times are kept. +fn epoch_secs(t: std::time::SystemTime) -> i64 { + t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64) +} + +/// Whether nothing is at `path` now. An error other than "not found", as from a folder that +/// can't be read, doesn't say it's gone. +fn is_gone(path: &Path) -> bool { + matches!(fs::symlink_metadata(path), Err(e) if e.kind() == io::ErrorKind::NotFound) +} + +/// The folder `path` is in, for saying where something couldn't be written. +fn parent_of(path: &Path) -> &Path { + path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(path) +} + /// True if `path`, a folder below a top-level item on device `top_dev`, is a mount point. /// The device check catches ordinary mounts and the attribute catches bind mounts. fn is_mount_boundary(path: &Path, m: &Metadata, top_dev: u64) -> bool { @@ -1920,8 +2541,8 @@ fn only_folder(dir: &Path) -> Option { Some(one.file_name()) } -/// Removes what a failed or cancelled extract left, whatever the job's cancel says. It never -/// follows a link, and stays on the disk it started on. +/// Removes what a failed or cancelled extract left, or a copy that filled its destination, +/// whatever the job's cancel says. It never follows a link, and stays on the disk it started on. fn remove_partial(path: &Path) { fn go(path: &Path, dev: u64) { let Ok(m) = fs::symlink_metadata(path) else { return }; @@ -2140,6 +2761,20 @@ mod tests { } } + /// Waits for the job, answering every conflict, if any come, with Replace for all. + fn finish_replacing(rx: &Receiver) -> Done { + let mut errors = Vec::new(); + loop { + match rx.recv_timeout(Duration::from_secs(20)).expect("job should finish") { + Event::Error { path, message, .. } => errors.push((path, message)), + Event::Conflict(c) => c.reply.send(all(Choice::Replace)).unwrap(), + Event::Expands(q) => panic!("unexpected question about {:?}", q.archive), + Event::Progress(_) => {} + Event::Finished(outcome) => return Done { outcome, errors }, + } + } + } + fn answer(choice: Choice) -> Answer { Answer { choice, apply_to_all: false } } @@ -2373,7 +3008,7 @@ mod tests { let done = finish(&rx, vec![]); fs::set_permissions(&bad, fs::Permissions::from_mode(0o600)).unwrap(); assert_eq!(done.errors.len(), 1, "{:?}", done.errors); - assert!(done.errors[0].1.contains("denied")); + assert_eq!(done.errors[0], (bad.clone(), "You don't have permission to read it".to_string())); assert!(s.path().join("dest/good").exists()); assert!(!s.path().join("dest/bad").exists()); no_partials(&s.path().join("dest")); @@ -3461,8 +4096,9 @@ mod tests { crafted_tar(&links, &[("ln", b"", Some("../..")), ("ln/through.txt", b"bad", None)]); e.start(Request::Extract { archives: vec![evil, links] }); let done = finish(&rx, vec![]); - assert_eq!(done.errors.len(), 2, "{:?}", done.errors); - assert!(done.errors.iter().all(|(_, m)| m.contains("outside its folder")), "{:?}", done.errors); + // Told once for both. + assert_eq!(done.errors, [(PathBuf::new(), "2 files: It holds items that would land outside its folder, so nothing was extracted".to_string())]); + assert_eq!(done.outcome.errors, 2); assert!(done.outcome.created.is_empty() && done.outcome.undo.is_none()); assert!(!s.path().join("escaped.txt").exists() && !s.path().join("through.txt").exists()); assert_eq!(names_in(&work), ["evil.tar", "links.tar"]); @@ -3482,8 +4118,7 @@ mod tests { crafted_tar(&dot, &[("x", b"", Some(".")), ("y", b"", Some("x/.."))]); e.start(Request::Extract { archives: vec![up, absolute, dot] }); let done = finish(&rx, vec![]); - assert_eq!(done.errors.len(), 3, "{:?}", done.errors); - assert!(done.errors.iter().all(|(_, m)| m.contains("outside its folder")), "{:?}", done.errors); + assert_eq!(done.errors, [(PathBuf::new(), "3 files: It holds items that would land outside its folder, so nothing was extracted".to_string())]); assert!(done.outcome.created.is_empty() && done.outcome.undo.is_none()); assert_eq!(names_in(&work), ["absolute.tar", "dot.tar", "up.tar"]); @@ -3509,8 +4144,7 @@ mod tests { crafted_tar(&sib, &[("proj/a.txt", b"a", None), ("proj/sib", b"", Some("../sib"))]); e.start(Request::Extract { archives: vec![up, sib] }); let done = finish(&rx, vec![]); - assert_eq!(done.errors.len(), 2, "{:?}", done.errors); - assert!(done.errors.iter().all(|(_, m)| m.contains("outside its folder")), "{:?}", done.errors); + assert_eq!(done.errors, [(PathBuf::new(), "2 files: It holds items that would land outside its folder, so nothing was extracted".to_string())]); assert_eq!(names_in(&work), ["sib.tar", "up.tar"]); let fine = work.join("fine.tar"); @@ -3616,9 +4250,10 @@ mod tests { e.start(Request::Extract { archives: vec![garbage, truncated, locked] }); let done = finish(&rx, vec![]); let messages: Vec<&str> = done.errors.iter().map(|(_, m)| m.as_str()).collect(); - assert_eq!(messages.len(), 3, "{messages:?}"); - assert!(messages[0].contains("damaged") && messages[1].contains("damaged"), "{messages:?}"); - assert!(messages[2].contains("password"), "{messages:?}"); + // The two damaged ones are told together. + assert_eq!(messages.len(), 2, "{messages:?}"); + assert!(messages[0].starts_with("2 files: ") && messages[0].contains("damaged"), "{messages:?}"); + assert!(messages[1].contains("password"), "{messages:?}"); assert!(done.outcome.created.is_empty()); assert_eq!(names_in(&work), ["broken.zip", "locked.zip", "truncated.zip"]); } @@ -4306,4 +4941,475 @@ mod tests { assert_eq!(done.outcome.undo, None, "nothing is left to undo"); assert!(done.outcome.created.is_empty()); } + + fn errno(e: Errno) -> io::Error { + io::Error::from_raw_os_error(e.raw_os_error()) + } + + #[test] + fn each_kind_of_failure_has_plain_words() { + let s = Scratch::new(); + let folder = s.dir("Backups"); + let item = folder.join("photo.jpg"); + let one = |e: Errno, side: Side| reason(&errno(e), &item, side).one; + let many = |e: Errno, side: Side| reason(&errno(e), &item, side).many; + let w = Side::Write(&folder); + for full in [Errno::NOSPC, Errno::DQUOT] { + let said = one(full, w); + assert!(said.starts_with("There isn't enough space in “Backups”, which has ") && said.ends_with(" free"), "{said}"); + } + assert_eq!(one(Errno::ACCESS, w), "You don't have permission to change “Backups”"); + assert_eq!(one(Errno::PERM, w), "You don't have permission to change “Backups”"); + assert_eq!(one(Errno::ACCESS, Side::Read), "You don't have permission to read it"); + assert_eq!(many(Errno::PERM, Side::Read), "You don't have permission to read them"); + assert_eq!(one(Errno::ROFS, w), "“Backups” is on a read-only drive"); + assert_eq!(one(Errno::NAMETOOLONG, w), "The name is too long for “Backups”"); + assert_eq!(many(Errno::NAMETOOLONG, w), "The names are too long for “Backups”"); + assert_eq!(one(Errno::IO, w), "The drive couldn't read or write it. It may be failing or have been unplugged"); + assert_eq!(many(Errno::IO, Side::Read), "The drive couldn't read or write them. It may be failing or have been unplugged"); + assert_eq!(one(Errno::NOENT, Side::Read), "It's no longer there"); + assert_eq!(many(Errno::NOENT, Side::Read), "They're no longer there"); + assert_eq!(one(Errno::NOENT, w), "“Backups” is no longer there", "the folder being written in went"); + // Changing an item where it is names its folder. + assert_eq!(one(Errno::ACCESS, Side::Change), "You don't have permission to change “Backups”"); + assert_eq!(one(Errno::NOENT, Side::Change), "It's no longer there"); + // Anything else keeps the system's words. + assert_eq!(one(Errno::BUSY, w), "Device or resource busy"); + } + + fn told_of(failures: &[(&str, Reason)]) -> Vec { + let mut f = Failures::default(); + for (path, r) in failures { + f.add(Path::new(path), Reason { key: r.key.clone(), one: r.one.clone(), many: r.many.clone() }); + } + f.told() + } + + fn because(path: &str, e: Errno, side: Side) -> Reason { + reason(&errno(e), Path::new(path), side) + } + + #[test] + fn one_failure_keeps_its_name_and_repeats_are_counted() { + let one = told_of(&[("/x/a.txt", because("/x/a.txt", Errno::ACCESS, Side::Read))]); + assert_eq!(one, [Told { path: "/x/a.txt".into(), message: "You don't have permission to read it".into(), paths: vec!["/x/a.txt".into()], count: 1 }]); + let names: Vec = (0..12).map(|i| format!("/x/{i}.txt")).collect(); + let mut many: Vec<(&str, Reason)> = names.iter().map(|n| (n.as_str(), because(n, Errno::ACCESS, Side::Read))).collect(); + many.insert(3, ("/x/gone.txt", because("/x/gone.txt", Errno::NOENT, Side::Read))); + let told = told_of(&many); + assert_eq!(told.len(), 2, "a group is told where its first failure was"); + assert_eq!((told[0].path.as_os_str(), told[0].message.as_str(), told[0].count), ("".as_ref(), "12 files: You don't have permission to read them", 12)); + // Only the first few names are kept, however many failed. + assert_eq!(told[0].paths, names[..NAMED].iter().map(PathBuf::from).collect::>()); + assert_eq!((told[1].path.as_os_str(), told[1].message.as_str()), ("/x/gone.txt".as_ref(), "It's no longer there")); + let same = Reason::same("Special files like sockets and devices aren't copied".into()); + assert_eq!(told_of(&[("/x/0", Reason::same(same.one.clone())), ("/x/1", same)])[0].message, "2 files: Special files like sockets and devices aren't copied"); + assert_eq!(thousands(20000), "20,000"); + assert_eq!(thousands(999), "999"); + assert_eq!(thousands(1_234_567), "1,234,567"); + } + + #[test] + fn a_hundred_thousand_failures_keep_five_names() { + let mut f = Failures::default(); + for i in 0..100_000 { + f.add(Path::new(&format!("/x/{i}")), Reason::same("x".into())); + } + assert_eq!(f.groups.len(), 1); + assert_eq!(f.groups[0].paths.len(), NAMED); + assert_eq!(f.told()[0].message, "100,000 files: x"); + } + + #[test] + fn no_space_in_two_folders_with_one_name_is_told_apart() { + let s = Scratch::new(); + let (a, b) = (s.dir("a/Backups"), s.dir("b/Backups")); + let ra = reason(&errno(Errno::NOSPC), &a.join("f"), Side::Write(&a)); + let rb = reason(&errno(Errno::NOSPC), &b.join("f"), Side::Write(&b)); + assert_ne!(ra.key, rb.key); + assert!(ra.one.starts_with("There isn't enough space in “Backups”"), "{}", ra.one); + } + + #[test] + fn a_folder_among_the_failures_counts_them_as_items() { + let s = Scratch::new(); + let d = s.dir("d"); + let f = s.file("f", b""); + let mut all = Failures::default(); + all.add(&d, Reason::same("x".into())); + all.add(&f, Reason::same("x".into())); + assert_eq!(all.told()[0].message, "2 items: x"); + } + + #[test] + fn a_job_with_many_unreadable_files_tells_them_once() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + for i in 0..5 { + let f = s.file(&format!("src/locked{i}"), b"x"); + fs::set_permissions(&f, fs::Permissions::from_mode(0o000)).unwrap(); + } + s.file("src/fine", b"y"); + e.start(Request::Copy { sources: vec![s.path().join("src")], dest: s.dir("dest") }); + let done = finish(&rx, vec![]); + for i in 0..5 { + fs::set_permissions(s.path().join(format!("src/locked{i}")), fs::Permissions::from_mode(0o600)).unwrap(); + } + assert_eq!(done.errors, [(PathBuf::new(), "5 files: You don't have permission to read them".to_string())]); + assert_eq!(done.outcome.errors, 5); + assert!(s.path().join("dest/src/fine").exists()); + } + + /// A tiny disk of its own, 4 MiB, that scripts/sandbox-run.sh mounts for this test alone. + fn small_disk(name: &str) -> PathBuf { + let d = Path::new("/run/gannet-small").join(name); + assert!(fs::metadata(&d).is_ok(), "run tests with scripts/test.sh"); + d + } + + /// `n` files of 1 MiB in `dir`, more than a small disk holds. + fn megabytes(s: &Scratch, dir: &str, n: usize) { + for i in 0..n { + s.file(&format!("{dir}/part{i}.bin"), &patterned(1 << 20)); + } + } + + fn contents(dir: &Path) -> Vec { + let mut names: Vec = fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names + } + + #[test] + fn a_copy_that_wont_fit_doesnt_start() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + megabytes(&s, "Big Folder", 6); + let disk = small_disk("refuse"); + e.start(Request::Copy { sources: vec![s.path().join("Big Folder")], dest: disk.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors.len(), 1, "{:?}", done.errors); + let (path, said) = &done.errors[0]; + assert_eq!(path, Path::new("")); + assert!(said.starts_with("“Big Folder” needs 6.3 MB, but “refuse” only has ") && said.ends_with(" free"), "{said}"); + assert!(contents(&disk).is_empty(), "nothing was started"); + assert_eq!(done.outcome.undo, None); + } + + #[test] + fn a_copy_that_fills_its_disk_partway_is_taken_away() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.skip_space_check = true; + megabytes(&s, "Big Folder/inner", 6); + let disk = small_disk("fill"); + let job = e.start(Request::Copy { sources: vec![s.path().join("Big Folder")], dest: disk.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “Big Folder”: there isn't enough space in “fill”. Nothing was copied".to_string())]); + assert!(contents(&disk).is_empty(), "{:?}", contents(&disk)); + assert_eq!(done.outcome.undo, None); + assert!(done.outcome.created.is_empty()); + assert!(job.progress.done_bytes.load(Ordering::Relaxed) > 0, "it did start"); + } + + #[test] + fn a_full_merge_takes_away_only_what_it_added() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.skip_space_check = true; + let disk = small_disk("merge"); + let top = disk.clone(); + // Replace sends what it replaces to that disk's own Trash. + e.trash.mount_of = Arc::new(move |p| p.starts_with(&top).then(|| top.clone())); + fs::create_dir_all(disk.join("data/kept")).unwrap(); + fs::write(disk.join("data/old.txt"), b"was here").unwrap(); + fs::write(disk.join("data/kept/inside"), b"also here").unwrap(); + fs::write(disk.join("data/a.bin"), b"old a").unwrap(); + s.file("data/a.bin", b"new a"); + megabytes(&s, "data", 3); + megabytes(&s, "data/kept", 1); + megabytes(&s, "data/new folder", 2); + e.start(Request::Copy { sources: vec![s.path().join("data")], dest: disk.clone() }); + // Replace merges the folders, and applies to the files as well. Which clashes come up + // before the disk fills depends on the order the folder lists its names in, so every + // one is answered, however many there are. + let done = finish_replacing(&rx); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “data”: there isn't enough space in “merge”. Nothing was copied".to_string())]); + assert_eq!(contents(&disk.join("data")), ["a.bin", "kept", "old.txt"]); + assert_eq!(contents(&disk.join("data/kept")), ["inside"]); + assert_eq!(fs::read(disk.join("data/old.txt")).unwrap(), b"was here"); + assert_eq!(fs::read(disk.join("data/a.bin")).unwrap(), b"old a", "what a Replace sent to the Trash is back"); + no_partials(&disk); + } + + #[test] + fn a_move_to_a_disk_that_fills_leaves_the_originals() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.skip_space_check = true; + megabytes(&s, "src/Life/maps", 3); + megabytes(&s, "src/Life", 3); + s.file("src/notes.txt", b"small"); + let before = contents(&s.path().join("src/Life")); + let disk = small_disk("move"); + e.start(Request::Move { sources: vec![s.path().join("src/notes.txt"), s.path().join("src/Life")], dest: disk.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't move 2 items: there isn't enough space in “move”. Nothing was moved".to_string())]); + assert!(contents(&disk).is_empty(), "{:?}", contents(&disk)); + assert_eq!(contents(&s.path().join("src/Life")), before); + assert_eq!(contents(&s.path().join("src/Life/maps")).len(), 3); + assert_eq!(fs::read(s.path().join("src/notes.txt")).unwrap(), b"small", "moved first, and still kept"); + assert_eq!(done.outcome.undo, None); + } + + #[test] + fn a_move_across_disks_keeps_a_file_changed_while_it_was_copied() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.force_exdev = true; + // Two chunks, with a pause between them. + e.slow_copy = Some(Duration::from_millis(500)); + let f = s.file("src/d/a", &patterned(CHUNK_FOR_TESTS)); + let d = s.dir("dest"); + e.start(Request::Move { sources: vec![s.path().join("src/d")], dest: d.clone() }); + std::thread::sleep(Duration::from_millis(150)); + fs::OpenOptions::new().append(true).open(&f).unwrap().write_all(b"more").unwrap(); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(f.clone(), "This changed while it was being moved, so the original was kept as well".to_string())]); + assert_eq!(fs::read(&f).unwrap().len(), CHUNK_FOR_TESTS + 4); + assert_eq!(done.outcome.undo, None); + } + + #[test] + fn a_name_already_there_skips_the_check_and_a_full_disk_still_takes_it_back() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + megabytes(&s, "Big Folder", 6); + let disk = small_disk("named"); + fs::create_dir(disk.join("Big Folder")).unwrap(); + fs::write(disk.join("Big Folder/mine.txt"), b"mine").unwrap(); + e.start(Request::Copy { sources: vec![s.path().join("Big Folder")], dest: disk.clone() }); + // Merged, so the check can't tell what it will take, and the copy starts. + let done = finish(&rx, vec![answer(Choice::Replace)]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “Big Folder”: there isn't enough space in “named”. Nothing was copied".to_string())]); + assert_eq!(contents(&disk.join("Big Folder")), ["mine.txt"]); + } + + #[test] + fn a_sparse_file_counts_only_what_it_holds() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + // 8 MiB long, nothing written: the check lets it start, and the copy writes the zeros. + let f = s.path().join("sparse.img"); + File::create(&f).unwrap().set_len(8 << 20).unwrap(); + let disk = small_disk("sparse"); + e.start(Request::Copy { sources: vec![f], dest: disk.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “sparse.img”: there isn't enough space in “sparse”. Nothing was copied".to_string())]); + assert!(contents(&disk).is_empty()); + } + + /// A bind mount shows the same device at another path, as a folder on one disk does, and + /// what's on one device isn't measured: it fills as it goes, and is taken back. + #[test] + fn a_copy_within_one_device_isnt_checked() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + let disk = small_disk("one"); + fs::create_dir(disk.join("src")).unwrap(); + for i in 0..3 { + fs::write(disk.join(format!("src/part{i}.bin")), patterned(1 << 20)).unwrap(); + } + let other = disk.join("other"); + fs::create_dir(&other).unwrap(); + e.start(Request::Copy { sources: vec![disk.join("src")], dest: other.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't copy “src”: there isn't enough space in “other”. Nothing was copied".to_string())]); + assert!(contents(&other).is_empty()); + assert_eq!(contents(&disk.join("src")).len(), 3); + } + + #[test] + fn a_move_that_fills_says_what_was_renamed_on_the_same_drive() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.skip_space_check = true; + let disk = small_disk("mixed"); + fs::write(disk.join("here.txt"), b"same drive").unwrap(); + let dest = disk.join("dest"); + fs::create_dir(&dest).unwrap(); + megabytes(&s, "Big", 6); + e.start(Request::Move { sources: vec![disk.join("here.txt"), s.path().join("Big")], dest: dest.clone() }); + let done = finish(&rx, vec![]); + assert_eq!(done.errors, [(PathBuf::new(), "Couldn't move 2 items: there isn't enough space in “dest”. 1 on the same drive was moved, and the rest were left where they were".to_string())]); + assert_eq!(contents(&dest), ["here.txt"]); + assert_eq!(contents(&s.path().join("Big")).len(), 6); + let Some(Undo(steps)) = &done.outcome.undo else { panic!("the rename can be undone") }; + assert!(matches!(&steps[..], [Step::Moved { .. }]), "{steps:?}"); + } + + #[test] + fn stopping_a_move_across_disks_takes_it_back() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.force_exdev = true; + // Each file copies in two chunks with a pause between, so the stop lands partway. + e.slow_copy = Some(Duration::from_millis(20)); + let sources: Vec = (0..50) + .map(|i| { + let f = s.path().join(format!("src/f{i:02}")); + fs::create_dir_all(f.parent().unwrap()).unwrap(); + File::create(&f).unwrap().set_len(CHUNK_FOR_TESTS as u64).unwrap(); + f + }) + .collect(); + let d = s.dir("dest"); + let job = e.start(Request::Move { sources: sources.clone(), dest: d.clone() }); + let started = Instant::now(); + while job.progress.done_items.load(Ordering::Relaxed) < 30 { + assert!(started.elapsed() < Duration::from_secs(20), "the move never got to 30"); + std::thread::sleep(Duration::from_millis(1)); + } + job.cancel(); + let done = finish(&rx, vec![]); + assert!(done.outcome.cancelled); + assert!(done.errors.is_empty(), "{:?}", done.errors); + assert_eq!(done.outcome.stopped.as_deref(), Some("Stopped moving 50 items. Nothing was moved")); + assert!(sources.iter().all(|f| f.exists()), "every original is there"); + assert!(contents(&d).is_empty(), "no copy is left: {:?}", contents(&d)); + assert_eq!(done.outcome.undo, None); + } + + #[test] + fn a_source_that_cant_be_checked_after_its_copy_stays() { + let s = Scratch::new(); + let (mut e, rx) = engine(&s); + e.force_exdev = true; + e.slow_copy = Some(Duration::from_millis(500)); + let f = s.file("src/d/a", &patterned(CHUNK_FOR_TESTS)); + let d = s.dir("dest"); + e.start(Request::Move { sources: vec![s.path().join("src/d")], dest: d.clone() }); + std::thread::sleep(Duration::from_millis(150)); + // Its folder can't be searched any more, so whether it's still the file copied can't be told. + fs::set_permissions(s.path().join("src/d"), fs::Permissions::from_mode(0o600)).unwrap(); + let done = finish(&rx, vec![]); + fs::set_permissions(s.path().join("src/d"), fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!(done.errors, [(f.clone(), "You don't have permission to read it".to_string())]); + assert_eq!(fs::read(&f).unwrap().len(), CHUNK_FOR_TESTS); + assert_eq!(done.outcome.undo, None, "not moved, as the original is still there"); + } + + #[test] + fn a_file_on_a_share_is_known_by_its_size_and_times_not_its_inode() { + let reference = 1_000_000; + let was = Seen { ino: 10, len: 5, mtime: (900_000, 7), ctime: (900_000, 9) }; + let same = |now: Seen, care| was.unchanged(&now, care, reference); + let renumbered = Seen { ino: 99, ..was }; + assert!(!same(renumbered, Care::Strict), "on a local disk a new inode is another file"); + assert!(!same(renumbered, Care::Coarse)); + assert!(same(renumbered, Care::Loose), "on a share the number can change by itself"); + assert!(!same(Seen { len: 6, ..renumbered }, Care::Loose)); + assert!(!same(Seen { mtime: (900_001, 7), ..was }, Care::Loose)); + // A rewrite of the same size that kept the time shows in the change time. + assert!(!same(Seen { ctime: (900_050, 0), ..renumbered }, Care::Loose)); + assert!(!same(Seen { ctime: (900_050, 0), ..was }, Care::Coarse)); + assert!(same(Seen { ctime: (900_050, 0), ..was }, Care::Strict), "fine times need no change time"); + // Where the filesystem doesn't keep a change time, it isn't compared. + assert!(Seen { ctime: (0, 0), ..was }.unchanged(&Seen { ctime: (5, 0), ..renumbered }, Care::Loose, reference)); + } + + #[test] + fn a_file_with_a_time_near_the_copy_is_kept_where_times_are_coarse_or_from_a_server() { + let reference = 1_000_000; + // Within 10 s either side of the reference, or after it, as a server running ahead stamps. + for t in [reference - 10, reference - 3, reference, reference + 3, reference + 10, reference + 3600] { + let w = Seen { ino: 1, len: 5, mtime: (t, 0), ctime: (t, 0) }; + assert!(!w.unchanged(&w, Care::Loose, reference), "{t}"); + assert!(!w.unchanged(&w, Care::Coarse, reference), "{t}"); + assert!(w.unchanged(&w, Care::Strict, reference), "a disk with fine times needs no window: {t}"); + } + let old = Seen { ino: 1, len: 5, mtime: (reference - 11, 0), ctime: (reference - 11, 0) }; + assert!(old.unchanged(&old, Care::Loose, reference)); + assert!(old.unchanged(&old, Care::Coarse, reference)); + } + + #[test] + fn the_reference_is_the_look_before_the_copy_or_the_job_start_if_earlier() { + let t = |secs| std::time::UNIX_EPOCH + Duration::from_secs(secs); + assert_eq!(reference_time(t(1_000_100), t(1_000_000)), 1_000_000, "the job started first"); + assert_eq!(reference_time(t(999_000), t(1_000_000)), 999_000, "the clock went back since the start"); + // A file changed just after its look, but stamped before the copy ended, is still kept. + let looked: i64 = 1_000_100; + let r = reference_time(t(looked as u64), t(1_000_090)); + let w = Seen { ino: 1, len: 5, mtime: (looked + 1, 0), ctime: (looked + 1, 0) }; + assert!(!w.unchanged(&w, Care::Loose, r)); + } + + #[test] + fn only_shares_that_renumber_inodes_are_loose() { + let m = |point: &str, fs_type: &str| crate::mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; + let all = [ + m("/", "ext4"), + m("/mnt/nas", "cifs"), + m("/mnt/smb", "smb3"), + m("/srv", "nfs4"), + m("/home/me/remote", "fuse.sshfs"), + m("/run/user/1000/gvfs", "fuse.gvfsd-fuse"), + m("/mnt/vm", "9p"), + m("/run/media/me/USB", "fuseblk"), + m("/mnt/exfat", "fuse.exfat"), + m("/home/me/vault", "fuse.gocryptfs"), + ]; + for loose in ["/mnt/nas/a", "/mnt/smb/a", "/srv/d", "/home/me/remote/b", "/run/user/1000/gvfs/x", "/mnt/vm/y"] { + assert_eq!(care_in(&all, Path::new(loose)), Care::Loose, "{loose}"); + } + for stable in ["/home/me/e", "/run/media/me/USB/c", "/mnt/exfat/f", "/home/me/vault/g"] { + assert_eq!(care_in(&all, Path::new(stable)), Care::Strict, "{stable}"); + } + let coarse = [m("/", "ext4"), m("/a", "vfat"), m("/b", "exfat"), m("/c", "msdos"), m("/d", "ext3")]; + for c in ["/a/x", "/b/x", "/c/x", "/d/x"] { + assert_eq!(care_in(&coarse, Path::new(c)), Care::Coarse, "{c}"); + } + } + + #[test] + fn stopping_a_merge_on_one_disk_keeps_what_it_renamed() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + // Each folder holds one thing, and the sources go in the order given, so the questions + // come in this order on any disk: d, d/sub, then e, where the move is stopped. + s.file("src/d/sub/b", b"b"); + s.file("src/e", b"new e"); + s.file("dest/d/sub/old", b"old"); + s.file("dest/e", b"old e"); + e.start(Request::Move { sources: vec![s.path().join("src/d"), s.path().join("src/e")], dest: s.path().join("dest") }); + let done = finish(&rx, vec![answer(Choice::Replace), answer(Choice::Replace), answer(Choice::Cancel)]); + assert!(done.outcome.cancelled); + assert_eq!(done.outcome.stopped, None, "something was moved, so it isn't \"Nothing was moved\""); + assert_eq!(fs::read(s.path().join("dest/d/sub/b")).unwrap(), b"b"); + assert_eq!(fs::read(s.path().join("dest/d/sub/old")).unwrap(), b"old"); + assert!(!s.path().join("src/d").exists(), "the folders it emptied went"); + assert_eq!(fs::read(s.path().join("src/e")).unwrap(), b"new e"); + assert_eq!(fs::read(s.path().join("dest/e")).unwrap(), b"old e"); + assert_eq!(done.outcome.created, [s.path().join("dest/d")], "the folder merged into is selected"); + } + + #[test] + fn a_move_doesnt_count_a_disk_mounted_inside_it() { + let s = Scratch::new(); + let (e, rx) = engine(&s); + // scripts/sandbox-run.sh mounts an 8 MiB disk at tree/mnt, inside a 4 MiB one. + let tree = Path::new("/run/gannet-small/nest/tree"); + fs::write(tree.join("a.bin"), patterned(1 << 20)).unwrap(); + fs::write(tree.join("mnt/big.bin"), patterned(5 << 20)).unwrap(); + let dest = small_disk("nestdest"); + e.start(Request::Move { sources: vec![tree.to_path_buf()], dest: dest.clone() }); + let done = finish(&rx, vec![]); + // Counting the 5 MiB on the other disk would refuse it; that disk stays where it is. + assert_eq!(done.errors, [(tree.join("mnt"), "This is a mount point, so it was left where it is".to_string())]); + assert_eq!(fs::read(dest.join("tree/a.bin")).unwrap().len(), 1 << 20); + assert_eq!(fs::metadata(tree.join("mnt/big.bin")).unwrap().len(), 5 << 20); + } + + const CHUNK_FOR_TESTS: usize = 8 * 1024 * 1024 + 1; } diff --git a/crates/core/src/space.rs b/crates/core/src/space.rs new file mode 100644 index 0000000..6de3263 --- /dev/null +++ b/crates/core/src/space.rs @@ -0,0 +1,146 @@ +//! How much room a folder's filesystem has left for this user. + +use std::fs::File; +use std::os::fd::AsRawFd; +use std::path::{Path, PathBuf}; + +use crate::{complete, mounts}; + +/// The bytes this user can still write in `folder`: the smaller of what the filesystem has free +/// and what's left of the user's quota on it. `/tmp` on a tmpfs mounted with `usrquota` can +/// say gigabytes are free while the quota has room for far less. `None` if it can't be told. +pub fn free(folder: &Path) -> Option { + let f = File::open(folder).ok()?; + let vfs = rustix::fs::fstatvfs(&f).ok()?; + let disk = vfs.f_bavail.saturating_mul(vfs.f_frsize); + Some(quota_left(&f).map_or(disk, |q| q.min(disk))) +} + +/// What's left of this user's block quota on the file's filesystem, if it has one. +fn quota_left(f: &File) -> Option { + // QCMD(Q_GETQUOTA, USRQUOTA): the command above the type's byte. + const GET_USER_QUOTA: libc::c_uint = (libc::Q_GETQUOTA as libc::c_uint) << 8; + // SAFETY: an all-zero dqblk is valid; it's plain integers. + let mut q: libc::dqblk = unsafe { std::mem::zeroed() }; + // SAFETY: the fd is open for the call, and q is a dqblk the kernel fills in. + let r = unsafe { libc::syscall(libc::SYS_quotactl_fd, f.as_raw_fd(), GET_USER_QUOTA, libc::getuid(), &mut q as *mut libc::dqblk) }; + if r != 0 || q.dqb_valid & libc::QIF_BLIMITS == 0 || q.dqb_bhardlimit == 0 { + return None; + } + // The limit is in 1 KiB blocks and the use in bytes. + Some(q.dqb_bhardlimit.saturating_mul(1024).saturating_sub(q.dqb_curspace)) +} + +/// Whether `folder` is on, or inside, a network share, autofs or FUSE mount, where asking for +/// free space is a round trip that can hang. The same mounts the path bar's completion keeps +/// out of ([`complete::avoided_fs`]): a FUSE drive on a local disk (`fuseblk`, as ntfs-3g) is +/// asked, and so is `/`, even as a container's fuse-overlayfs root. The path is followed one +/// part at a time against the mount table first ([`complete::resolve`]), so a link to a share +/// counts as the share, and nothing on a share is looked up to find out. A folder that can't be +/// followed there counts as remote: it's left alone. +pub fn is_remote(folder: &Path) -> bool { + real_place(&mounts::read_mounts(), folder, &complete::Disk).is_none() +} + +/// Where `folder` really is, if it's a folder that can be reached without going into a share. +fn real_place(all: &[mounts::Mount], folder: &Path, look: &impl complete::Look) -> Option { + match complete::resolve(folder, all, look)? { + (real, complete::Kind::Folder) if !remote_in(all, &real) => Some(real), + _ => None, + } +} + +fn remote_in(all: &[mounts::Mount], folder: &Path) -> bool { + all.iter().any(|m| complete::avoided_fs(&m.fs_type) && m.point != Path::new("/") && folder.starts_with(&m.point)) +} + +/// Whether a check for room in `folder` would give a clear answer: not on a share or FUSE +/// (see [`is_remote`]), and not on btrfs, zfs or bcachefs, which can compress what's written, +/// share blocks between subvolumes of one pool, or dedupe, so the source's size says little +/// about what the copy will take. +pub fn worth_checking(folder: &Path) -> bool { + worth_checking_in(&mounts::read_mounts(), folder, &complete::Disk) +} + +fn worth_checking_in(all: &[mounts::Mount], folder: &Path, look: &impl complete::Look) -> bool { + let Some(real) = real_place(all, folder, look) else { return false }; + let point = mounts::mount_point_of(all, &real); + let fs_type = all.iter().rev().find(|m| Some(&m.point) == point.as_ref()).map(|m| m.fs_type.as_str()); + !matches!(fs_type, Some("btrfs" | "zfs" | "bcachefs")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn free_space_is_never_more_than_the_disk_has() { + let s = crate::testutil::Scratch::new(); + let disk = rustix::fs::statvfs(s.path()).map(|v| v.f_bavail * v.f_frsize).unwrap(); + let free = free(s.path()).unwrap(); + assert!(free <= disk, "{free} > {disk}"); + } + + #[test] + fn a_small_tmpfs_says_how_little_it_has() { + // scripts/sandbox-run.sh mounts these, 4 MiB each. + let free = free(Path::new(SMALL)).unwrap(); + assert!(free <= 4 << 20 && free > 0, "{free}"); + assert!(!is_remote(Path::new(SMALL)) && worth_checking(Path::new(SMALL))); + } + + /// A disk of folders, with these links, that says if anything inside a share is looked up. + struct Fake(Vec<(&'static str, &'static str)>, &'static [&'static str]); + + impl complete::Look for Fake { + fn kind(&self, p: &Path) -> Option { + assert!(!self.1.iter().any(|s| p.starts_with(s)), "looked inside a share: {p:?}"); + Some(if self.0.iter().any(|(l, _)| p == Path::new(l)) { complete::Kind::Link } else { complete::Kind::Folder }) + } + fn read_link(&self, p: &Path) -> Option { + self.0.iter().find(|(l, _)| p == Path::new(l)).map(|(_, t)| PathBuf::from(t)) + } + fn entries(&self, _: &Path, _: &dyn Fn(&Path) -> bool) -> Option)>> { + None + } + } + + #[test] + fn a_link_to_a_share_counts_as_the_share() { + let m = |point: &str, fs_type: &str| mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; + let all = [m("/", "ext4"), m("/mnt/nas", "cifs"), m("/home", "btrfs"), m("/srv", "ext4")]; + let look = Fake(vec![("/srv/nas", "/mnt/nas"), ("/srv/backups", "/mnt/nas/backups"), ("/srv/home", "/home/me")], &["/mnt/nas"]); + assert!(real_place(&all, Path::new("/srv/nas/photos"), &look).is_none()); + assert!(!worth_checking_in(&all, Path::new("/srv/backups"), &look)); + assert!(!worth_checking_in(&all, Path::new("/srv/home/x"), &look), "a link onto btrfs is btrfs"); + assert!(worth_checking_in(&all, Path::new("/srv/data"), &look)); + assert_eq!(real_place(&all, Path::new("/srv/data"), &look), Some(PathBuf::from("/srv/data"))); + } + + #[test] + fn shares_and_fuse_are_never_asked_but_local_disks_are() { + let m = |point: &str, fs_type: &str| mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; + let all = [m("/", "fuse.fuse-overlayfs"), m("/mnt/nas", "cifs"), m("/mnt/nas/usb", "ext4"), m("/run/media/me/USB", "fuseblk"), m("/home/me/cloud", "fuse.rclone"), m("/net", "autofs")]; + assert!(!remote_in(&all, Path::new("/home/me/Documents")), "/ is never a share"); + assert!(remote_in(&all, Path::new("/mnt/nas/photos"))); + assert!(remote_in(&all, Path::new("/mnt/nas/usb")), "a mount inside a share counts as the share"); + assert!(!remote_in(&all, Path::new("/run/media/me/USB/x"))); + assert!(remote_in(&all, Path::new("/home/me/cloud"))); + assert!(remote_in(&all, Path::new("/net/host"))); + } + + #[test] + fn copy_on_write_disks_are_never_checked() { + let m = |point: &str, fs_type: &str| mounts::Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() }; + let all = [m("/", "ext4"), m("/home", "btrfs"), m("/tank", "zfs"), m("/pool", "bcachefs"), m("/tmp", "tmpfs"), m("/mnt/nas", "nfs4")]; + let ok = Fake(vec![], &[]); + assert!(worth_checking_in(&all, Path::new("/srv"), &ok)); + assert!(worth_checking_in(&all, Path::new("/tmp/x"), &ok)); + let look = Fake(vec![], &["/mnt/nas"]); + for no in ["/home/me", "/tank/a", "/pool", "/mnt/nas/a"] { + assert!(!worth_checking_in(&all, Path::new(no), &look), "{no}"); + } + } + + const SMALL: &str = "/run/gannet-small/space"; +} diff --git a/scripts/sandbox-run.sh b/scripts/sandbox-run.sh index 9c2c82d..b2e7ead 100755 --- a/scripts/sandbox-run.sh +++ b/scripts/sandbox-run.sh @@ -37,7 +37,14 @@ hide=() mapfile -d '' hide < "$SCRATCH/hide" # The covers come after every bind, as a bind brings what's mounted inside it along, and a # share mounted inside the checkout would otherwise come back with it. +# Tiny disks of their own, for tests of a destination that fills up. One for each such test, +# as tests run side by side. They're under /run, which the covers leave alone. +small=() +for name in space refuse fill merge move mixed named sparse one nest nestdest; do small+=(--size 4194304 --tmpfs "/run/gannet-small/$name"); done +# And a bigger disk mounted inside one of them, for a move that must leave it alone. +small+=(--size 8388608 --tmpfs /run/gannet-small/nest/tree/mnt) bwrap --die-with-parent --unshare-pid --unshare-net --ro-bind / / --dev /dev --proc /proc --tmpfs /run --tmpfs /run/gannet-tree/mnt --tmpfs "$HOME" \ + "${small[@]}" \ --bind "$SCRATCH/home" "$SCRATCH/home" --bind "$SCRATCH/tmp" /tmp \ --ro-bind "$BIN" "$BIN" --ro-bind "$ROOT" "$ROOT" --bind "$SCRATCH" "$SCRATCH" \ "${hide[@]}" \ diff --git a/tests/e2e.py b/tests/e2e.py index 4721f82..59825fc 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -3903,6 +3903,126 @@ def long_copies_show_progress_and_cancel(h): a.close() +def AppWithSmallDisk(h, start, disk, extra_env=None): + """A window with a 4 MiB disk of its own at `disk`, which the test can't see from outside.""" + disk.mkdir(exist_ok=True) + return App(h, start, extra_env=extra_env, bwrap_extra=("--size", str(4 << 20), "--tmpfs", str(disk))) + + +def megabytes(fs, folder, n): + """`n` files of 1 MiB in `folder`, so a few of them fill the small disk.""" + for i in range(n): + p = fs / folder / f"part{i}.bin" + p.parent.mkdir(parents=True, exist_ok=True) + p.write_bytes(os.urandom(1 << 20)) + + +def paste_into(a, folder, copy=True): + a.key("a", mods=["ctrl"]) + a.key("c" if copy else "x", mods=["ctrl"]) + time.sleep(0.1) + a.key("l", mods=["ctrl"]) + a.type(str(folder)) + a.key("Return") + a.wait(lambda s: s["dir"] == str(folder) and not s["loading"], f"at {folder}") + a.key("v", mods=["ctrl"]) + + +@check +def a_copy_too_big_for_the_disk_never_starts(h): + fs = fresh_fs() + disk = SCRATCH / "smalldisk" + megabytes(fs, "src/Life Is Strange", 6) + a = AppWithSmallDisk(h, fs / "src", disk) + a.wait(lambda s: s["count"] == 1) + paste_into(a, disk) + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "refused") + a.shot("copy-wont-fit") + assert len(s["notices"]) == 1, s["notices"] + assert re.fullmatch(r"“Life Is Strange” needs 6\.3 MB, but “smalldisk” only has [0-9.]+ [kM]B free", s["notices"][0]), s["notices"] + time.sleep(0.3) + assert a.state()["names"] == [], "nothing was started" + a.close() + + +@check +def a_copy_that_fills_the_disk_is_undone_even_in_a_merge(h): + fs = fresh_fs() + disk = SCRATCH / "smalldisk" + tree(fs, {"old/data/old.txt": "was here", "old/data/kept/inside.txt": "also here"}) + megabytes(fs, "new/data", 3) + megabytes(fs, "new/data/kept", 1) + megabytes(fs, "new/data/new folder", 2) + megabytes(fs, "big/Big Folder", 6) + # Skips the check before starting, so the copies fill the disk partway. + a = AppWithSmallDisk(h, fs / "big", disk, extra_env={"GANNET_SKIP_SPACE_CHECK": "1"}) + a.wait(lambda s: s["count"] == 1) + paste_into(a, disk) + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "filled and undone") + a.shot("copy-filled") + assert s["notices"] == ["Couldn't copy “Big Folder”: there isn't enough space in “smalldisk”. Nothing was copied"], s["notices"] + assert s["names"] == [], s["names"] + a.key("Escape") + a.wait(lambda s: not s["notices"]) + # A folder that was there before keeps everything it had. + a.key("l", mods=["ctrl"]) + a.type(str(fs / "old")) + a.key("Return") + a.wait(lambda s: s["dir"] == str(fs / "old") and s["count"] == 1) + paste_into(a, disk) + a.wait(lambda s: s["jobs"] == 0 and s["names"] == ["data"], "the folder that will be merged into") + a.key("l", mods=["ctrl"]) + a.type(str(fs / "new")) + a.key("Return") + a.wait(lambda s: s["dir"] == str(fs / "new") and s["count"] == 1) + paste_into(a, disk) + a.wait(lambda s: s["dialog"] == "conflict", "asks about the folder") + time.sleep(0.45) # A new conflict ignores input for a moment. + a.type("a") # For every folder: "kept" clashes too. + a.key("Left") + a.key("Return") # Merge. + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "merge filled and undone") + assert s["notices"] == ["Couldn't copy “data”: there isn't enough space in “smalldisk”. Nothing was copied"], s["notices"] + a.key("Escape") + a.key("l", mods=["ctrl"]) + a.type(str(disk / "data")) + a.key("Return") + s = a.wait(lambda s: s["dir"] == str(disk / "data") and not s["loading"], "in the merged folder") + assert sorted(s["names"]) == ["kept", "old.txt"], s["names"] + a.key("l", mods=["ctrl"]) + a.type(str(disk / "data/kept")) + a.key("Return") + s = a.wait(lambda s: s["dir"] == str(disk / "data/kept") and not s["loading"], "in the folder inside") + assert s["names"] == ["inside.txt"], s["names"] + a.close() + + +@check +def a_move_that_fills_the_other_disk_leaves_the_originals(h): + fs = fresh_fs() + disk = SCRATCH / "smalldisk" + megabytes(fs, "src/Life/maps", 3) + megabytes(fs, "src/Life", 3) + before = sorted(str(p.relative_to(fs)) for p in (fs / "src").rglob("*")) + a = AppWithSmallDisk(h, fs / "src", disk, extra_env={"GANNET_SKIP_SPACE_CHECK": "1"}) + a.wait(lambda s: s["count"] == 1) + paste_into(a, disk, copy=False) + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "filled and undone") + a.shot("move-filled") + assert s["notices"] == ["Couldn't move “Life”: there isn't enough space in “smalldisk”. Nothing was moved"], s["notices"] + assert s["names"] == [], s["names"] + assert sorted(str(p.relative_to(fs)) for p in (fs / "src").rglob("*")) == before, "the originals are all there" + # Without the skip, the same move is refused before it starts. + a.close() + a = AppWithSmallDisk(h, fs / "src", disk) + a.wait(lambda s: s["count"] == 1) + paste_into(a, disk, copy=False) + s = a.wait(lambda s: s["jobs"] == 0 and s["notices"], "refused") + assert s["notices"][0].startswith("“Life” needs 6.3 MB, but “smalldisk” only has "), s["notices"] + assert sorted(str(p.relative_to(fs)) for p in (fs / "src").rglob("*")) == before + a.close() + + @check def failures_are_visible(h): fs = fresh_fs() @@ -3921,7 +4041,7 @@ def failures_are_visible(h): a.key("v", mods=["ctrl"]) s = a.wait(lambda s: s["jobs"] == 0 and len(s["notices"]) >= 2, "each failure reported") a.shot("failures") - assert any("denied" in n for n in s["notices"]), s["notices"] + assert any("You don't have permission" in n for n in s["notices"]), s["notices"] assert [p.name for p in (fs / "ro").iterdir()] == ["x"] # They stay until dismissed. time.sleep(0.5)