Skip to main content

oxinav_core/
operation.rs

1use crate::archive::{classify_entry_path, detect_format, ArchiveFormat, EntryTarget};
2use crate::error::OxiNavError;
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5
6#[derive(Debug, Clone)]
7pub enum Operation {
8    Copy { src: PathBuf, dest: PathBuf },
9    Move { src: PathBuf, dest: PathBuf },
10    Rename { src: PathBuf, dest: PathBuf },
11    Delete { path: PathBuf },
12    CreateDir { path: PathBuf },
13    CreateFile { path: PathBuf },
14    CreateSymlink { source: PathBuf, link: PathBuf },
15    ExtractArchive { archive: PathBuf, dest_dir: PathBuf },
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum OperationStatus {
20    Pending,
21    InProgress,
22    Done,
23    Failed(String),
24}
25
26/// A snapshot of a batch operation's progress, emitted once per item as the
27/// operation runs. `items_total`/`bytes_total` are fixed by a pre-walk before
28/// the first item is processed; the `*_done` counts and `current` path advance
29/// as work proceeds.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Progress {
32    /// The item currently being processed.
33    pub current: PathBuf,
34    /// Items completed so far (files; directories are structural).
35    pub items_done: usize,
36    /// Total items to process, known up front.
37    pub items_total: usize,
38    /// Bytes processed so far.
39    pub bytes_done: u64,
40    /// Total bytes to process, known up front (0 when unknown).
41    pub bytes_total: u64,
42}
43
44/// How a progress-aware operation finished.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum OperationOutcome {
47    /// Every item was processed.
48    Completed,
49    /// The cancel signal was set; remaining items were left untouched.
50    Cancelled,
51}
52
53pub trait Filesystem: Send + Sync {
54    fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError>;
55    fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError>;
56    fn delete(&self, path: &Path) -> Result<(), OxiNavError>;
57    fn create_dir(&self, path: &Path) -> Result<(), OxiNavError>;
58    /// Create an empty file at `path`.
59    fn create_file(&self, path: &Path) -> Result<(), OxiNavError>;
60    /// Create a symbolic link at `link` pointing at `source`.
61    fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError>;
62    fn exists(&self, path: &Path) -> bool;
63    /// Whether `path` is a directory. Used to drive recursive walks.
64    fn is_dir(&self, path: &Path) -> bool;
65    /// The immediate children of a directory (full paths).
66    fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError>;
67    /// Size of a file in bytes; 0 for directories or when unknown.
68    fn size(&self, path: &Path) -> u64;
69    /// Up to `max` bytes from the start of a file. Reading a prefix rather
70    /// than the whole file is what keeps the read-only viewer's memory use
71    /// bounded no matter how large the file is.
72    fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError>;
73    /// How many entries `archive` holds, so progress totals can be fixed
74    /// before extraction begins. For a gzipped tar this means decompressing
75    /// once to count and again to extract — the price of totals known up
76    /// front, which the progress contract requires.
77    fn count_archive_entries(
78        &self,
79        archive: &Path,
80        format: ArchiveFormat,
81    ) -> Result<usize, OxiNavError>;
82    /// Extract `archive` into `dest_dir`, invoking `on_entry` per entry
83    /// written. The format is decided by the caller so that detection stays
84    /// a pure, tested function rather than being repeated per backend.
85    fn extract_archive(
86        &self,
87        archive: &Path,
88        dest_dir: &Path,
89        format: ArchiveFormat,
90        on_entry: &mut dyn FnMut(&Path),
91    ) -> Result<(), OxiNavError>;
92}
93
94pub struct OperationEngine<F: Filesystem> {
95    fs: F,
96}
97
98#[derive(Debug, Clone, Copy)]
99pub struct StdFilesystem;
100
101impl Filesystem for StdFilesystem {
102    fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
103        if src.is_dir() {
104            copy_dir_recursive(src, dest).map_err(|source| OxiNavError::Io {
105                path: dest.to_path_buf(),
106                source,
107            })
108        } else {
109            std::fs::copy(src, dest)
110                .map(|_| ())
111                .map_err(|source| OxiNavError::Io {
112                    path: dest.to_path_buf(),
113                    source,
114                })
115        }
116    }
117
118    fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
119        std::fs::rename(src, dest).map_err(|source| OxiNavError::Io {
120            path: dest.to_path_buf(),
121            source,
122        })
123    }
124
125    fn delete(&self, path: &Path) -> Result<(), OxiNavError> {
126        let result = if path.is_dir() {
127            std::fs::remove_dir_all(path)
128        } else {
129            std::fs::remove_file(path)
130        };
131
132        result.map_err(|source| OxiNavError::Io {
133            path: path.to_path_buf(),
134            source,
135        })
136    }
137
138    fn create_dir(&self, path: &Path) -> Result<(), OxiNavError> {
139        std::fs::create_dir(path).map_err(|source| OxiNavError::Io {
140            path: path.to_path_buf(),
141            source,
142        })
143    }
144
145    fn create_file(&self, path: &Path) -> Result<(), OxiNavError> {
146        // create_new refuses to clobber, so a file appearing between the
147        // engine's pre-check and here is still an error rather than data loss.
148        std::fs::OpenOptions::new()
149            .write(true)
150            .create_new(true)
151            .open(path)
152            .map(|_| ())
153            .map_err(|source| OxiNavError::Io {
154                path: path.to_path_buf(),
155                source,
156            })
157    }
158
159    fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError> {
160        std::os::unix::fs::symlink(source, link).map_err(|source| OxiNavError::Io {
161            path: link.to_path_buf(),
162            source,
163        })
164    }
165
166    fn exists(&self, path: &Path) -> bool {
167        path.exists()
168    }
169
170    fn is_dir(&self, path: &Path) -> bool {
171        path.is_dir()
172    }
173
174    fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError> {
175        let entries = std::fs::read_dir(path).map_err(|source| OxiNavError::Io {
176            path: path.to_path_buf(),
177            source,
178        })?;
179        let mut out = Vec::new();
180        for entry in entries {
181            let entry = entry.map_err(|source| OxiNavError::Io {
182                path: path.to_path_buf(),
183                source,
184            })?;
185            out.push(entry.path());
186        }
187        Ok(out)
188    }
189
190    fn size(&self, path: &Path) -> u64 {
191        std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
192    }
193
194    fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
195        use std::io::Read;
196
197        let io_error = |source| OxiNavError::Io {
198            path: path.to_path_buf(),
199            source,
200        };
201        let file = std::fs::File::open(path).map_err(io_error)?;
202        let mut buffer = Vec::new();
203        file.take(max as u64)
204            .read_to_end(&mut buffer)
205            .map_err(io_error)?;
206        Ok(buffer)
207    }
208
209    fn count_archive_entries(
210        &self,
211        archive: &Path,
212        format: ArchiveFormat,
213    ) -> Result<usize, OxiNavError> {
214        let file = open_archive(archive)?;
215        match format {
216            ArchiveFormat::Zip => {
217                let zip = zip::ZipArchive::new(file).map_err(|e| archive_error(archive, e))?;
218                Ok(zip.len())
219            }
220            ArchiveFormat::Tar => {
221                let mut tar = tar::Archive::new(file);
222                let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
223                Ok(entries.count())
224            }
225            ArchiveFormat::TarGz => {
226                let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
227                let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
228                Ok(entries.count())
229            }
230        }
231    }
232
233    fn extract_archive(
234        &self,
235        archive: &Path,
236        dest_dir: &Path,
237        format: ArchiveFormat,
238        on_entry: &mut dyn FnMut(&Path),
239    ) -> Result<(), OxiNavError> {
240        let file = open_archive(archive)?;
241        match format {
242            ArchiveFormat::Zip => {
243                let mut zip = zip::ZipArchive::new(file).map_err(|e| archive_error(archive, e))?;
244                for index in 0..zip.len() {
245                    let mut entry = zip.by_index(index).map_err(|e| archive_error(archive, e))?;
246                    let raw = entry.name().to_string();
247                    let Some(target) = resolve_entry(dest_dir, &raw)? else {
248                        continue;
249                    };
250
251                    if entry.is_dir() {
252                        create_dir_all(&target)?;
253                    } else {
254                        if let Some(parent) = target.parent() {
255                            create_dir_all(parent)?;
256                        }
257                        let mut out =
258                            std::fs::File::create(&target).map_err(|source| OxiNavError::Io {
259                                path: target.clone(),
260                                source,
261                            })?;
262                        std::io::copy(&mut entry, &mut out).map_err(|source| OxiNavError::Io {
263                            path: target.clone(),
264                            source,
265                        })?;
266                    }
267                    on_entry(&target);
268                }
269                Ok(())
270            }
271            ArchiveFormat::Tar => extract_tar(tar::Archive::new(file), archive, dest_dir, on_entry),
272            ArchiveFormat::TarGz => extract_tar(
273                tar::Archive::new(flate2::read::GzDecoder::new(file)),
274                archive,
275                dest_dir,
276                on_entry,
277            ),
278        }
279    }
280}
281
282/// Expand a leading `~` (alone or as `~/rest`) to `home`. A `~` anywhere
283/// else is an ordinary character and is left alone.
284fn expand_home(input: &str, home: &Path) -> PathBuf {
285    match input.strip_prefix('~') {
286        Some("") => home.to_path_buf(),
287        Some(rest) => match rest.strip_prefix('/') {
288            Some(relative) => home.join(relative),
289            // `~foo` names another user's home, which we do not resolve.
290            None => PathBuf::from(input),
291        },
292        None => PathBuf::from(input),
293    }
294}
295
296fn open_archive(archive: &Path) -> Result<std::fs::File, OxiNavError> {
297    std::fs::File::open(archive).map_err(|source| OxiNavError::Io {
298        path: archive.to_path_buf(),
299        source,
300    })
301}
302
303/// Wrap a decoder error as I/O against the archive, so callers see one error
304/// type regardless of which backend produced it.
305fn archive_error<E: std::fmt::Display>(archive: &Path, error: E) -> OxiNavError {
306    OxiNavError::Io {
307        path: archive.to_path_buf(),
308        source: std::io::Error::other(error.to_string()),
309    }
310}
311
312fn create_dir_all(path: &Path) -> Result<(), OxiNavError> {
313    std::fs::create_dir_all(path).map_err(|source| OxiNavError::Io {
314        path: path.to_path_buf(),
315        source,
316    })
317}
318
319/// Join a raw archive entry name onto `dest_dir`. `Ok(None)` means the entry
320/// names the destination itself and has nothing to write; an escaping entry
321/// is an error.
322fn resolve_entry(dest_dir: &Path, raw: &str) -> Result<Option<PathBuf>, OxiNavError> {
323    match classify_entry_path(Path::new(raw)) {
324        EntryTarget::Within(relative) => Ok(Some(dest_dir.join(relative))),
325        EntryTarget::ArchiveRoot => Ok(None),
326        EntryTarget::Escaping => Err(OxiNavError::UnsafeArchiveEntry(raw.to_string())),
327    }
328}
329
330fn extract_tar<R: std::io::Read>(
331    mut tar: tar::Archive<R>,
332    archive: &Path,
333    dest_dir: &Path,
334    on_entry: &mut dyn FnMut(&Path),
335) -> Result<(), OxiNavError> {
336    let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
337    for entry in entries {
338        let mut entry = entry.map_err(|e| archive_error(archive, e))?;
339        let raw = entry
340            .path()
341            .map_err(|e| archive_error(archive, e))?
342            .to_string_lossy()
343            .into_owned();
344        let Some(target) = resolve_entry(dest_dir, &raw)? else {
345            continue;
346        };
347
348        if entry.header().entry_type().is_dir() {
349            create_dir_all(&target)?;
350        } else {
351            if let Some(parent) = target.parent() {
352                create_dir_all(parent)?;
353            }
354            // unpack rather than a manual copy so tar's own mode/mtime
355            // handling still applies.
356            entry
357                .unpack(&target)
358                .map_err(|e| archive_error(archive, e))?;
359        }
360        on_entry(&target);
361    }
362    Ok(())
363}
364
365impl<F: Filesystem> OperationEngine<F> {
366    pub fn new(fs: F) -> Self {
367        Self { fs }
368    }
369
370    pub fn exists(&self, path: &Path) -> bool {
371        self.fs.exists(path)
372    }
373
374    /// Read at most `max` bytes from the start of `path`, for read-only
375    /// viewing. Like the mutating operations, the path is checked before the
376    /// filesystem is touched.
377    /// Resolve a user-typed directory path for a jump: expand a leading `~`
378    /// against `home`, then require that it exists and is a directory.
379    ///
380    /// Lives on the engine rather than in `pane` because the checks go
381    /// through the `Filesystem` trait, which is what makes them testable
382    /// without a real directory to point at.
383    pub fn resolve_directory(&self, input: &str, home: &Path) -> Result<PathBuf, OxiNavError> {
384        let trimmed = input.trim();
385        if trimmed.is_empty() {
386            return Err(OxiNavError::SourceNotFound(PathBuf::from(trimmed)));
387        }
388
389        let expanded = expand_home(trimmed, home);
390
391        if !self.fs.exists(&expanded) {
392            return Err(OxiNavError::SourceNotFound(expanded));
393        }
394        if !self.fs.is_dir(&expanded) {
395            return Err(OxiNavError::NotADirectory(expanded));
396        }
397        Ok(expanded)
398    }
399
400    /// Pre-flight for extraction: the archive must exist, be a format we
401    /// decode, and have a directory to land in. Checked before any decoding
402    /// so an unsupported archive leaves nothing behind.
403    fn check_extractable(
404        &self,
405        archive: &Path,
406        dest_dir: &Path,
407    ) -> Result<ArchiveFormat, OxiNavError> {
408        if !self.fs.exists(archive) {
409            return Err(OxiNavError::SourceNotFound(archive.to_path_buf()));
410        }
411        if !self.fs.exists(dest_dir) {
412            return Err(OxiNavError::SourceNotFound(dest_dir.to_path_buf()));
413        }
414        detect_format(archive).ok_or_else(|| OxiNavError::UnsupportedArchive(archive.to_path_buf()))
415    }
416
417    pub fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
418        if !self.fs.exists(path) {
419            return Err(OxiNavError::SourceNotFound(path.to_path_buf()));
420        }
421        self.fs.read_capped(path, max)
422    }
423
424    pub fn execute(&self, op: &Operation) -> Result<(), OxiNavError> {
425        match op {
426            Operation::Copy { src, dest } => {
427                if !self.fs.exists(src) {
428                    return Err(OxiNavError::SourceNotFound(src.clone()));
429                }
430                if self.fs.exists(dest) {
431                    return Err(OxiNavError::DestinationExists(dest.clone()));
432                }
433                self.fs.copy(src, dest)
434            }
435            Operation::Move { src, dest } => {
436                if !self.fs.exists(src) {
437                    return Err(OxiNavError::SourceNotFound(src.clone()));
438                }
439                if self.fs.exists(dest) {
440                    return Err(OxiNavError::DestinationExists(dest.clone()));
441                }
442                // Fall back to copy+delete for cross-device moves
443                match self.fs.rename(src, dest) {
444                    Ok(()) => Ok(()),
445                    Err(_) => {
446                        self.fs.copy(src, dest)?;
447                        self.fs.delete(src)
448                    }
449                }
450            }
451            Operation::Rename { src, dest } => {
452                if !self.fs.exists(src) {
453                    return Err(OxiNavError::SourceNotFound(src.clone()));
454                }
455                if self.fs.exists(dest) {
456                    return Err(OxiNavError::DestinationExists(dest.clone()));
457                }
458                self.fs.rename(src, dest)
459            }
460            Operation::Delete { path } => {
461                if !self.fs.exists(path) {
462                    return Err(OxiNavError::SourceNotFound(path.clone()));
463                }
464                self.fs.delete(path)
465            }
466            Operation::CreateDir { path } => {
467                if self.fs.exists(path) {
468                    return Err(OxiNavError::DestinationExists(path.clone()));
469                }
470                self.fs.create_dir(path)
471            }
472            Operation::CreateFile { path } => {
473                if self.fs.exists(path) {
474                    return Err(OxiNavError::DestinationExists(path.clone()));
475                }
476                self.fs.create_file(path)
477            }
478            Operation::CreateSymlink { source, link } => {
479                if !self.fs.exists(source) {
480                    return Err(OxiNavError::SourceNotFound(source.clone()));
481                }
482                if self.fs.exists(link) {
483                    return Err(OxiNavError::DestinationExists(link.clone()));
484                }
485                self.fs.create_symlink(source, link)
486            }
487            Operation::ExtractArchive { archive, dest_dir } => {
488                let format = self.check_extractable(archive, dest_dir)?;
489                self.fs
490                    .extract_archive(archive, dest_dir, format, &mut |_| {})
491            }
492        }
493    }
494
495    /// Execute an operation while reporting incremental progress and honoring
496    /// a cooperative cancel flag.
497    ///
498    /// For batch operations (Copy/Move/Delete over a directory) the engine
499    /// drives the recursive walk itself, emitting one [`Progress`] per file
500    /// and polling `cancel` before each not-yet-started item. Totals are fixed
501    /// by a pre-walk before the first item is processed. Rename, CreateDir,
502    /// CreateFile and CreateSymlink are instantaneous, so they delegate to
503    /// [`execute`](Self::execute) and emit a single final tick.
504    ///
505    /// On cancellation the already-processed items are left in place (no
506    /// rollback) and [`OperationOutcome::Cancelled`] is returned.
507    pub fn execute_with_progress(
508        &self,
509        op: &Operation,
510        cancel: &AtomicBool,
511        on_progress: &mut dyn FnMut(Progress),
512    ) -> Result<OperationOutcome, OxiNavError> {
513        match op {
514            Operation::Copy { src, dest } => {
515                if !self.fs.exists(src) {
516                    return Err(OxiNavError::SourceNotFound(src.clone()));
517                }
518                if self.fs.exists(dest) {
519                    return Err(OxiNavError::DestinationExists(dest.clone()));
520                }
521                let (items_total, bytes_total) = self.walk_totals(src);
522                let mut state = ProgressState::new(items_total, bytes_total);
523                self.copy_recursive(src, dest, cancel, &mut state, on_progress)?;
524                Ok(outcome(cancel))
525            }
526            Operation::Delete { path } => {
527                if !self.fs.exists(path) {
528                    return Err(OxiNavError::SourceNotFound(path.clone()));
529                }
530                let (items_total, bytes_total) = self.walk_totals(path);
531                let mut state = ProgressState::new(items_total, bytes_total);
532                self.delete_recursive(path, cancel, &mut state, on_progress)?;
533                Ok(outcome(cancel))
534            }
535            Operation::Move { src, dest } => {
536                if !self.fs.exists(src) {
537                    return Err(OxiNavError::SourceNotFound(src.clone()));
538                }
539                if self.fs.exists(dest) {
540                    return Err(OxiNavError::DestinationExists(dest.clone()));
541                }
542                let (items_total, bytes_total) = self.walk_totals(src);
543                // Same-device rename is atomic — a single tick.
544                if self.fs.rename(src, dest).is_ok() {
545                    on_progress(Progress {
546                        current: src.clone(),
547                        items_done: items_total,
548                        items_total,
549                        bytes_done: bytes_total,
550                        bytes_total,
551                    });
552                    return Ok(OperationOutcome::Completed);
553                }
554                // Cross-device fallback: copy tree (with progress), then delete source.
555                let mut state = ProgressState::new(items_total, bytes_total);
556                self.copy_recursive(src, dest, cancel, &mut state, on_progress)?;
557                if cancel.load(Ordering::Relaxed) {
558                    return Ok(OperationOutcome::Cancelled);
559                }
560                self.fs.delete(src)?;
561                Ok(OperationOutcome::Completed)
562            }
563            // Instantaneous single-item ops: reuse the synchronous path.
564            Operation::Rename { dest, .. } => {
565                self.execute(op)?;
566                on_progress(single_tick(dest.clone()));
567                Ok(OperationOutcome::Completed)
568            }
569            Operation::CreateSymlink { link, .. } => {
570                self.execute(op)?;
571                on_progress(single_tick(link.clone()));
572                Ok(OperationOutcome::Completed)
573            }
574            // The one operation here that is neither instantaneous nor a
575            // filesystem walk: totals come from counting the archive first.
576            Operation::ExtractArchive { archive, dest_dir } => {
577                let format = self.check_extractable(archive, dest_dir)?;
578                let items_total = self.fs.count_archive_entries(archive, format)?;
579                let mut items_done = 0;
580
581                self.fs
582                    .extract_archive(archive, dest_dir, format, &mut |written| {
583                        items_done += 1;
584                        on_progress(Progress {
585                            current: written.to_path_buf(),
586                            items_done,
587                            items_total,
588                            bytes_done: 0,
589                            bytes_total: 0,
590                        });
591                    })?;
592
593                Ok(OperationOutcome::Completed)
594            }
595            Operation::CreateDir { path } | Operation::CreateFile { path } => {
596                self.execute(op)?;
597                on_progress(single_tick(path.clone()));
598                Ok(OperationOutcome::Completed)
599            }
600        }
601    }
602
603    /// Estimate the `(items, bytes)` an operation will process, matching what
604    /// [`execute_with_progress`](Self::execute_with_progress) counts. Lets a
605    /// caller pre-sum batch-wide totals before starting work.
606    pub fn estimate_totals(&self, op: &Operation) -> (usize, u64) {
607        match op {
608            Operation::Copy { src, .. } | Operation::Move { src, .. } => self.walk_totals(src),
609            Operation::Delete { path } => self.walk_totals(path),
610            Operation::Rename { .. }
611            | Operation::CreateDir { .. }
612            | Operation::CreateFile { .. }
613            | Operation::CreateSymlink { .. } => (1, 0),
614            // Counting can fail (missing or undecodable archive); execution
615            // will report that properly, so fall back to a single item here
616            // rather than surfacing an error from an estimate.
617            Operation::ExtractArchive { archive, dest_dir } => self
618                .check_extractable(archive, dest_dir)
619                .and_then(|format| self.fs.count_archive_entries(archive, format))
620                .map(|items| (items, 0))
621                .unwrap_or((1, 0)),
622        }
623    }
624
625    /// Count files (as items) and sum their sizes under `path`, recursively.
626    /// A file is one item; a directory contributes its descendant files.
627    fn walk_totals(&self, path: &Path) -> (usize, u64) {
628        if self.fs.is_dir(path) {
629            let mut items = 0;
630            let mut bytes = 0;
631            if let Ok(children) = self.fs.read_dir(path) {
632                for child in &children {
633                    let (i, b) = self.walk_totals(child);
634                    items += i;
635                    bytes += b;
636                }
637            }
638            (items, bytes)
639        } else {
640            (1, self.fs.size(path))
641        }
642    }
643
644    fn copy_recursive(
645        &self,
646        src: &Path,
647        dest: &Path,
648        cancel: &AtomicBool,
649        state: &mut ProgressState,
650        on_progress: &mut dyn FnMut(Progress),
651    ) -> Result<(), OxiNavError> {
652        if cancel.load(Ordering::Relaxed) {
653            return Ok(());
654        }
655        if self.fs.is_dir(src) {
656            self.fs.create_dir(dest)?;
657            for child in self.fs.read_dir(src)? {
658                if cancel.load(Ordering::Relaxed) {
659                    return Ok(());
660                }
661                let child_dest = match child.file_name() {
662                    Some(name) => dest.join(name),
663                    None => dest.to_path_buf(),
664                };
665                self.copy_recursive(&child, &child_dest, cancel, state, on_progress)?;
666            }
667        } else {
668            self.fs.copy(src, dest)?;
669            state.advance(self.fs.size(src));
670            on_progress(state.snapshot(src));
671        }
672        Ok(())
673    }
674
675    fn delete_recursive(
676        &self,
677        path: &Path,
678        cancel: &AtomicBool,
679        state: &mut ProgressState,
680        on_progress: &mut dyn FnMut(Progress),
681    ) -> Result<(), OxiNavError> {
682        if cancel.load(Ordering::Relaxed) {
683            return Ok(());
684        }
685        if self.fs.is_dir(path) {
686            for child in self.fs.read_dir(path)? {
687                if cancel.load(Ordering::Relaxed) {
688                    return Ok(());
689                }
690                self.delete_recursive(&child, cancel, state, on_progress)?;
691            }
692            if cancel.load(Ordering::Relaxed) {
693                return Ok(());
694            }
695            // Children are gone; remove the now-empty directory (structural).
696            self.fs.delete(path)?;
697        } else {
698            let bytes = self.fs.size(path);
699            self.fs.delete(path)?;
700            state.advance(bytes);
701            on_progress(state.snapshot(path));
702        }
703        Ok(())
704    }
705}
706
707/// Mutable accumulator threaded through a recursive walk to build each
708/// [`Progress`] snapshot.
709struct ProgressState {
710    items_done: usize,
711    items_total: usize,
712    bytes_done: u64,
713    bytes_total: u64,
714}
715
716impl ProgressState {
717    fn new(items_total: usize, bytes_total: u64) -> Self {
718        Self {
719            items_done: 0,
720            items_total,
721            bytes_done: 0,
722            bytes_total,
723        }
724    }
725
726    fn advance(&mut self, bytes: u64) {
727        self.items_done += 1;
728        self.bytes_done += bytes;
729    }
730
731    fn snapshot(&self, current: &Path) -> Progress {
732        Progress {
733            current: current.to_path_buf(),
734            items_done: self.items_done,
735            items_total: self.items_total,
736            bytes_done: self.bytes_done,
737            bytes_total: self.bytes_total,
738        }
739    }
740}
741
742fn outcome(cancel: &AtomicBool) -> OperationOutcome {
743    if cancel.load(Ordering::Relaxed) {
744        OperationOutcome::Cancelled
745    } else {
746        OperationOutcome::Completed
747    }
748}
749
750fn single_tick(current: PathBuf) -> Progress {
751    Progress {
752        current,
753        items_done: 1,
754        items_total: 1,
755        bytes_done: 0,
756        bytes_total: 0,
757    }
758}
759
760fn copy_dir_recursive(src: &Path, dest: &Path) -> std::io::Result<()> {
761    std::fs::create_dir_all(dest)?;
762    for entry in std::fs::read_dir(src)? {
763        let entry = entry?;
764        let dest_path = dest.join(entry.file_name());
765        if entry.file_type()?.is_dir() {
766            copy_dir_recursive(&entry.path(), &dest_path)?;
767        } else {
768            std::fs::copy(entry.path(), &dest_path)?;
769        }
770    }
771    Ok(())
772}
773
774#[cfg(test)]
775mod tests {
776    use super::*;
777    use std::collections::HashMap;
778    use std::sync::{Arc, Mutex};
779
780    /// In-memory filesystem. Each path maps to `Some(size)` for a file or
781    /// `None` for a directory, so the mock can model a tree for recursive
782    /// walks without touching disk.
783    #[derive(Clone)]
784    struct MockFs {
785        nodes: Arc<Mutex<HashMap<PathBuf, Option<u64>>>>,
786        /// Entry names each archive path "contains", standing in for a real
787        /// decoder so extraction is testable without a file on disk.
788        archives: Arc<Mutex<HashMap<PathBuf, Vec<String>>>>,
789    }
790
791    impl MockFs {
792        /// Build from a flat list of files (each 0 bytes).
793        fn with(paths: &[&str]) -> Self {
794            Self {
795                nodes: Arc::new(Mutex::new(
796                    paths.iter().map(|p| (PathBuf::from(p), Some(0))).collect(),
797                )),
798                archives: Arc::new(Mutex::new(HashMap::new())),
799            }
800        }
801
802        /// Register `entries` as the contents of the archive at `path`.
803        fn with_archive(self, path: &str, entries: &[&str]) -> Self {
804            self.nodes
805                .lock()
806                .unwrap()
807                .insert(PathBuf::from(path), Some(0));
808            self.archives.lock().unwrap().insert(
809                PathBuf::from(path),
810                entries.iter().map(|e| e.to_string()).collect(),
811            );
812            self
813        }
814
815        fn archive_entries(&self, archive: &Path) -> Vec<String> {
816            self.archives
817                .lock()
818                .unwrap()
819                .get(archive)
820                .cloned()
821                .unwrap_or_default()
822        }
823
824        /// Build a tree: `None` marks a directory, `Some(size)` a file.
825        fn tree(entries: &[(&str, Option<u64>)]) -> Self {
826            Self {
827                nodes: Arc::new(Mutex::new(
828                    entries
829                        .iter()
830                        .map(|(p, size)| (PathBuf::from(p), *size))
831                        .collect(),
832                )),
833                archives: Arc::new(Mutex::new(HashMap::new())),
834            }
835        }
836    }
837
838    impl Filesystem for MockFs {
839        fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
840            let mut nodes = self.nodes.lock().unwrap();
841            let value = nodes.get(src).copied().unwrap_or(Some(0));
842            nodes.insert(dest.to_path_buf(), value);
843            Ok(())
844        }
845        fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
846            let mut nodes = self.nodes.lock().unwrap();
847            let value = nodes.remove(src).unwrap_or(Some(0));
848            nodes.insert(dest.to_path_buf(), value);
849            Ok(())
850        }
851        fn delete(&self, path: &Path) -> Result<(), OxiNavError> {
852            let mut nodes = self.nodes.lock().unwrap();
853            nodes.remove(path);
854            // Remove descendants too, matching remove_dir_all semantics.
855            let prefix = format!("{}/", path.display());
856            nodes.retain(|p, _| !p.display().to_string().starts_with(&prefix));
857            Ok(())
858        }
859        fn create_dir(&self, path: &Path) -> Result<(), OxiNavError> {
860            self.nodes.lock().unwrap().insert(path.to_path_buf(), None);
861            Ok(())
862        }
863        fn create_file(&self, path: &Path) -> Result<(), OxiNavError> {
864            self.nodes
865                .lock()
866                .unwrap()
867                .insert(path.to_path_buf(), Some(0));
868            Ok(())
869        }
870        fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError> {
871            // Records the link as an entry mirroring its target's kind, which
872            // is all the listing-level assertions here need.
873            let mut nodes = self.nodes.lock().unwrap();
874            let value = nodes.get(source).copied().unwrap_or(Some(0));
875            nodes.insert(link.to_path_buf(), value);
876            Ok(())
877        }
878        fn exists(&self, path: &Path) -> bool {
879            self.nodes.lock().unwrap().contains_key(path)
880        }
881        fn is_dir(&self, path: &Path) -> bool {
882            matches!(self.nodes.lock().unwrap().get(path), Some(None))
883        }
884        fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError> {
885            let nodes = self.nodes.lock().unwrap();
886            Ok(nodes
887                .keys()
888                .filter(|p| p.parent() == Some(path))
889                .cloned()
890                .collect())
891        }
892        fn size(&self, path: &Path) -> u64 {
893            match self.nodes.lock().unwrap().get(path) {
894                Some(Some(size)) => *size,
895                _ => 0,
896            }
897        }
898        /// Files hold no real bytes here, so a read yields filler of the
899        /// recorded size — enough to exercise the cap, which is the only
900        /// behaviour of this method worth asserting on.
901        fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
902            let len = (self.size(path) as usize).min(max);
903            Ok(vec![b'a'; len])
904        }
905        fn count_archive_entries(
906            &self,
907            archive: &Path,
908            _format: ArchiveFormat,
909        ) -> Result<usize, OxiNavError> {
910            Ok(self.archive_entries(archive).len())
911        }
912        /// Stands in for a decoder: the "contents" of an archive are the
913        /// entry names registered with `with_archive`, run through the same
914        /// `safe_entry_path` guard the real backends use.
915        fn extract_archive(
916            &self,
917            archive: &Path,
918            dest_dir: &Path,
919            _format: ArchiveFormat,
920            on_entry: &mut dyn FnMut(&Path),
921        ) -> Result<(), OxiNavError> {
922            for raw in self.archive_entries(archive) {
923                let Some(target) = resolve_entry(dest_dir, &raw)? else {
924                    continue;
925                };
926                self.nodes.lock().unwrap().insert(target.clone(), Some(0));
927                on_entry(&target);
928            }
929            Ok(())
930        }
931    }
932
933    #[test]
934    fn create_file_creates_an_empty_file() {
935        let fs = MockFs::with(&[]);
936        let engine = OperationEngine::new(fs);
937
938        engine
939            .execute(&Operation::CreateFile {
940                path: "/new.txt".into(),
941            })
942            .unwrap();
943
944        assert!(engine.exists(Path::new("/new.txt")));
945    }
946
947    #[test]
948    fn create_file_rejects_an_existing_name() {
949        let engine = OperationEngine::new(MockFs::with(&["/taken.txt"]));
950
951        let result = engine.execute(&Operation::CreateFile {
952            path: "/taken.txt".into(),
953        });
954
955        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
956    }
957
958    #[test]
959    fn create_file_rejects_an_existing_directory_name() {
960        let engine = OperationEngine::new(MockFs::tree(&[("/dir", None)]));
961
962        let result = engine.execute(&Operation::CreateFile {
963            path: "/dir".into(),
964        });
965
966        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
967    }
968
969    #[test]
970    fn create_symlink_creates_a_link_at_the_target_path() {
971        let engine = OperationEngine::new(MockFs::with(&["/src.txt"]));
972
973        engine
974            .execute(&Operation::CreateSymlink {
975                source: "/src.txt".into(),
976                link: "/other/link.txt".into(),
977            })
978            .unwrap();
979
980        assert!(engine.exists(Path::new("/other/link.txt")));
981        // The source is linked, not moved.
982        assert!(engine.exists(Path::new("/src.txt")));
983    }
984
985    #[test]
986    fn create_symlink_rejects_a_missing_source() {
987        let engine = OperationEngine::new(MockFs::with(&[]));
988
989        let result = engine.execute(&Operation::CreateSymlink {
990            source: "/gone.txt".into(),
991            link: "/link.txt".into(),
992        });
993
994        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
995        assert!(!engine.exists(Path::new("/link.txt")));
996    }
997
998    #[test]
999    fn create_symlink_rejects_an_existing_link_path() {
1000        let engine = OperationEngine::new(MockFs::with(&["/src.txt", "/link.txt"]));
1001
1002        let result = engine.execute(&Operation::CreateSymlink {
1003            source: "/src.txt".into(),
1004            link: "/link.txt".into(),
1005        });
1006
1007        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
1008    }
1009
1010    #[test]
1011    fn new_single_item_ops_estimate_one_item() {
1012        let engine = OperationEngine::new(MockFs::with(&["/src.txt"]));
1013
1014        assert_eq!(
1015            engine.estimate_totals(&Operation::CreateFile {
1016                path: "/new.txt".into()
1017            }),
1018            (1, 0)
1019        );
1020        assert_eq!(
1021            engine.estimate_totals(&Operation::CreateSymlink {
1022                source: "/src.txt".into(),
1023                link: "/link.txt".into(),
1024            }),
1025            (1, 0)
1026        );
1027    }
1028
1029    fn extract(archive: &str, dest: &str) -> Operation {
1030        Operation::ExtractArchive {
1031            archive: archive.into(),
1032            dest_dir: dest.into(),
1033        }
1034    }
1035
1036    #[test]
1037    fn extract_writes_entries_under_the_destination() {
1038        let fs =
1039            MockFs::tree(&[("/dest", None)]).with_archive("/a.zip", &["one.txt", "nested/two.txt"]);
1040        let engine = OperationEngine::new(fs);
1041
1042        engine.execute(&extract("/a.zip", "/dest")).unwrap();
1043
1044        assert!(engine.exists(Path::new("/dest/one.txt")));
1045        assert!(engine.exists(Path::new("/dest/nested/two.txt")));
1046    }
1047
1048    #[test]
1049    fn extract_rejects_an_unsupported_format_without_writing_anything() {
1050        let fs = MockFs::tree(&[("/dest", None)]).with_archive("/a.rar", &["one.txt"]);
1051        let engine = OperationEngine::new(fs);
1052
1053        let result = engine.execute(&extract("/a.rar", "/dest"));
1054
1055        assert!(matches!(result, Err(OxiNavError::UnsupportedArchive(_))));
1056        // The format is checked before decoding, so nothing was extracted.
1057        assert!(!engine.exists(Path::new("/dest/one.txt")));
1058    }
1059
1060    #[test]
1061    fn extract_rejects_a_missing_archive() {
1062        let engine = OperationEngine::new(MockFs::tree(&[("/dest", None)]));
1063
1064        let result = engine.execute(&extract("/gone.zip", "/dest"));
1065
1066        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
1067    }
1068
1069    #[test]
1070    fn extract_rejects_a_missing_destination() {
1071        let fs = MockFs::with(&[]).with_archive("/a.zip", &["one.txt"]);
1072        let engine = OperationEngine::new(fs);
1073
1074        let result = engine.execute(&extract("/a.zip", "/nope"));
1075
1076        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
1077    }
1078
1079    #[test]
1080    fn extract_refuses_an_entry_escaping_the_destination() {
1081        let fs = MockFs::tree(&[("/dest", None)]).with_archive("/evil.zip", &["../../etc/passwd"]);
1082        let engine = OperationEngine::new(fs);
1083
1084        let result = engine.execute(&extract("/evil.zip", "/dest"));
1085
1086        assert!(matches!(result, Err(OxiNavError::UnsafeArchiveEntry(_))));
1087        assert!(!engine.exists(Path::new("/etc/passwd")));
1088    }
1089
1090    #[test]
1091    fn extract_reports_progress_per_entry_against_a_total_known_up_front() {
1092        let fs = MockFs::tree(&[("/dest", None)])
1093            .with_archive("/a.tar.gz", &["one.txt", "two.txt", "three.txt"]);
1094        let engine = OperationEngine::new(fs);
1095        let cancel = AtomicBool::new(false);
1096        let mut seen: Vec<Progress> = Vec::new();
1097
1098        let outcome = engine
1099            .execute_with_progress(&extract("/a.tar.gz", "/dest"), &cancel, &mut |p| {
1100                seen.push(p)
1101            })
1102            .unwrap();
1103
1104        assert_eq!(outcome, OperationOutcome::Completed);
1105        assert_eq!(seen.len(), 3);
1106        // Totals fixed before the first entry, counts advancing to N of N.
1107        assert!(seen.iter().all(|p| p.items_total == 3));
1108        assert_eq!(
1109            seen.iter().map(|p| p.items_done).collect::<Vec<_>>(),
1110            vec![1, 2, 3]
1111        );
1112    }
1113
1114    #[test]
1115    fn extract_estimates_the_archive_entry_count() {
1116        let fs = MockFs::tree(&[("/dest", None)]).with_archive("/a.zip", &["one.txt", "two.txt"]);
1117        let engine = OperationEngine::new(fs);
1118
1119        assert_eq!(engine.estimate_totals(&extract("/a.zip", "/dest")), (2, 0));
1120    }
1121
1122    #[test]
1123    fn extract_estimate_falls_back_to_one_item_when_unreadable() {
1124        let engine = OperationEngine::new(MockFs::tree(&[("/dest", None)]));
1125
1126        assert_eq!(
1127            engine.estimate_totals(&extract("/gone.zip", "/dest")),
1128            (1, 0)
1129        );
1130    }
1131
1132    /// A scratch directory under the system temp dir, emptied first.
1133    fn scratch(name: &str) -> PathBuf {
1134        let dir = std::env::temp_dir().join(name);
1135        std::fs::remove_dir_all(&dir).ok();
1136        std::fs::create_dir_all(&dir).unwrap();
1137        dir
1138    }
1139
1140    fn write_zip(path: &Path, entries: &[(&str, &[u8])]) {
1141        use std::io::Write;
1142        let file = std::fs::File::create(path).unwrap();
1143        let mut zip = zip::ZipWriter::new(file);
1144        for (name, body) in entries {
1145            zip.start_file(*name, zip::write::SimpleFileOptions::default())
1146                .unwrap();
1147            zip.write_all(body).unwrap();
1148        }
1149        zip.finish().unwrap();
1150    }
1151
1152    fn write_tar_gz(path: &Path, entries: &[(&str, &[u8])]) {
1153        let file = std::fs::File::create(path).unwrap();
1154        let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());
1155        let mut builder = tar::Builder::new(encoder);
1156        for (name, body) in entries {
1157            let mut header = tar::Header::new_gnu();
1158            header.set_size(body.len() as u64);
1159            header.set_mode(0o644);
1160            header.set_cksum();
1161            builder.append_data(&mut header, name, *body).unwrap();
1162        }
1163        builder.into_inner().unwrap().finish().unwrap();
1164    }
1165
1166    #[test]
1167    fn real_zip_is_extracted_with_its_contents_and_nesting() {
1168        let dir = scratch("oxinav_test_extract_zip");
1169        let archive = dir.join("bundle.zip");
1170        write_zip(
1171            &archive,
1172            &[("top.txt", b"one"), ("nested/deep.txt", b"two")],
1173        );
1174        let dest = dir.join("out");
1175        std::fs::create_dir_all(&dest).unwrap();
1176
1177        let engine = OperationEngine::new(StdFilesystem);
1178        engine
1179            .execute(&Operation::ExtractArchive {
1180                archive,
1181                dest_dir: dest.clone(),
1182            })
1183            .unwrap();
1184
1185        assert_eq!(std::fs::read(dest.join("top.txt")).unwrap(), b"one");
1186        assert_eq!(std::fs::read(dest.join("nested/deep.txt")).unwrap(), b"two");
1187
1188        std::fs::remove_dir_all(&dir).ok();
1189    }
1190
1191    #[test]
1192    fn real_tar_gz_is_extracted_with_its_contents() {
1193        let dir = scratch("oxinav_test_extract_targz");
1194        let archive = dir.join("bundle.tar.gz");
1195        write_tar_gz(&archive, &[("a.txt", b"alpha"), ("sub/b.txt", b"beta")]);
1196        let dest = dir.join("out");
1197        std::fs::create_dir_all(&dest).unwrap();
1198
1199        let engine = OperationEngine::new(StdFilesystem);
1200        engine
1201            .execute(&Operation::ExtractArchive {
1202                archive,
1203                dest_dir: dest.clone(),
1204            })
1205            .unwrap();
1206
1207        assert_eq!(std::fs::read(dest.join("a.txt")).unwrap(), b"alpha");
1208        assert_eq!(std::fs::read(dest.join("sub/b.txt")).unwrap(), b"beta");
1209
1210        std::fs::remove_dir_all(&dir).ok();
1211    }
1212
1213    #[test]
1214    fn real_tar_gz_with_a_dot_root_entry_still_extracts() {
1215        // `tar czf x.tar.gz -C dir .` makes `./` the first entry. Treating it
1216        // as an escape aborted the whole archive on entry one; only a
1217        // GNU-tar-built fixture caught it, since tar::Builder emits no root.
1218        let dir = scratch("oxinav_test_extract_dot_root");
1219        let archive = dir.join("rooted.tar.gz");
1220        write_tar_gz(
1221            &archive,
1222            &[
1223                ("./", b""),
1224                ("./top.txt", b"one"),
1225                ("./sub/deep.txt", b"two"),
1226            ],
1227        );
1228        let dest = dir.join("out");
1229        std::fs::create_dir_all(&dest).unwrap();
1230
1231        let engine = OperationEngine::new(StdFilesystem);
1232        engine
1233            .execute(&Operation::ExtractArchive {
1234                archive,
1235                dest_dir: dest.clone(),
1236            })
1237            .unwrap();
1238
1239        assert_eq!(std::fs::read(dest.join("top.txt")).unwrap(), b"one");
1240        assert_eq!(std::fs::read(dest.join("sub/deep.txt")).unwrap(), b"two");
1241
1242        std::fs::remove_dir_all(&dir).ok();
1243    }
1244
1245    #[test]
1246    fn real_zip_slip_entry_never_escapes_the_destination() {
1247        let dir = scratch("oxinav_test_extract_zipslip");
1248        let archive = dir.join("evil.zip");
1249        // A genuine zip-slip payload: the entry name climbs out of dest.
1250        write_zip(&archive, &[("../escaped.txt", b"pwned")]);
1251        let dest = dir.join("out");
1252        std::fs::create_dir_all(&dest).unwrap();
1253
1254        let engine = OperationEngine::new(StdFilesystem);
1255        let result = engine.execute(&Operation::ExtractArchive {
1256            archive,
1257            dest_dir: dest.clone(),
1258        });
1259
1260        assert!(matches!(result, Err(OxiNavError::UnsafeArchiveEntry(_))));
1261        assert!(!dir.join("escaped.txt").exists());
1262
1263        std::fs::remove_dir_all(&dir).ok();
1264    }
1265
1266    #[test]
1267    fn real_entry_count_matches_the_archive() {
1268        let dir = scratch("oxinav_test_extract_count");
1269        let zip_path = dir.join("z.zip");
1270        write_zip(&zip_path, &[("a", b"1"), ("b", b"2"), ("c", b"3")]);
1271        let tgz_path = dir.join("t.tar.gz");
1272        write_tar_gz(&tgz_path, &[("a", b"1"), ("b", b"2")]);
1273
1274        let fs = StdFilesystem;
1275        assert_eq!(
1276            fs.count_archive_entries(&zip_path, ArchiveFormat::Zip)
1277                .unwrap(),
1278            3
1279        );
1280        assert_eq!(
1281            fs.count_archive_entries(&tgz_path, ArchiveFormat::TarGz)
1282                .unwrap(),
1283            2
1284        );
1285
1286        std::fs::remove_dir_all(&dir).ok();
1287    }
1288
1289    #[test]
1290    fn resolve_directory_accepts_an_existing_directory() {
1291        let engine = OperationEngine::new(MockFs::tree(&[("/home/me/code", None)]));
1292
1293        let target = engine
1294            .resolve_directory("/home/me/code", Path::new("/home/me"))
1295            .unwrap();
1296
1297        assert_eq!(target, PathBuf::from("/home/me/code"));
1298    }
1299
1300    #[test]
1301    fn resolve_directory_expands_a_leading_tilde() {
1302        let engine =
1303            OperationEngine::new(MockFs::tree(&[("/home/me", None), ("/home/me/code", None)]));
1304        let home = Path::new("/home/me");
1305
1306        assert_eq!(
1307            engine.resolve_directory("~/code", home).unwrap(),
1308            PathBuf::from("/home/me/code")
1309        );
1310        // `~` alone is the home directory itself.
1311        assert_eq!(
1312            engine.resolve_directory("~", home).unwrap(),
1313            PathBuf::from("/home/me")
1314        );
1315    }
1316
1317    #[test]
1318    fn resolve_directory_leaves_an_interior_tilde_alone() {
1319        let engine = OperationEngine::new(MockFs::tree(&[("/data/back~up", None)]));
1320
1321        assert_eq!(
1322            engine
1323                .resolve_directory("/data/back~up", Path::new("/home/me"))
1324                .unwrap(),
1325            PathBuf::from("/data/back~up")
1326        );
1327    }
1328
1329    #[test]
1330    fn resolve_directory_rejects_a_missing_path() {
1331        let engine = OperationEngine::new(MockFs::tree(&[]));
1332
1333        let result = engine.resolve_directory("/nope", Path::new("/home/me"));
1334
1335        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
1336    }
1337
1338    #[test]
1339    fn resolve_directory_rejects_a_file() {
1340        let engine = OperationEngine::new(MockFs::with(&["/home/me/notes.txt"]));
1341
1342        let result = engine.resolve_directory("/home/me/notes.txt", Path::new("/home/me"));
1343
1344        assert!(matches!(result, Err(OxiNavError::NotADirectory(_))));
1345    }
1346
1347    #[test]
1348    fn resolve_directory_rejects_a_blank_input() {
1349        let engine = OperationEngine::new(MockFs::tree(&[("/home/me", None)]));
1350
1351        assert!(engine
1352            .resolve_directory("   ", Path::new("/home/me"))
1353            .is_err());
1354    }
1355
1356    #[test]
1357    fn resolve_directory_trims_surrounding_whitespace() {
1358        let engine = OperationEngine::new(MockFs::tree(&[("/home/me/code", None)]));
1359
1360        assert_eq!(
1361            engine
1362                .resolve_directory("  /home/me/code  ", Path::new("/home/me"))
1363                .unwrap(),
1364            PathBuf::from("/home/me/code")
1365        );
1366    }
1367
1368    #[test]
1369    fn read_capped_stops_at_the_cap() {
1370        let engine = OperationEngine::new(MockFs::tree(&[("/big", Some(4096))]));
1371
1372        let bytes = engine.read_capped(Path::new("/big"), 100).unwrap();
1373
1374        assert_eq!(bytes.len(), 100);
1375    }
1376
1377    #[test]
1378    fn read_capped_missing_source_errors() {
1379        let engine = OperationEngine::new(MockFs::with(&[]));
1380
1381        let result = engine.read_capped(Path::new("/gone"), 100);
1382
1383        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
1384    }
1385
1386    #[test]
1387    fn copy_missing_source_errors() {
1388        let engine = OperationEngine::new(MockFs::with(&[]));
1389        let result = engine.execute(&Operation::Copy {
1390            src: "/a".into(),
1391            dest: "/b".into(),
1392        });
1393        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
1394    }
1395
1396    #[test]
1397    fn copy_existing_dest_errors() {
1398        let engine = OperationEngine::new(MockFs::with(&["/a", "/b"]));
1399        let result = engine.execute(&Operation::Copy {
1400            src: "/a".into(),
1401            dest: "/b".into(),
1402        });
1403        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
1404    }
1405
1406    #[test]
1407    fn delete_missing_source_errors() {
1408        let engine = OperationEngine::new(MockFs::with(&[]));
1409        let result = engine.execute(&Operation::Delete { path: "/a".into() });
1410        assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
1411    }
1412
1413    #[test]
1414    fn create_dir_existing_errors() {
1415        let engine = OperationEngine::new(MockFs::with(&["/dir"]));
1416        let result = engine.execute(&Operation::CreateDir {
1417            path: "/dir".into(),
1418        });
1419        assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
1420    }
1421
1422    #[test]
1423    fn exists_reports_true_for_present_path() {
1424        let engine = OperationEngine::new(MockFs::with(&["/a"]));
1425        assert!(engine.exists(Path::new("/a")));
1426    }
1427
1428    #[test]
1429    fn exists_reports_false_for_missing_path() {
1430        let engine = OperationEngine::new(MockFs::with(&["/a"]));
1431        assert!(!engine.exists(Path::new("/b")));
1432    }
1433
1434    #[test]
1435    fn recursive_copy_emits_progress_per_file() {
1436        // /src holds 3 files (one nested); totals: 3 items, 60 bytes.
1437        let engine = OperationEngine::new(MockFs::tree(&[
1438            ("/src", None),
1439            ("/src/a.txt", Some(10)),
1440            ("/src/b.txt", Some(20)),
1441            ("/src/sub", None),
1442            ("/src/sub/c.txt", Some(30)),
1443        ]));
1444        let cancel = AtomicBool::new(false);
1445        let mut ticks = Vec::new();
1446        let outcome = engine
1447            .execute_with_progress(
1448                &Operation::Copy {
1449                    src: "/src".into(),
1450                    dest: "/dst".into(),
1451                },
1452                &cancel,
1453                &mut |p| ticks.push(p),
1454            )
1455            .unwrap();
1456
1457        assert_eq!(outcome, OperationOutcome::Completed);
1458        // One tick per file, in item order regardless of walk order.
1459        assert_eq!(
1460            ticks.iter().map(|p| p.items_done).collect::<Vec<_>>(),
1461            vec![1, 2, 3]
1462        );
1463        // Totals are fixed up front on every tick.
1464        assert!(ticks
1465            .iter()
1466            .all(|p| p.items_total == 3 && p.bytes_total == 60));
1467        // bytes_done accumulates monotonically to the total.
1468        assert!(ticks.windows(2).all(|w| w[0].bytes_done <= w[1].bytes_done));
1469        assert_eq!(ticks.last().unwrap().bytes_done, 60);
1470        // Every file landed under the destination.
1471        assert!(engine.exists(Path::new("/dst/a.txt")));
1472        assert!(engine.exists(Path::new("/dst/b.txt")));
1473        assert!(engine.exists(Path::new("/dst/sub/c.txt")));
1474    }
1475
1476    #[test]
1477    fn estimate_totals_counts_files_and_bytes() {
1478        let engine = OperationEngine::new(MockFs::tree(&[
1479            ("/src", None),
1480            ("/src/a.txt", Some(10)),
1481            ("/src/sub", None),
1482            ("/src/sub/b.txt", Some(30)),
1483        ]));
1484        // A directory: descendant files and their summed bytes.
1485        assert_eq!(
1486            engine.estimate_totals(&Operation::Copy {
1487                src: "/src".into(),
1488                dest: "/dst".into(),
1489            }),
1490            (2, 40)
1491        );
1492        // A single file: one item, its own size.
1493        assert_eq!(
1494            engine.estimate_totals(&Operation::Delete {
1495                path: "/src/a.txt".into(),
1496            }),
1497            (1, 10)
1498        );
1499    }
1500
1501    #[test]
1502    fn cancel_stops_before_next_item() {
1503        let engine = OperationEngine::new(MockFs::tree(&[
1504            ("/src", None),
1505            ("/src/a", Some(1)),
1506            ("/src/b", Some(1)),
1507            ("/src/c", Some(1)),
1508        ]));
1509        let cancel = Arc::new(AtomicBool::new(false));
1510        let flag = cancel.clone();
1511        let mut ticks = 0usize;
1512        let outcome = engine
1513            .execute_with_progress(
1514                &Operation::Copy {
1515                    src: "/src".into(),
1516                    dest: "/dst".into(),
1517                },
1518                &cancel,
1519                // Cancel right after the first item completes.
1520                &mut |_| {
1521                    ticks += 1;
1522                    flag.store(true, Ordering::Relaxed);
1523                },
1524            )
1525            .unwrap();
1526
1527        assert_eq!(outcome, OperationOutcome::Cancelled);
1528        // Stopped before starting the second item.
1529        assert_eq!(ticks, 1);
1530        // Exactly one of the three files was copied; the rest were left alone.
1531        let copied = ["/dst/a", "/dst/b", "/dst/c"]
1532            .iter()
1533            .filter(|p| engine.exists(&PathBuf::from(*p)))
1534            .count();
1535        assert_eq!(copied, 1);
1536    }
1537}