1use crate::archive::{
2 classify_entry_path, detect_format, ArchiveEntry, ArchiveFormat, EntryKind, EntryTarget,
3};
4use crate::error::OxiNavError;
5use crate::pane::matches_filter;
6use crate::search::{pattern_error, snippet, SearchEnd, SearchHit, SearchQuery, MAX_HITS};
7use std::ops::ControlFlow;
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, Ordering};
10
11#[derive(Debug, Clone)]
12pub enum Operation {
13 Copy {
14 src: PathBuf,
15 dest: PathBuf,
16 },
17 Move {
18 src: PathBuf,
19 dest: PathBuf,
20 },
21 Rename {
22 src: PathBuf,
23 dest: PathBuf,
24 },
25 Delete {
26 path: PathBuf,
27 },
28 CreateDir {
29 path: PathBuf,
30 },
31 CreateFile {
32 path: PathBuf,
33 },
34 CreateSymlink {
35 source: PathBuf,
36 link: PathBuf,
37 },
38 ExtractArchive {
39 archive: PathBuf,
40 dest_dir: PathBuf,
41 },
42 CreateArchive {
45 sources: Vec<PathBuf>,
46 base_dir: PathBuf,
47 archive: PathBuf,
48 },
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum OperationStatus {
53 Pending,
54 InProgress,
55 Done,
56 Failed(String),
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Progress {
65 pub current: PathBuf,
67 pub items_done: usize,
69 pub items_total: usize,
71 pub bytes_done: u64,
73 pub bytes_total: u64,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum OperationOutcome {
80 Completed,
82 Cancelled,
84}
85
86pub trait Filesystem: Send + Sync {
87 fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError>;
88 fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError>;
89 fn delete(&self, path: &Path) -> Result<(), OxiNavError>;
90 fn create_dir(&self, path: &Path) -> Result<(), OxiNavError>;
91 fn create_file(&self, path: &Path) -> Result<(), OxiNavError>;
93 fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError>;
95 fn exists(&self, path: &Path) -> bool;
96 fn is_symlink(&self, path: &Path) -> bool;
99 fn is_dir(&self, path: &Path) -> bool;
101 fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError>;
103 fn size(&self, path: &Path) -> u64;
105 fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError>;
109 fn count_archive_entries(
114 &self,
115 archive: &Path,
116 format: ArchiveFormat,
117 ) -> Result<usize, OxiNavError>;
118 fn extract_archive(
122 &self,
123 archive: &Path,
124 dest_dir: &Path,
125 format: ArchiveFormat,
126 on_entry: &mut dyn FnMut(&Path),
127 ) -> Result<(), OxiNavError>;
128 fn write_archive(
133 &self,
134 archive: &Path,
135 format: ArchiveFormat,
136 entries: &[ArchiveEntry],
137 on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
138 ) -> Result<ControlFlow<()>, OxiNavError>;
139 fn search(
145 &self,
146 root: &Path,
147 query: &SearchQuery,
148 cancel: &AtomicBool,
149 on_hit: &mut dyn FnMut(SearchHit) -> ControlFlow<()>,
150 ) -> Result<ControlFlow<()>, OxiNavError>;
151}
152
153pub struct OperationEngine<F: Filesystem> {
154 fs: F,
155}
156
157#[derive(Debug, Clone, Copy)]
158pub struct StdFilesystem;
159
160impl Filesystem for StdFilesystem {
161 fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
162 if src.is_dir() {
163 copy_dir_recursive(src, dest).map_err(|source| OxiNavError::Io {
164 path: dest.to_path_buf(),
165 source,
166 })
167 } else {
168 std::fs::copy(src, dest)
169 .map(|_| ())
170 .map_err(|source| OxiNavError::Io {
171 path: dest.to_path_buf(),
172 source,
173 })
174 }
175 }
176
177 fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
178 std::fs::rename(src, dest).map_err(|source| OxiNavError::Io {
179 path: dest.to_path_buf(),
180 source,
181 })
182 }
183
184 fn delete(&self, path: &Path) -> Result<(), OxiNavError> {
185 let result = if path.is_dir() {
186 std::fs::remove_dir_all(path)
187 } else {
188 std::fs::remove_file(path)
189 };
190
191 result.map_err(|source| OxiNavError::Io {
192 path: path.to_path_buf(),
193 source,
194 })
195 }
196
197 fn create_dir(&self, path: &Path) -> Result<(), OxiNavError> {
198 std::fs::create_dir(path).map_err(|source| OxiNavError::Io {
199 path: path.to_path_buf(),
200 source,
201 })
202 }
203
204 fn create_file(&self, path: &Path) -> Result<(), OxiNavError> {
205 std::fs::OpenOptions::new()
208 .write(true)
209 .create_new(true)
210 .open(path)
211 .map(|_| ())
212 .map_err(|source| OxiNavError::Io {
213 path: path.to_path_buf(),
214 source,
215 })
216 }
217
218 fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError> {
219 #[cfg(unix)]
220 let result = std::os::unix::fs::symlink(source, link);
221 #[cfg(windows)]
225 let result = if source.is_dir() {
226 std::os::windows::fs::symlink_dir(source, link)
227 } else {
228 std::os::windows::fs::symlink_file(source, link)
229 };
230 result.map_err(|source| OxiNavError::Io {
231 path: link.to_path_buf(),
232 source,
233 })
234 }
235
236 fn exists(&self, path: &Path) -> bool {
237 path.exists()
238 }
239
240 fn is_symlink(&self, path: &Path) -> bool {
241 path.is_symlink()
242 }
243
244 fn is_dir(&self, path: &Path) -> bool {
245 path.is_dir()
246 }
247
248 fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError> {
249 let entries = std::fs::read_dir(path).map_err(|source| OxiNavError::Io {
250 path: path.to_path_buf(),
251 source,
252 })?;
253 let mut out = Vec::new();
254 for entry in entries {
255 let entry = entry.map_err(|source| OxiNavError::Io {
256 path: path.to_path_buf(),
257 source,
258 })?;
259 out.push(entry.path());
260 }
261 Ok(out)
262 }
263
264 fn size(&self, path: &Path) -> u64 {
265 std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
266 }
267
268 fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
269 use std::io::Read;
270
271 let io_error = |source| OxiNavError::Io {
272 path: path.to_path_buf(),
273 source,
274 };
275 let file = std::fs::File::open(path).map_err(io_error)?;
276 let mut buffer = Vec::new();
277 file.take(max as u64)
278 .read_to_end(&mut buffer)
279 .map_err(io_error)?;
280 Ok(buffer)
281 }
282
283 fn count_archive_entries(
284 &self,
285 archive: &Path,
286 format: ArchiveFormat,
287 ) -> Result<usize, OxiNavError> {
288 let file = open_archive(archive)?;
289 match format {
290 ArchiveFormat::Zip => {
291 let zip = zip::ZipArchive::new(file).map_err(|e| archive_error(archive, e))?;
292 Ok(zip.len())
293 }
294 ArchiveFormat::Tar => {
295 let mut tar = tar::Archive::new(file);
296 let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
297 Ok(entries.count())
298 }
299 ArchiveFormat::TarGz => {
300 let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
301 let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
302 Ok(entries.count())
303 }
304 }
305 }
306
307 fn extract_archive(
308 &self,
309 archive: &Path,
310 dest_dir: &Path,
311 format: ArchiveFormat,
312 on_entry: &mut dyn FnMut(&Path),
313 ) -> Result<(), OxiNavError> {
314 let file = open_archive(archive)?;
315 match format {
316 ArchiveFormat::Zip => {
317 let mut zip = zip::ZipArchive::new(file).map_err(|e| archive_error(archive, e))?;
318 for index in 0..zip.len() {
319 let mut entry = zip.by_index(index).map_err(|e| archive_error(archive, e))?;
320 let raw = entry.name().to_string();
321 let Some(target) = resolve_entry(dest_dir, &raw)? else {
322 continue;
323 };
324
325 if entry.is_dir() {
326 create_dir_all(&target)?;
327 } else {
328 if let Some(parent) = target.parent() {
329 create_dir_all(parent)?;
330 }
331 let mut out =
332 std::fs::File::create(&target).map_err(|source| OxiNavError::Io {
333 path: target.clone(),
334 source,
335 })?;
336 std::io::copy(&mut entry, &mut out).map_err(|source| OxiNavError::Io {
337 path: target.clone(),
338 source,
339 })?;
340 }
341 #[cfg(unix)]
345 if let Some(mode) = entry.unix_mode() {
346 use std::os::unix::fs::PermissionsExt;
347 let permissions = std::fs::Permissions::from_mode(mode & 0o777);
348 std::fs::set_permissions(&target, permissions).map_err(|source| {
349 OxiNavError::Io {
350 path: target.clone(),
351 source,
352 }
353 })?;
354 }
355 on_entry(&target);
356 }
357 Ok(())
358 }
359 ArchiveFormat::Tar => extract_tar(tar::Archive::new(file), archive, dest_dir, on_entry),
360 ArchiveFormat::TarGz => extract_tar(
361 tar::Archive::new(flate2::read::GzDecoder::new(file)),
362 archive,
363 dest_dir,
364 on_entry,
365 ),
366 }
367 }
368
369 fn write_archive(
373 &self,
374 archive: &Path,
375 format: ArchiveFormat,
376 entries: &[ArchiveEntry],
377 on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
378 ) -> Result<ControlFlow<()>, OxiNavError> {
379 let name = archive.file_name().unwrap_or_default().to_string_lossy();
380 let temp = archive.with_file_name(format!(".{name}.oxinav-partial"));
381 let io_error = |path: &Path| {
382 let path = path.to_path_buf();
383 move |source| OxiNavError::Io { path, source }
384 };
385
386 let written = (|| {
387 let file = std::fs::OpenOptions::new()
388 .write(true)
389 .create_new(true)
390 .open(&temp)
391 .map_err(io_error(&temp))?;
392 let file = match format {
393 ArchiveFormat::Zip => write_zip(file, archive, entries, on_entry)?,
394 ArchiveFormat::Tar => write_tar(file, archive, entries, on_entry)?,
395 ArchiveFormat::TarGz => {
396 let encoder =
397 flate2::write::GzEncoder::new(file, flate2::Compression::default());
398 match write_tar(encoder, archive, entries, on_entry)? {
399 Some(encoder) => Some(encoder.finish().map_err(io_error(&temp))?),
400 None => None,
401 }
402 }
403 };
404 let Some(file) = file else {
405 return Ok(ControlFlow::Break(()));
406 };
407 file.sync_all().map_err(io_error(&temp))?;
408 std::fs::rename(&temp, archive).map_err(io_error(archive))?;
409 Ok(ControlFlow::Continue(()))
410 })();
411
412 if !matches!(written, Ok(ControlFlow::Continue(()))) {
413 let _ = std::fs::remove_file(&temp);
414 }
415 written
416 }
417
418 fn search(
423 &self,
424 root: &Path,
425 query: &SearchQuery,
426 cancel: &AtomicBool,
427 on_hit: &mut dyn FnMut(SearchHit) -> ControlFlow<()>,
428 ) -> Result<ControlFlow<()>, OxiNavError> {
429 use grep_regex::RegexMatcherBuilder;
430 use grep_searcher::{sinks::Lossy, BinaryDetection, SearcherBuilder};
431
432 let matcher = RegexMatcherBuilder::new()
433 .case_insensitive(query.case_insensitive)
434 .line_terminator(Some(b'\n'))
436 .build(&query.pattern)
437 .map_err(|error| OxiNavError::InvalidPattern(pattern_error(&error.to_string())))?;
438 let mut searcher = SearcherBuilder::new()
439 .binary_detection(BinaryDetection::quit(b'\0'))
440 .line_number(true)
441 .build();
442 let walker = ignore::WalkBuilder::new(root)
443 .hidden(!query.include_hidden)
444 .sort_by_file_name(|a, b| a.cmp(b))
445 .build();
446
447 for entry in walker {
448 if cancel.load(Ordering::Relaxed) {
449 return Ok(ControlFlow::Break(()));
450 }
451 let Ok(entry) = entry else { continue };
452 if !entry.file_type().is_some_and(|kind| kind.is_file()) {
453 continue;
454 }
455 if let Some(glob) = &query.name_glob {
456 let name = entry.file_name().to_string_lossy();
457 if !matches_filter(&name, glob) {
458 continue;
459 }
460 }
461
462 let mut flow = ControlFlow::Continue(());
463 let path = entry.path();
464 let _ = searcher.search_path(
466 &matcher,
467 path,
468 Lossy(|line, text| {
469 flow = on_hit(SearchHit {
470 path: path.to_path_buf(),
471 line,
472 text: snippet(text),
473 });
474 Ok(flow.is_continue())
475 }),
476 );
477 if flow.is_break() {
478 return Ok(ControlFlow::Break(()));
479 }
480 }
481 Ok(ControlFlow::Continue(()))
482 }
483}
484
485fn zip_entry_name(entry: &ArchiveEntry) -> Result<String, OxiNavError> {
488 let parts: Option<Vec<&str>> = entry
489 .name
490 .components()
491 .map(|part| part.as_os_str().to_str())
492 .collect();
493 parts
494 .map(|parts| parts.join("/"))
495 .ok_or_else(|| OxiNavError::Io {
496 path: entry.source.clone(),
497 source: std::io::Error::other("zip entry names must be UTF-8"),
498 })
499}
500
501fn unix_mode(path: &Path) -> Option<u32> {
503 #[cfg(unix)]
504 {
505 use std::os::unix::fs::PermissionsExt;
506 std::fs::symlink_metadata(path)
507 .ok()
508 .map(|metadata| metadata.permissions().mode() & 0o7777)
509 }
510 #[cfg(not(unix))]
511 {
512 let _ = path;
513 None
514 }
515}
516
517fn zip_time(path: &Path) -> Option<zip::DateTime> {
521 use chrono::{Datelike, Timelike};
522 let modified = std::fs::symlink_metadata(path).ok()?.modified().ok()?;
523 let local: chrono::DateTime<chrono::Local> = modified.into();
524 zip::DateTime::from_date_and_time(
525 u16::try_from(local.year()).ok()?,
526 local.month() as u8,
527 local.day() as u8,
528 local.hour() as u8,
529 local.minute() as u8,
530 local.second() as u8,
531 )
532 .ok()
533}
534
535fn write_zip(
537 file: std::fs::File,
538 archive: &Path,
539 entries: &[ArchiveEntry],
540 on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
541) -> Result<Option<std::fs::File>, OxiNavError> {
542 use zip::write::SimpleFileOptions;
543
544 let mut zip = zip::ZipWriter::new(file);
545 for entry in entries {
546 let name = zip_entry_name(entry)?;
547 let source_error = |source| OxiNavError::Io {
548 path: entry.source.clone(),
549 source,
550 };
551 let mut options =
552 SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
553 if let Some(mode) = unix_mode(&entry.source) {
554 options = options.unix_permissions(mode);
555 }
556 if let Some(time) = zip_time(&entry.source) {
557 options = options.last_modified_time(time);
558 }
559 match entry.kind {
560 EntryKind::Dir => zip
561 .add_directory(name, options)
562 .map_err(|e| archive_error(archive, e))?,
563 EntryKind::Symlink => {
564 let target = std::fs::read_link(&entry.source).map_err(source_error)?;
565 zip.add_symlink(name, target.to_string_lossy(), options)
566 .map_err(|e| archive_error(archive, e))?;
567 }
568 EntryKind::File => {
569 let mut source = std::fs::File::open(&entry.source).map_err(source_error)?;
570 let len = source.metadata().map_err(source_error)?.len();
571 let options = options.large_file(len >= u64::from(u32::MAX));
574 zip.start_file(name, options)
575 .map_err(|e| archive_error(archive, e))?;
576 std::io::copy(&mut source, &mut zip).map_err(source_error)?;
577 }
578 }
579 if on_entry(&entry.source).is_break() {
580 return Ok(None);
581 }
582 }
583 zip.finish()
584 .map(Some)
585 .map_err(|e| archive_error(archive, e))
586}
587
588fn write_tar<W: std::io::Write>(
591 writer: W,
592 archive: &Path,
593 entries: &[ArchiveEntry],
594 on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
595) -> Result<Option<W>, OxiNavError> {
596 let mut builder = tar::Builder::new(writer);
597 builder.follow_symlinks(false);
598 for entry in entries {
599 builder
600 .append_path_with_name(&entry.source, &entry.name)
601 .map_err(|source| OxiNavError::Io {
602 path: entry.source.clone(),
603 source,
604 })?;
605 if on_entry(&entry.source).is_break() {
606 return Ok(None);
607 }
608 }
609 builder
611 .into_inner()
612 .map(Some)
613 .map_err(|source| OxiNavError::Io {
614 path: archive.to_path_buf(),
615 source,
616 })
617}
618
619fn expand_home(input: &str, home: &Path) -> PathBuf {
622 match input.strip_prefix('~') {
623 Some("") => home.to_path_buf(),
624 Some(rest) => match rest.strip_prefix('/') {
625 Some(relative) => home.join(relative),
626 None => PathBuf::from(input),
628 },
629 None => PathBuf::from(input),
630 }
631}
632
633fn open_archive(archive: &Path) -> Result<std::fs::File, OxiNavError> {
634 std::fs::File::open(archive).map_err(|source| OxiNavError::Io {
635 path: archive.to_path_buf(),
636 source,
637 })
638}
639
640fn archive_error<E: std::fmt::Display>(archive: &Path, error: E) -> OxiNavError {
643 OxiNavError::Io {
644 path: archive.to_path_buf(),
645 source: std::io::Error::other(error.to_string()),
646 }
647}
648
649fn create_dir_all(path: &Path) -> Result<(), OxiNavError> {
650 std::fs::create_dir_all(path).map_err(|source| OxiNavError::Io {
651 path: path.to_path_buf(),
652 source,
653 })
654}
655
656fn resolve_entry(dest_dir: &Path, raw: &str) -> Result<Option<PathBuf>, OxiNavError> {
660 match classify_entry_path(Path::new(raw)) {
661 EntryTarget::Within(relative) => Ok(Some(dest_dir.join(relative))),
662 EntryTarget::ArchiveRoot => Ok(None),
663 EntryTarget::Escaping => Err(OxiNavError::UnsafeArchiveEntry(raw.to_string())),
664 }
665}
666
667fn extract_tar<R: std::io::Read>(
668 mut tar: tar::Archive<R>,
669 archive: &Path,
670 dest_dir: &Path,
671 on_entry: &mut dyn FnMut(&Path),
672) -> Result<(), OxiNavError> {
673 let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
674 for entry in entries {
675 let mut entry = entry.map_err(|e| archive_error(archive, e))?;
676 let raw = entry
677 .path()
678 .map_err(|e| archive_error(archive, e))?
679 .to_string_lossy()
680 .into_owned();
681 let Some(target) = resolve_entry(dest_dir, &raw)? else {
682 continue;
683 };
684
685 if entry.header().entry_type().is_dir() {
686 create_dir_all(&target)?;
687 } else {
688 if let Some(parent) = target.parent() {
689 create_dir_all(parent)?;
690 }
691 entry
694 .unpack(&target)
695 .map_err(|e| archive_error(archive, e))?;
696 }
697 on_entry(&target);
698 }
699 Ok(())
700}
701
702impl<F: Filesystem> OperationEngine<F> {
703 pub fn new(fs: F) -> Self {
704 Self { fs }
705 }
706
707 pub fn exists(&self, path: &Path) -> bool {
708 self.fs.exists(path)
709 }
710
711 pub fn resolve_directory(&self, input: &str, home: &Path) -> Result<PathBuf, OxiNavError> {
721 let trimmed = input.trim();
722 if trimmed.is_empty() {
723 return Err(OxiNavError::SourceNotFound(PathBuf::from(trimmed)));
724 }
725
726 let expanded = expand_home(trimmed, home);
727
728 if !self.fs.exists(&expanded) {
729 return Err(OxiNavError::SourceNotFound(expanded));
730 }
731 if !self.fs.is_dir(&expanded) {
732 return Err(OxiNavError::NotADirectory(expanded));
733 }
734 Ok(expanded)
735 }
736
737 fn check_extractable(
741 &self,
742 archive: &Path,
743 dest_dir: &Path,
744 ) -> Result<ArchiveFormat, OxiNavError> {
745 if !self.fs.exists(archive) {
746 return Err(OxiNavError::SourceNotFound(archive.to_path_buf()));
747 }
748 if !self.fs.exists(dest_dir) {
749 return Err(OxiNavError::SourceNotFound(dest_dir.to_path_buf()));
750 }
751 detect_format(archive).ok_or_else(|| OxiNavError::UnsupportedArchive(archive.to_path_buf()))
752 }
753
754 fn check_packable(
758 &self,
759 sources: &[PathBuf],
760 archive: &Path,
761 ) -> Result<ArchiveFormat, OxiNavError> {
762 let format = detect_format(archive)
763 .ok_or_else(|| OxiNavError::UnsupportedArchive(archive.to_path_buf()))?;
764 if self.fs.exists(archive) || self.fs.is_symlink(archive) {
765 return Err(OxiNavError::DestinationExists(archive.to_path_buf()));
766 }
767 if let Some(missing) = sources
768 .iter()
769 .find(|source| !self.fs.exists(source) && !self.fs.is_symlink(source))
770 {
771 return Err(OxiNavError::SourceNotFound(missing.clone()));
772 }
773 Ok(format)
774 }
775
776 fn archive_entries(
780 &self,
781 sources: &[PathBuf],
782 base_dir: &Path,
783 ) -> Result<Vec<ArchiveEntry>, OxiNavError> {
784 let mut entries = Vec::new();
785 for source in sources {
786 self.collect_entries(source, base_dir, &mut entries)?;
787 }
788 Ok(entries)
789 }
790
791 fn collect_entries(
792 &self,
793 path: &Path,
794 base_dir: &Path,
795 entries: &mut Vec<ArchiveEntry>,
796 ) -> Result<(), OxiNavError> {
797 let name = match path.strip_prefix(base_dir) {
798 Ok(relative) => relative.to_path_buf(),
799 Err(_) => PathBuf::from(path.file_name().unwrap_or_default()),
802 };
803 let kind = if self.fs.is_symlink(path) {
804 EntryKind::Symlink
805 } else if self.fs.is_dir(path) {
806 EntryKind::Dir
807 } else {
808 EntryKind::File
809 };
810 entries.push(ArchiveEntry {
811 source: path.to_path_buf(),
812 name,
813 kind,
814 });
815 if kind == EntryKind::Dir {
816 let mut children = self.fs.read_dir(path)?;
817 children.sort();
818 for child in children {
819 self.collect_entries(&child, base_dir, entries)?;
820 }
821 }
822 Ok(())
823 }
824
825 pub fn search(
829 &self,
830 root: &Path,
831 query: &SearchQuery,
832 cancel: &AtomicBool,
833 on_hit: &mut dyn FnMut(SearchHit),
834 ) -> Result<SearchEnd, OxiNavError> {
835 let mut count = 0;
836 let mut capped = false;
837 let flow = self.fs.search(root, query, cancel, &mut |hit| {
838 if count == MAX_HITS {
839 capped = true;
840 return ControlFlow::Break(());
841 }
842 count += 1;
843 on_hit(hit);
844 ControlFlow::Continue(())
845 })?;
846 Ok(if capped {
847 SearchEnd::Capped
848 } else if flow.is_break() {
849 SearchEnd::Stopped
850 } else {
851 SearchEnd::Finished
852 })
853 }
854
855 pub fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
856 if !self.fs.exists(path) {
857 return Err(OxiNavError::SourceNotFound(path.to_path_buf()));
858 }
859 self.fs.read_capped(path, max)
860 }
861
862 pub fn execute(&self, op: &Operation) -> Result<(), OxiNavError> {
863 match op {
864 Operation::Copy { src, dest } => {
865 if !self.fs.exists(src) {
866 return Err(OxiNavError::SourceNotFound(src.clone()));
867 }
868 if self.fs.exists(dest) {
869 return Err(OxiNavError::DestinationExists(dest.clone()));
870 }
871 self.fs.copy(src, dest)
872 }
873 Operation::Move { src, dest } => {
874 if !self.fs.exists(src) {
875 return Err(OxiNavError::SourceNotFound(src.clone()));
876 }
877 if self.fs.exists(dest) {
878 return Err(OxiNavError::DestinationExists(dest.clone()));
879 }
880 match self.fs.rename(src, dest) {
882 Ok(()) => Ok(()),
883 Err(_) => {
884 self.fs.copy(src, dest)?;
885 self.fs.delete(src)
886 }
887 }
888 }
889 Operation::Rename { src, dest } => {
890 if !self.fs.exists(src) {
891 return Err(OxiNavError::SourceNotFound(src.clone()));
892 }
893 if self.fs.exists(dest) {
894 return Err(OxiNavError::DestinationExists(dest.clone()));
895 }
896 self.fs.rename(src, dest)
897 }
898 Operation::Delete { path } => {
899 if !self.fs.exists(path) {
900 return Err(OxiNavError::SourceNotFound(path.clone()));
901 }
902 self.fs.delete(path)
903 }
904 Operation::CreateDir { path } => {
905 if self.fs.exists(path) {
906 return Err(OxiNavError::DestinationExists(path.clone()));
907 }
908 self.fs.create_dir(path)
909 }
910 Operation::CreateFile { path } => {
911 if self.fs.exists(path) {
912 return Err(OxiNavError::DestinationExists(path.clone()));
913 }
914 self.fs.create_file(path)
915 }
916 Operation::CreateSymlink { source, link } => {
917 if !self.fs.exists(source) {
918 return Err(OxiNavError::SourceNotFound(source.clone()));
919 }
920 if self.fs.exists(link) {
921 return Err(OxiNavError::DestinationExists(link.clone()));
922 }
923 self.fs.create_symlink(source, link)
924 }
925 Operation::ExtractArchive { archive, dest_dir } => {
926 let format = self.check_extractable(archive, dest_dir)?;
927 self.fs
928 .extract_archive(archive, dest_dir, format, &mut |_| {})
929 }
930 Operation::CreateArchive { .. } => self
931 .execute_with_progress(op, &AtomicBool::new(false), &mut |_| {})
932 .map(|_| ()),
933 }
934 }
935
936 pub fn execute_with_progress(
949 &self,
950 op: &Operation,
951 cancel: &AtomicBool,
952 on_progress: &mut dyn FnMut(Progress),
953 ) -> Result<OperationOutcome, OxiNavError> {
954 match op {
955 Operation::Copy { src, dest } => {
956 if !self.fs.exists(src) {
957 return Err(OxiNavError::SourceNotFound(src.clone()));
958 }
959 if self.fs.exists(dest) {
960 return Err(OxiNavError::DestinationExists(dest.clone()));
961 }
962 let (items_total, bytes_total) = self.walk_totals(src);
963 let mut state = ProgressState::new(items_total, bytes_total);
964 self.copy_recursive(src, dest, cancel, &mut state, on_progress)?;
965 Ok(outcome(cancel))
966 }
967 Operation::Delete { path } => {
968 if !self.fs.exists(path) {
969 return Err(OxiNavError::SourceNotFound(path.clone()));
970 }
971 let (items_total, bytes_total) = self.walk_totals(path);
972 let mut state = ProgressState::new(items_total, bytes_total);
973 self.delete_recursive(path, cancel, &mut state, on_progress)?;
974 Ok(outcome(cancel))
975 }
976 Operation::Move { src, dest } => {
977 if !self.fs.exists(src) {
978 return Err(OxiNavError::SourceNotFound(src.clone()));
979 }
980 if self.fs.exists(dest) {
981 return Err(OxiNavError::DestinationExists(dest.clone()));
982 }
983 let (items_total, bytes_total) = self.walk_totals(src);
984 if self.fs.rename(src, dest).is_ok() {
986 on_progress(Progress {
987 current: src.clone(),
988 items_done: items_total,
989 items_total,
990 bytes_done: bytes_total,
991 bytes_total,
992 });
993 return Ok(OperationOutcome::Completed);
994 }
995 let mut state = ProgressState::new(items_total, bytes_total);
997 self.copy_recursive(src, dest, cancel, &mut state, on_progress)?;
998 if cancel.load(Ordering::Relaxed) {
999 return Ok(OperationOutcome::Cancelled);
1000 }
1001 self.fs.delete(src)?;
1002 Ok(OperationOutcome::Completed)
1003 }
1004 Operation::Rename { dest, .. } => {
1006 self.execute(op)?;
1007 on_progress(single_tick(dest.clone()));
1008 Ok(OperationOutcome::Completed)
1009 }
1010 Operation::CreateSymlink { link, .. } => {
1011 self.execute(op)?;
1012 on_progress(single_tick(link.clone()));
1013 Ok(OperationOutcome::Completed)
1014 }
1015 Operation::ExtractArchive { archive, dest_dir } => {
1018 let format = self.check_extractable(archive, dest_dir)?;
1019 let items_total = self.fs.count_archive_entries(archive, format)?;
1020 let mut items_done = 0;
1021
1022 self.fs
1023 .extract_archive(archive, dest_dir, format, &mut |written| {
1024 items_done += 1;
1025 on_progress(Progress {
1026 current: written.to_path_buf(),
1027 items_done,
1028 items_total,
1029 bytes_done: 0,
1030 bytes_total: 0,
1031 });
1032 })?;
1033
1034 Ok(OperationOutcome::Completed)
1035 }
1036 Operation::CreateDir { path } | Operation::CreateFile { path } => {
1037 self.execute(op)?;
1038 on_progress(single_tick(path.clone()));
1039 Ok(OperationOutcome::Completed)
1040 }
1041 Operation::CreateArchive {
1045 sources,
1046 base_dir,
1047 archive,
1048 } => {
1049 let format = self.check_packable(sources, archive)?;
1050 let entries = self.archive_entries(sources, base_dir)?;
1051 let sizes: Vec<u64> = entries
1052 .iter()
1053 .map(|entry| match entry.kind {
1054 EntryKind::File => self.fs.size(&entry.source),
1055 EntryKind::Dir | EntryKind::Symlink => 0,
1056 })
1057 .collect();
1058 let mut state = ProgressState::new(entries.len(), sizes.iter().sum());
1059 if cancel.load(Ordering::Relaxed) {
1060 return Ok(OperationOutcome::Cancelled);
1061 }
1062
1063 let flow = self
1064 .fs
1065 .write_archive(archive, format, &entries, &mut |written| {
1066 state.advance(sizes[state.items_done]);
1067 on_progress(state.snapshot(written));
1068 if cancel.load(Ordering::Relaxed) {
1069 ControlFlow::Break(())
1070 } else {
1071 ControlFlow::Continue(())
1072 }
1073 })?;
1074 Ok(if flow.is_break() {
1075 OperationOutcome::Cancelled
1076 } else {
1077 OperationOutcome::Completed
1078 })
1079 }
1080 }
1081 }
1082
1083 pub fn estimate_totals(&self, op: &Operation) -> (usize, u64) {
1087 match op {
1088 Operation::Copy { src, .. } | Operation::Move { src, .. } => self.walk_totals(src),
1089 Operation::Delete { path } => self.walk_totals(path),
1090 Operation::Rename { .. }
1091 | Operation::CreateDir { .. }
1092 | Operation::CreateFile { .. }
1093 | Operation::CreateSymlink { .. } => (1, 0),
1094 Operation::ExtractArchive { archive, dest_dir } => self
1098 .check_extractable(archive, dest_dir)
1099 .and_then(|format| self.fs.count_archive_entries(archive, format))
1100 .map(|items| (items, 0))
1101 .unwrap_or((1, 0)),
1102 Operation::CreateArchive {
1103 sources, base_dir, ..
1104 } => self
1105 .archive_entries(sources, base_dir)
1106 .map(|entries| {
1107 let bytes = entries
1108 .iter()
1109 .filter(|entry| entry.kind == EntryKind::File)
1110 .map(|entry| self.fs.size(&entry.source))
1111 .sum();
1112 (entries.len(), bytes)
1113 })
1114 .unwrap_or((1, 0)),
1115 }
1116 }
1117
1118 fn walk_totals(&self, path: &Path) -> (usize, u64) {
1121 if self.fs.is_dir(path) {
1122 let mut items = 0;
1123 let mut bytes = 0;
1124 if let Ok(children) = self.fs.read_dir(path) {
1125 for child in &children {
1126 let (i, b) = self.walk_totals(child);
1127 items += i;
1128 bytes += b;
1129 }
1130 }
1131 (items, bytes)
1132 } else {
1133 (1, self.fs.size(path))
1134 }
1135 }
1136
1137 fn copy_recursive(
1138 &self,
1139 src: &Path,
1140 dest: &Path,
1141 cancel: &AtomicBool,
1142 state: &mut ProgressState,
1143 on_progress: &mut dyn FnMut(Progress),
1144 ) -> Result<(), OxiNavError> {
1145 if cancel.load(Ordering::Relaxed) {
1146 return Ok(());
1147 }
1148 if self.fs.is_dir(src) {
1149 self.fs.create_dir(dest)?;
1150 for child in self.fs.read_dir(src)? {
1151 if cancel.load(Ordering::Relaxed) {
1152 return Ok(());
1153 }
1154 let child_dest = match child.file_name() {
1155 Some(name) => dest.join(name),
1156 None => dest.to_path_buf(),
1157 };
1158 self.copy_recursive(&child, &child_dest, cancel, state, on_progress)?;
1159 }
1160 } else {
1161 self.fs.copy(src, dest)?;
1162 state.advance(self.fs.size(src));
1163 on_progress(state.snapshot(src));
1164 }
1165 Ok(())
1166 }
1167
1168 fn delete_recursive(
1169 &self,
1170 path: &Path,
1171 cancel: &AtomicBool,
1172 state: &mut ProgressState,
1173 on_progress: &mut dyn FnMut(Progress),
1174 ) -> Result<(), OxiNavError> {
1175 if cancel.load(Ordering::Relaxed) {
1176 return Ok(());
1177 }
1178 if self.fs.is_dir(path) {
1179 for child in self.fs.read_dir(path)? {
1180 if cancel.load(Ordering::Relaxed) {
1181 return Ok(());
1182 }
1183 self.delete_recursive(&child, cancel, state, on_progress)?;
1184 }
1185 if cancel.load(Ordering::Relaxed) {
1186 return Ok(());
1187 }
1188 self.fs.delete(path)?;
1190 } else {
1191 let bytes = self.fs.size(path);
1192 self.fs.delete(path)?;
1193 state.advance(bytes);
1194 on_progress(state.snapshot(path));
1195 }
1196 Ok(())
1197 }
1198}
1199
1200struct ProgressState {
1203 items_done: usize,
1204 items_total: usize,
1205 bytes_done: u64,
1206 bytes_total: u64,
1207}
1208
1209impl ProgressState {
1210 fn new(items_total: usize, bytes_total: u64) -> Self {
1211 Self {
1212 items_done: 0,
1213 items_total,
1214 bytes_done: 0,
1215 bytes_total,
1216 }
1217 }
1218
1219 fn advance(&mut self, bytes: u64) {
1220 self.items_done += 1;
1221 self.bytes_done += bytes;
1222 }
1223
1224 fn snapshot(&self, current: &Path) -> Progress {
1225 Progress {
1226 current: current.to_path_buf(),
1227 items_done: self.items_done,
1228 items_total: self.items_total,
1229 bytes_done: self.bytes_done,
1230 bytes_total: self.bytes_total,
1231 }
1232 }
1233}
1234
1235fn outcome(cancel: &AtomicBool) -> OperationOutcome {
1236 if cancel.load(Ordering::Relaxed) {
1237 OperationOutcome::Cancelled
1238 } else {
1239 OperationOutcome::Completed
1240 }
1241}
1242
1243fn single_tick(current: PathBuf) -> Progress {
1244 Progress {
1245 current,
1246 items_done: 1,
1247 items_total: 1,
1248 bytes_done: 0,
1249 bytes_total: 0,
1250 }
1251}
1252
1253fn copy_dir_recursive(src: &Path, dest: &Path) -> std::io::Result<()> {
1254 std::fs::create_dir_all(dest)?;
1255 for entry in std::fs::read_dir(src)? {
1256 let entry = entry?;
1257 let dest_path = dest.join(entry.file_name());
1258 if entry.file_type()?.is_dir() {
1259 copy_dir_recursive(&entry.path(), &dest_path)?;
1260 } else {
1261 std::fs::copy(entry.path(), &dest_path)?;
1262 }
1263 }
1264 Ok(())
1265}
1266
1267#[cfg(test)]
1268mod tests {
1269 use super::*;
1270 use std::collections::{HashMap, HashSet};
1271 use std::sync::{Arc, Mutex};
1272
1273 #[derive(Clone)]
1277 struct MockFs {
1278 nodes: Arc<Mutex<HashMap<PathBuf, Option<u64>>>>,
1279 archives: Arc<Mutex<HashMap<PathBuf, Vec<String>>>>,
1282 links: Arc<Mutex<HashSet<PathBuf>>>,
1284 unreadable: Arc<Mutex<HashSet<PathBuf>>>,
1286 packed: Arc<Mutex<PackedArchives>>,
1288 contents: Arc<Mutex<HashMap<PathBuf, String>>>,
1290 }
1291
1292 type PackedArchives = HashMap<PathBuf, Vec<(PathBuf, EntryKind)>>;
1293
1294 impl MockFs {
1295 fn with(paths: &[&str]) -> Self {
1297 Self {
1298 nodes: Arc::new(Mutex::new(
1299 paths.iter().map(|p| (PathBuf::from(p), Some(0))).collect(),
1300 )),
1301 archives: Arc::new(Mutex::new(HashMap::new())),
1302 links: Arc::default(),
1303 unreadable: Arc::default(),
1304 packed: Arc::default(),
1305 contents: Arc::default(),
1306 }
1307 }
1308
1309 fn with_archive(self, path: &str, entries: &[&str]) -> Self {
1311 self.nodes
1312 .lock()
1313 .unwrap()
1314 .insert(PathBuf::from(path), Some(0));
1315 self.archives.lock().unwrap().insert(
1316 PathBuf::from(path),
1317 entries.iter().map(|e| e.to_string()).collect(),
1318 );
1319 self
1320 }
1321
1322 fn with_content(self, path: &str, text: &str) -> Self {
1324 {
1325 let mut nodes = self.nodes.lock().unwrap();
1326 let path = PathBuf::from(path);
1327 let mut parent = path.parent();
1328 while let Some(dir) = parent {
1329 nodes.entry(dir.to_path_buf()).or_insert(None);
1330 parent = dir.parent();
1331 }
1332 nodes.insert(path.clone(), Some(text.len() as u64));
1333 self.contents.lock().unwrap().insert(path, text.to_string());
1334 }
1335 self
1336 }
1337
1338 fn with_link(self, path: &str) -> Self {
1339 self.links.lock().unwrap().insert(PathBuf::from(path));
1340 self
1341 }
1342
1343 fn with_unreadable(self, path: &str) -> Self {
1344 self.unreadable.lock().unwrap().insert(PathBuf::from(path));
1345 self
1346 }
1347
1348 fn packed(&self, archive: &str) -> Vec<(String, EntryKind)> {
1349 self.packed
1350 .lock()
1351 .unwrap()
1352 .get(Path::new(archive))
1353 .map(|entries| {
1354 entries
1355 .iter()
1356 .map(|(name, kind)| (name.display().to_string(), *kind))
1357 .collect()
1358 })
1359 .unwrap_or_default()
1360 }
1361
1362 fn archive_entries(&self, archive: &Path) -> Vec<String> {
1363 self.archives
1364 .lock()
1365 .unwrap()
1366 .get(archive)
1367 .cloned()
1368 .unwrap_or_default()
1369 }
1370
1371 fn tree(entries: &[(&str, Option<u64>)]) -> Self {
1373 Self {
1374 nodes: Arc::new(Mutex::new(
1375 entries
1376 .iter()
1377 .map(|(p, size)| (PathBuf::from(p), *size))
1378 .collect(),
1379 )),
1380 archives: Arc::new(Mutex::new(HashMap::new())),
1381 links: Arc::default(),
1382 unreadable: Arc::default(),
1383 packed: Arc::default(),
1384 contents: Arc::default(),
1385 }
1386 }
1387 }
1388
1389 impl Filesystem for MockFs {
1390 fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
1391 let mut nodes = self.nodes.lock().unwrap();
1392 let value = nodes.get(src).copied().unwrap_or(Some(0));
1393 nodes.insert(dest.to_path_buf(), value);
1394 Ok(())
1395 }
1396 fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
1397 let mut nodes = self.nodes.lock().unwrap();
1398 let value = nodes.remove(src).unwrap_or(Some(0));
1399 nodes.insert(dest.to_path_buf(), value);
1400 Ok(())
1401 }
1402 fn delete(&self, path: &Path) -> Result<(), OxiNavError> {
1403 let mut nodes = self.nodes.lock().unwrap();
1404 nodes.remove(path);
1405 let prefix = format!("{}/", path.display());
1407 nodes.retain(|p, _| !p.display().to_string().starts_with(&prefix));
1408 Ok(())
1409 }
1410 fn create_dir(&self, path: &Path) -> Result<(), OxiNavError> {
1411 self.nodes.lock().unwrap().insert(path.to_path_buf(), None);
1412 Ok(())
1413 }
1414 fn create_file(&self, path: &Path) -> Result<(), OxiNavError> {
1415 self.nodes
1416 .lock()
1417 .unwrap()
1418 .insert(path.to_path_buf(), Some(0));
1419 Ok(())
1420 }
1421 fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError> {
1422 let mut nodes = self.nodes.lock().unwrap();
1425 let value = nodes.get(source).copied().unwrap_or(Some(0));
1426 nodes.insert(link.to_path_buf(), value);
1427 Ok(())
1428 }
1429 fn exists(&self, path: &Path) -> bool {
1430 self.nodes.lock().unwrap().contains_key(path)
1431 }
1432 fn is_symlink(&self, path: &Path) -> bool {
1433 self.links.lock().unwrap().contains(path)
1434 }
1435 fn is_dir(&self, path: &Path) -> bool {
1436 matches!(self.nodes.lock().unwrap().get(path), Some(None))
1437 }
1438 fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError> {
1439 let nodes = self.nodes.lock().unwrap();
1440 Ok(nodes
1441 .keys()
1442 .filter(|p| p.parent() == Some(path))
1443 .cloned()
1444 .collect())
1445 }
1446 fn size(&self, path: &Path) -> u64 {
1447 match self.nodes.lock().unwrap().get(path) {
1448 Some(Some(size)) => *size,
1449 _ => 0,
1450 }
1451 }
1452 fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
1456 let len = (self.size(path) as usize).min(max);
1457 Ok(vec![b'a'; len])
1458 }
1459 fn count_archive_entries(
1460 &self,
1461 archive: &Path,
1462 _format: ArchiveFormat,
1463 ) -> Result<usize, OxiNavError> {
1464 Ok(self.archive_entries(archive).len())
1465 }
1466 fn extract_archive(
1470 &self,
1471 archive: &Path,
1472 dest_dir: &Path,
1473 _format: ArchiveFormat,
1474 on_entry: &mut dyn FnMut(&Path),
1475 ) -> Result<(), OxiNavError> {
1476 for raw in self.archive_entries(archive) {
1477 let Some(target) = resolve_entry(dest_dir, &raw)? else {
1478 continue;
1479 };
1480 self.nodes.lock().unwrap().insert(target.clone(), Some(0));
1481 on_entry(&target);
1482 }
1483 Ok(())
1484 }
1485 fn write_archive(
1488 &self,
1489 archive: &Path,
1490 _format: ArchiveFormat,
1491 entries: &[ArchiveEntry],
1492 on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
1493 ) -> Result<ControlFlow<()>, OxiNavError> {
1494 let mut written = Vec::new();
1495 for entry in entries {
1496 if self.unreadable.lock().unwrap().contains(&entry.source) {
1497 return Err(OxiNavError::Io {
1498 path: entry.source.clone(),
1499 source: std::io::Error::from(std::io::ErrorKind::PermissionDenied),
1500 });
1501 }
1502 written.push((entry.name.clone(), entry.kind));
1503 if on_entry(&entry.source).is_break() {
1504 return Ok(ControlFlow::Break(()));
1505 }
1506 }
1507 self.nodes
1508 .lock()
1509 .unwrap()
1510 .insert(archive.to_path_buf(), Some(0));
1511 self.packed
1512 .lock()
1513 .unwrap()
1514 .insert(archive.to_path_buf(), written);
1515 Ok(ControlFlow::Continue(()))
1516 }
1517 fn search(
1520 &self,
1521 root: &Path,
1522 query: &SearchQuery,
1523 cancel: &AtomicBool,
1524 on_hit: &mut dyn FnMut(SearchHit) -> ControlFlow<()>,
1525 ) -> Result<ControlFlow<()>, OxiNavError> {
1526 let fold = |text: &str| {
1527 if query.case_insensitive {
1528 text.to_lowercase()
1529 } else {
1530 text.to_string()
1531 }
1532 };
1533 let needle = fold(&query.pattern);
1534 let mut files: Vec<(PathBuf, String)> = self
1535 .contents
1536 .lock()
1537 .unwrap()
1538 .iter()
1539 .map(|(path, text)| (path.clone(), text.clone()))
1540 .collect();
1541 files.sort();
1542 for (path, text) in files {
1543 if cancel.load(Ordering::Relaxed) {
1544 return Ok(ControlFlow::Break(()));
1545 }
1546 let Ok(relative) = path.strip_prefix(root) else {
1547 continue;
1548 };
1549 let hidden = relative
1550 .components()
1551 .any(|part| part.as_os_str().to_string_lossy().starts_with('.'));
1552 if hidden && !query.include_hidden {
1553 continue;
1554 }
1555 let name = path.file_name().unwrap_or_default().to_string_lossy();
1556 if let Some(glob) = &query.name_glob {
1557 if !matches_filter(&name, glob) {
1558 continue;
1559 }
1560 }
1561 for (index, line) in text.lines().enumerate() {
1562 if fold(line).contains(&needle) {
1563 let hit = SearchHit {
1564 path: path.clone(),
1565 line: index as u64 + 1,
1566 text: snippet(line),
1567 };
1568 if on_hit(hit).is_break() {
1569 return Ok(ControlFlow::Break(()));
1570 }
1571 }
1572 }
1573 }
1574 Ok(ControlFlow::Continue(()))
1575 }
1576 }
1577
1578 fn query(pattern: &str, include_hidden: bool, name_glob: Option<&str>) -> SearchQuery {
1579 let mut pane = crate::pane::Pane::new(PathBuf::from("/"));
1580 pane.show_hidden = include_hidden;
1581 pane.filter = name_glob.map(str::to_string);
1582 SearchQuery::new(pattern, &pane).unwrap()
1583 }
1584
1585 fn search_all(
1586 engine: &OperationEngine<MockFs>,
1587 query: &SearchQuery,
1588 ) -> (Vec<String>, SearchEnd) {
1589 let mut hits = Vec::new();
1590 let end = engine
1591 .search(
1592 Path::new("/proj"),
1593 query,
1594 &AtomicBool::new(false),
1595 &mut |hit| {
1596 hits.push(format!("{}:{}:{}", hit.path.display(), hit.line, hit.text));
1597 },
1598 )
1599 .unwrap();
1600 (hits, end)
1601 }
1602
1603 #[test]
1604 fn search_finds_matches_recursively_in_order() {
1605 let fs = MockFs::with(&[])
1606 .with_content("/proj/src/b.rs", "x\nfn main() {}\n")
1607 .with_content("/proj/a.rs", "fn main()")
1608 .with_content("/elsewhere/c.rs", "fn main()");
1609 let engine = OperationEngine::new(fs);
1610
1611 let (hits, end) = search_all(&engine, &query("fn main", false, None));
1612
1613 assert_eq!(
1614 hits,
1615 vec!["/proj/a.rs:1:fn main()", "/proj/src/b.rs:2:fn main() {}"]
1616 );
1617 assert_eq!(end, SearchEnd::Finished);
1618 }
1619
1620 #[test]
1621 fn search_skips_hidden_files_unless_the_pane_shows_them() {
1622 let fs = MockFs::with(&[])
1623 .with_content("/proj/.env", "token")
1624 .with_content("/proj/.git/config", "token")
1625 .with_content("/proj/a.txt", "token");
1626 let engine = OperationEngine::new(fs);
1627
1628 assert_eq!(search_all(&engine, &query("token", false, None)).0.len(), 1);
1629 assert_eq!(search_all(&engine, &query("token", true, None)).0.len(), 3);
1630 }
1631
1632 #[test]
1633 fn search_follows_the_pane_name_filter() {
1634 let fs = MockFs::with(&[])
1635 .with_content("/proj/a.rs", "needle")
1636 .with_content("/proj/a.md", "needle");
1637 let engine = OperationEngine::new(fs);
1638
1639 let (hits, _) = search_all(&engine, &query("needle", false, Some("*.rs")));
1640 assert_eq!(hits, vec!["/proj/a.rs:1:needle"]);
1641 }
1642
1643 #[test]
1644 fn search_stops_at_the_cap() {
1645 let text = "hit\n".repeat(MAX_HITS + 5);
1646 let fs = MockFs::with(&[]).with_content("/proj/many.txt", &text);
1647 let engine = OperationEngine::new(fs);
1648
1649 let (hits, end) = search_all(&engine, &query("hit", false, None));
1650 assert_eq!(hits.len(), MAX_HITS);
1651 assert_eq!(end, SearchEnd::Capped);
1652 }
1653
1654 #[test]
1655 fn exactly_the_cap_is_not_capped() {
1656 let text = "hit\n".repeat(MAX_HITS);
1657 let fs = MockFs::with(&[]).with_content("/proj/many.txt", &text);
1658 let engine = OperationEngine::new(fs);
1659
1660 let (hits, end) = search_all(&engine, &query("hit", false, None));
1661 assert_eq!(hits.len(), MAX_HITS);
1662 assert_eq!(end, SearchEnd::Finished);
1663 }
1664
1665 #[test]
1666 fn cancelling_a_search_stops_it() {
1667 let fs = MockFs::with(&[])
1668 .with_content("/proj/a.txt", "hit")
1669 .with_content("/proj/b.txt", "hit");
1670 let engine = OperationEngine::new(fs);
1671 let cancel = AtomicBool::new(false);
1672 let mut hits = 0;
1673
1674 let end = engine
1675 .search(
1676 Path::new("/proj"),
1677 &query("hit", false, None),
1678 &cancel,
1679 &mut |_| {
1680 hits += 1;
1681 cancel.store(true, Ordering::Relaxed);
1682 },
1683 )
1684 .unwrap();
1685
1686 assert_eq!(hits, 1);
1687 assert_eq!(end, SearchEnd::Stopped);
1688 }
1689
1690 #[test]
1691 fn mock_search_applies_smart_case() {
1692 let fs = MockFs::with(&[]).with_content("/proj/a.txt", "TODO\nTodo\ntodo");
1693 let engine = OperationEngine::new(fs);
1694
1695 assert_eq!(search_all(&engine, &query("todo", false, None)).0.len(), 3);
1696 assert_eq!(search_all(&engine, &query("Todo", false, None)).0.len(), 1);
1697 }
1698
1699 fn pack(sources: &[&str], base_dir: &str, archive: &str) -> Operation {
1700 Operation::CreateArchive {
1701 sources: sources.iter().map(PathBuf::from).collect(),
1702 base_dir: PathBuf::from(base_dir),
1703 archive: PathBuf::from(archive),
1704 }
1705 }
1706
1707 fn packing_tree() -> MockFs {
1710 MockFs::tree(&[
1711 ("/w", None),
1712 ("/w/src", None),
1713 ("/w/src/main.rs", Some(10)),
1714 ("/w/src/lib.rs", Some(20)),
1715 ("/w/src/empty", None),
1716 ("/w/notes.txt", Some(5)),
1717 ("/out", None),
1718 ])
1719 }
1720
1721 #[test]
1722 fn packing_names_entries_relative_to_the_base_directory() {
1723 let fs = packing_tree();
1724 let engine = OperationEngine::new(fs.clone());
1725
1726 engine
1727 .execute(&pack(&["/w/src", "/w/notes.txt"], "/w", "/out/a.zip"))
1728 .unwrap();
1729
1730 assert_eq!(
1731 fs.packed("/out/a.zip"),
1732 vec![
1733 ("src".to_string(), EntryKind::Dir),
1734 ("src/empty".to_string(), EntryKind::Dir),
1735 ("src/lib.rs".to_string(), EntryKind::File),
1736 ("src/main.rs".to_string(), EntryKind::File),
1737 ("notes.txt".to_string(), EntryKind::File),
1738 ]
1739 );
1740 }
1741
1742 #[test]
1743 fn packing_does_not_follow_symlinks() {
1744 let fs = MockFs::tree(&[
1745 ("/w", None),
1746 ("/w/big", None),
1747 ("/w/big/huge.bin", Some(1_000)),
1748 ("/w/link", None),
1749 ("/w/link/huge.bin", Some(1_000)),
1750 ("/out", None),
1751 ])
1752 .with_link("/w/link");
1753 let engine = OperationEngine::new(fs.clone());
1754
1755 engine
1756 .execute(&pack(&["/w/link"], "/w", "/out/a.tar"))
1757 .unwrap();
1758
1759 assert_eq!(
1760 fs.packed("/out/a.tar"),
1761 vec![("link".to_string(), EntryKind::Symlink)]
1762 );
1763 }
1764
1765 #[test]
1766 fn packing_reports_progress_against_a_known_total() {
1767 let fs = packing_tree();
1768 let engine = OperationEngine::new(fs);
1769 let mut ticks = Vec::new();
1770
1771 let outcome = engine
1772 .execute_with_progress(
1773 &pack(&["/w/src"], "/w", "/out/a.tar.gz"),
1774 &AtomicBool::new(false),
1775 &mut |p| ticks.push(p),
1776 )
1777 .unwrap();
1778
1779 assert_eq!(outcome, OperationOutcome::Completed);
1780 assert_eq!(ticks.len(), 4);
1781 assert!(ticks
1782 .iter()
1783 .all(|p| p.items_total == 4 && p.bytes_total == 30));
1784 assert_eq!(ticks.last().unwrap().items_done, 4);
1785 assert_eq!(ticks.last().unwrap().bytes_done, 30);
1786 assert_eq!(
1787 engine.estimate_totals(&pack(&["/w/src"], "/w", "/out/a.tar.gz")),
1788 (4, 30)
1789 );
1790 }
1791
1792 #[test]
1793 fn packing_refuses_an_existing_destination() {
1794 let fs = packing_tree();
1795 fs.nodes
1796 .lock()
1797 .unwrap()
1798 .insert(PathBuf::from("/out/a.zip"), Some(7));
1799 let engine = OperationEngine::new(fs.clone());
1800
1801 let result = engine.execute(&pack(&["/w/notes.txt"], "/w", "/out/a.zip"));
1802
1803 assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
1804 assert!(fs.packed("/out/a.zip").is_empty());
1805 assert_eq!(fs.size(Path::new("/out/a.zip")), 7);
1806 }
1807
1808 #[test]
1809 fn packing_refuses_an_unsupported_extension() {
1810 let fs = packing_tree();
1811 let engine = OperationEngine::new(fs.clone());
1812
1813 let result = engine.execute(&pack(&["/w/notes.txt"], "/w", "/out/a.rar"));
1814
1815 assert!(matches!(result, Err(OxiNavError::UnsupportedArchive(_))));
1816 assert!(!fs.exists(Path::new("/out/a.rar")));
1817 }
1818
1819 #[test]
1820 fn packing_refuses_a_missing_source() {
1821 let engine = OperationEngine::new(packing_tree());
1822
1823 let result = engine.execute(&pack(&["/w/gone.txt"], "/w", "/out/a.zip"));
1824
1825 assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
1826 }
1827
1828 #[test]
1829 fn cancelling_packing_leaves_no_archive() {
1830 let fs = packing_tree();
1831 let engine = OperationEngine::new(fs.clone());
1832 let cancel = AtomicBool::new(false);
1833 let mut ticks = 0;
1834
1835 let outcome = engine
1836 .execute_with_progress(&pack(&["/w/src"], "/w", "/out/a.zip"), &cancel, &mut |_| {
1837 ticks += 1;
1838 cancel.store(true, Ordering::Relaxed);
1839 })
1840 .unwrap();
1841
1842 assert_eq!(outcome, OperationOutcome::Cancelled);
1843 assert_eq!(ticks, 1);
1844 assert!(!fs.exists(Path::new("/out/a.zip")));
1845 }
1846
1847 #[test]
1848 fn an_unreadable_file_fails_packing_and_names_it() {
1849 let fs = packing_tree().with_unreadable("/w/src/main.rs");
1850 let engine = OperationEngine::new(fs.clone());
1851
1852 let result = engine.execute(&pack(&["/w/src"], "/w", "/out/a.zip"));
1853
1854 match result {
1855 Err(OxiNavError::Io { path, .. }) => assert_eq!(path, PathBuf::from("/w/src/main.rs")),
1856 other => panic!("expected an I/O error naming the file, got {other:?}"),
1857 }
1858 assert!(!fs.exists(Path::new("/out/a.zip")));
1859 }
1860
1861 fn scratch_dir(test: &str) -> PathBuf {
1863 let dir = std::env::temp_dir().join(format!("oxinav_{test}_{}", std::process::id()));
1864 let _ = std::fs::remove_dir_all(&dir);
1865 std::fs::create_dir_all(&dir).unwrap();
1866 dir
1867 }
1868
1869 fn snapshot(root: &Path) -> Vec<(String, String)> {
1872 fn walk(root: &Path, dir: &Path, out: &mut Vec<(String, String)>) {
1873 let mut children: Vec<_> = std::fs::read_dir(dir)
1874 .unwrap()
1875 .map(|e| e.unwrap().path())
1876 .collect();
1877 children.sort();
1878 for child in children {
1879 let name = child.strip_prefix(root).unwrap().display().to_string();
1880 if child.is_symlink() {
1881 let target = std::fs::read_link(&child).unwrap();
1882 out.push((name, format!("<link {}>", target.display())));
1883 } else if child.is_dir() {
1884 out.push((name, "<dir>".to_string()));
1885 walk(root, &child, out);
1886 } else {
1887 out.push((name, std::fs::read_to_string(&child).unwrap()));
1888 }
1889 }
1890 }
1891 let mut out = Vec::new();
1892 walk(root, root, &mut out);
1893 out
1894 }
1895
1896 fn round_trip(test: &str, name: &str) -> (PathBuf, PathBuf, PathBuf) {
1899 let work = scratch_dir(test);
1900 let tree = work.join("tree");
1901 std::fs::create_dir_all(tree.join("sub/empty")).unwrap();
1902 std::fs::write(tree.join("a.txt"), "alpha").unwrap();
1903 std::fs::write(tree.join("sub/b.txt"), "beta").unwrap();
1904 #[cfg(unix)]
1905 {
1906 use std::os::unix::fs::PermissionsExt;
1907 std::fs::set_permissions(
1908 tree.join("sub/b.txt"),
1909 std::fs::Permissions::from_mode(0o750),
1910 )
1911 .unwrap();
1912 }
1913
1914 let engine = OperationEngine::new(StdFilesystem);
1915 let archive = work.join(name);
1916 engine
1917 .execute(&Operation::CreateArchive {
1918 sources: vec![tree.clone()],
1919 base_dir: work.clone(),
1920 archive: archive.clone(),
1921 })
1922 .unwrap();
1923 let out = work.join("out");
1924 std::fs::create_dir(&out).unwrap();
1925 engine
1926 .execute(&Operation::ExtractArchive {
1927 archive: archive.clone(),
1928 dest_dir: out.clone(),
1929 })
1930 .unwrap();
1931 (work, archive, out)
1932 }
1933
1934 #[cfg(unix)]
1935 fn mode(path: &Path) -> u32 {
1936 use std::os::unix::fs::PermissionsExt;
1937 std::fs::metadata(path).unwrap().permissions().mode() & 0o777
1938 }
1939
1940 #[test]
1941 fn every_format_round_trips_through_extraction() {
1942 for (test, name) in [
1943 ("rt_zip", "x.zip"),
1944 ("rt_tar", "x.tar"),
1945 ("rt_tgz", "x.tar.gz"),
1946 ] {
1947 let (work, _, out) = round_trip(test, name);
1948 assert_eq!(
1949 snapshot(&out.join("tree")),
1950 snapshot(&work.join("tree")),
1951 "{name}"
1952 );
1953 #[cfg(unix)]
1954 assert_eq!(mode(&out.join("tree/sub/b.txt")), 0o750, "{name}");
1955 std::fs::remove_dir_all(&work).unwrap();
1956 }
1957 }
1958
1959 #[test]
1960 fn zip_entries_keep_their_modification_date() {
1961 let (work, archive, _) = round_trip("zip_time", "t.zip");
1962 let mut zip = zip::ZipArchive::new(std::fs::File::open(&archive).unwrap()).unwrap();
1963 let entry = zip.by_name("tree/a.txt").unwrap();
1964 let year = entry.last_modified().map(|time| time.year());
1965 assert!(year.is_some_and(|year| year > 2000), "{year:?}");
1966 std::fs::remove_dir_all(&work).unwrap();
1967 }
1968
1969 #[cfg(unix)]
1970 #[test]
1971 fn symlinks_are_packed_as_links() {
1972 let work = scratch_dir("pack_links");
1973 let outside = work.join("outside");
1974 std::fs::create_dir(&outside).unwrap();
1975 std::fs::write(outside.join("big.bin"), "lots").unwrap();
1976 std::os::unix::fs::symlink(&outside, work.join("link")).unwrap();
1977 let engine = OperationEngine::new(StdFilesystem);
1978
1979 for name in ["l.tar", "l.zip"] {
1980 engine
1981 .execute(&Operation::CreateArchive {
1982 sources: vec![work.join("link")],
1983 base_dir: work.clone(),
1984 archive: work.join(name),
1985 })
1986 .unwrap();
1987 }
1988
1989 let tar_entries: Vec<_> =
1990 tar::Archive::new(std::fs::File::open(work.join("l.tar")).unwrap())
1991 .entries()
1992 .unwrap()
1993 .map(|e| e.unwrap().header().entry_type())
1994 .collect();
1995 assert_eq!(tar_entries, vec![tar::EntryType::Symlink]);
1996
1997 let mut zip =
1998 zip::ZipArchive::new(std::fs::File::open(work.join("l.zip")).unwrap()).unwrap();
1999 assert_eq!(zip.len(), 1);
2000 assert!(zip.by_index(0).unwrap().is_symlink());
2001 std::fs::remove_dir_all(&work).unwrap();
2002 }
2003
2004 #[test]
2005 fn cancelled_packing_leaves_neither_archive_nor_temp_file() {
2006 let work = scratch_dir("pack_cancel");
2007 for i in 0..5 {
2008 std::fs::write(work.join(format!("f{i}.txt")), "x").unwrap();
2009 }
2010 let engine = OperationEngine::new(StdFilesystem);
2011 let cancel = AtomicBool::new(false);
2012 let archive = work.join("out.tar.gz");
2013 let sources = (0..5).map(|i| work.join(format!("f{i}.txt"))).collect();
2014
2015 let outcome = engine
2016 .execute_with_progress(
2017 &Operation::CreateArchive {
2018 sources,
2019 base_dir: work.clone(),
2020 archive: archive.clone(),
2021 },
2022 &cancel,
2023 &mut |_| cancel.store(true, Ordering::Relaxed),
2024 )
2025 .unwrap();
2026
2027 assert_eq!(outcome, OperationOutcome::Cancelled);
2028 assert!(!archive.exists());
2029 assert!(!work.join(".out.tar.gz.oxinav-partial").exists());
2030 std::fs::remove_dir_all(&work).unwrap();
2031 }
2032
2033 fn search_tree(test: &str) -> PathBuf {
2037 let root = scratch_dir(test);
2038 std::fs::create_dir_all(root.join(".git")).unwrap();
2039 std::fs::create_dir_all(root.join("src")).unwrap();
2040 std::fs::create_dir_all(root.join("target")).unwrap();
2041 std::fs::write(root.join(".gitignore"), "target/\n").unwrap();
2042 std::fs::write(root.join("src/b.rs"), "// TODO later\nfn main() {}\n").unwrap();
2043 std::fs::write(root.join("a.md"), "todo: write docs\nTodo list\n").unwrap();
2044 std::fs::write(root.join("target/out.rs"), "fn main() {}\n").unwrap();
2045 std::fs::write(root.join("blob.bin"), b"fn main\0\x01\x02").unwrap();
2046 std::fs::write(root.join(".env"), "fn main\n").unwrap();
2047 root
2048 }
2049
2050 fn std_search(root: &Path, pattern: &str) -> Result<Vec<String>, OxiNavError> {
2051 let engine = OperationEngine::new(StdFilesystem);
2052 let query = query(pattern, false, None);
2053 let mut hits = Vec::new();
2054 engine.search(root, &query, &AtomicBool::new(false), &mut |hit| {
2055 let name = hit
2056 .path
2057 .strip_prefix(root)
2058 .unwrap()
2059 .to_string_lossy()
2060 .replace('\\', "/");
2061 hits.push(format!("{name}:{}:{}", hit.line, hit.text));
2062 })?;
2063 Ok(hits)
2064 }
2065
2066 #[test]
2067 fn ripgrep_backend_skips_ignored_binary_and_hidden_files() {
2068 let root = search_tree("rg_scope");
2069 assert_eq!(
2070 std_search(&root, r"fn\s+main").unwrap(),
2071 vec!["src/b.rs:2:fn main() {}"]
2072 );
2073 std::fs::remove_dir_all(&root).unwrap();
2074 }
2075
2076 #[test]
2077 fn ripgrep_backend_applies_smart_case_in_a_stable_order() {
2078 let root = search_tree("rg_case");
2079 assert_eq!(
2080 std_search(&root, "todo").unwrap(),
2081 vec![
2082 "a.md:1:todo: write docs",
2083 "a.md:2:Todo list",
2084 "src/b.rs:1:// TODO later",
2085 ]
2086 );
2087 assert_eq!(std_search(&root, "Todo").unwrap(), vec!["a.md:2:Todo list"]);
2088 std::fs::remove_dir_all(&root).unwrap();
2089 }
2090
2091 #[test]
2092 fn ripgrep_backend_rejects_an_invalid_regex() {
2093 let root = search_tree("rg_invalid");
2094 assert!(matches!(
2095 std_search(&root, "foo("),
2096 Err(OxiNavError::InvalidPattern(_))
2097 ));
2098 std::fs::remove_dir_all(&root).unwrap();
2099 }
2100
2101 #[test]
2102 fn create_file_creates_an_empty_file() {
2103 let fs = MockFs::with(&[]);
2104 let engine = OperationEngine::new(fs);
2105
2106 engine
2107 .execute(&Operation::CreateFile {
2108 path: "/new.txt".into(),
2109 })
2110 .unwrap();
2111
2112 assert!(engine.exists(Path::new("/new.txt")));
2113 }
2114
2115 #[test]
2116 fn create_file_rejects_an_existing_name() {
2117 let engine = OperationEngine::new(MockFs::with(&["/taken.txt"]));
2118
2119 let result = engine.execute(&Operation::CreateFile {
2120 path: "/taken.txt".into(),
2121 });
2122
2123 assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
2124 }
2125
2126 #[test]
2127 fn create_file_rejects_an_existing_directory_name() {
2128 let engine = OperationEngine::new(MockFs::tree(&[("/dir", None)]));
2129
2130 let result = engine.execute(&Operation::CreateFile {
2131 path: "/dir".into(),
2132 });
2133
2134 assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
2135 }
2136
2137 #[test]
2138 fn create_symlink_creates_a_link_at_the_target_path() {
2139 let engine = OperationEngine::new(MockFs::with(&["/src.txt"]));
2140
2141 engine
2142 .execute(&Operation::CreateSymlink {
2143 source: "/src.txt".into(),
2144 link: "/other/link.txt".into(),
2145 })
2146 .unwrap();
2147
2148 assert!(engine.exists(Path::new("/other/link.txt")));
2149 assert!(engine.exists(Path::new("/src.txt")));
2151 }
2152
2153 #[test]
2154 fn create_symlink_rejects_a_missing_source() {
2155 let engine = OperationEngine::new(MockFs::with(&[]));
2156
2157 let result = engine.execute(&Operation::CreateSymlink {
2158 source: "/gone.txt".into(),
2159 link: "/link.txt".into(),
2160 });
2161
2162 assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
2163 assert!(!engine.exists(Path::new("/link.txt")));
2164 }
2165
2166 #[test]
2167 fn create_symlink_rejects_an_existing_link_path() {
2168 let engine = OperationEngine::new(MockFs::with(&["/src.txt", "/link.txt"]));
2169
2170 let result = engine.execute(&Operation::CreateSymlink {
2171 source: "/src.txt".into(),
2172 link: "/link.txt".into(),
2173 });
2174
2175 assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
2176 }
2177
2178 #[test]
2179 fn new_single_item_ops_estimate_one_item() {
2180 let engine = OperationEngine::new(MockFs::with(&["/src.txt"]));
2181
2182 assert_eq!(
2183 engine.estimate_totals(&Operation::CreateFile {
2184 path: "/new.txt".into()
2185 }),
2186 (1, 0)
2187 );
2188 assert_eq!(
2189 engine.estimate_totals(&Operation::CreateSymlink {
2190 source: "/src.txt".into(),
2191 link: "/link.txt".into(),
2192 }),
2193 (1, 0)
2194 );
2195 }
2196
2197 fn extract(archive: &str, dest: &str) -> Operation {
2198 Operation::ExtractArchive {
2199 archive: archive.into(),
2200 dest_dir: dest.into(),
2201 }
2202 }
2203
2204 #[test]
2205 fn extract_writes_entries_under_the_destination() {
2206 let fs =
2207 MockFs::tree(&[("/dest", None)]).with_archive("/a.zip", &["one.txt", "nested/two.txt"]);
2208 let engine = OperationEngine::new(fs);
2209
2210 engine.execute(&extract("/a.zip", "/dest")).unwrap();
2211
2212 assert!(engine.exists(Path::new("/dest/one.txt")));
2213 assert!(engine.exists(Path::new("/dest/nested/two.txt")));
2214 }
2215
2216 #[test]
2217 fn extract_rejects_an_unsupported_format_without_writing_anything() {
2218 let fs = MockFs::tree(&[("/dest", None)]).with_archive("/a.rar", &["one.txt"]);
2219 let engine = OperationEngine::new(fs);
2220
2221 let result = engine.execute(&extract("/a.rar", "/dest"));
2222
2223 assert!(matches!(result, Err(OxiNavError::UnsupportedArchive(_))));
2224 assert!(!engine.exists(Path::new("/dest/one.txt")));
2226 }
2227
2228 #[test]
2229 fn extract_rejects_a_missing_archive() {
2230 let engine = OperationEngine::new(MockFs::tree(&[("/dest", None)]));
2231
2232 let result = engine.execute(&extract("/gone.zip", "/dest"));
2233
2234 assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
2235 }
2236
2237 #[test]
2238 fn extract_rejects_a_missing_destination() {
2239 let fs = MockFs::with(&[]).with_archive("/a.zip", &["one.txt"]);
2240 let engine = OperationEngine::new(fs);
2241
2242 let result = engine.execute(&extract("/a.zip", "/nope"));
2243
2244 assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
2245 }
2246
2247 #[test]
2248 fn extract_refuses_an_entry_escaping_the_destination() {
2249 let fs = MockFs::tree(&[("/dest", None)]).with_archive("/evil.zip", &["../../etc/passwd"]);
2250 let engine = OperationEngine::new(fs);
2251
2252 let result = engine.execute(&extract("/evil.zip", "/dest"));
2253
2254 assert!(matches!(result, Err(OxiNavError::UnsafeArchiveEntry(_))));
2255 assert!(!engine.exists(Path::new("/etc/passwd")));
2256 }
2257
2258 #[test]
2259 fn extract_reports_progress_per_entry_against_a_total_known_up_front() {
2260 let fs = MockFs::tree(&[("/dest", None)])
2261 .with_archive("/a.tar.gz", &["one.txt", "two.txt", "three.txt"]);
2262 let engine = OperationEngine::new(fs);
2263 let cancel = AtomicBool::new(false);
2264 let mut seen: Vec<Progress> = Vec::new();
2265
2266 let outcome = engine
2267 .execute_with_progress(&extract("/a.tar.gz", "/dest"), &cancel, &mut |p| {
2268 seen.push(p)
2269 })
2270 .unwrap();
2271
2272 assert_eq!(outcome, OperationOutcome::Completed);
2273 assert_eq!(seen.len(), 3);
2274 assert!(seen.iter().all(|p| p.items_total == 3));
2276 assert_eq!(
2277 seen.iter().map(|p| p.items_done).collect::<Vec<_>>(),
2278 vec![1, 2, 3]
2279 );
2280 }
2281
2282 #[test]
2283 fn extract_estimates_the_archive_entry_count() {
2284 let fs = MockFs::tree(&[("/dest", None)]).with_archive("/a.zip", &["one.txt", "two.txt"]);
2285 let engine = OperationEngine::new(fs);
2286
2287 assert_eq!(engine.estimate_totals(&extract("/a.zip", "/dest")), (2, 0));
2288 }
2289
2290 #[test]
2291 fn extract_estimate_falls_back_to_one_item_when_unreadable() {
2292 let engine = OperationEngine::new(MockFs::tree(&[("/dest", None)]));
2293
2294 assert_eq!(
2295 engine.estimate_totals(&extract("/gone.zip", "/dest")),
2296 (1, 0)
2297 );
2298 }
2299
2300 fn scratch(name: &str) -> PathBuf {
2302 let dir = std::env::temp_dir().join(name);
2303 std::fs::remove_dir_all(&dir).ok();
2304 std::fs::create_dir_all(&dir).unwrap();
2305 dir
2306 }
2307
2308 fn write_zip(path: &Path, entries: &[(&str, &[u8])]) {
2309 use std::io::Write;
2310 let file = std::fs::File::create(path).unwrap();
2311 let mut zip = zip::ZipWriter::new(file);
2312 for (name, body) in entries {
2313 zip.start_file(*name, zip::write::SimpleFileOptions::default())
2314 .unwrap();
2315 zip.write_all(body).unwrap();
2316 }
2317 zip.finish().unwrap();
2318 }
2319
2320 fn write_tar_gz(path: &Path, entries: &[(&str, &[u8])]) {
2321 let file = std::fs::File::create(path).unwrap();
2322 let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());
2323 let mut builder = tar::Builder::new(encoder);
2324 for (name, body) in entries {
2325 let mut header = tar::Header::new_gnu();
2326 header.set_size(body.len() as u64);
2327 header.set_mode(0o644);
2328 header.set_cksum();
2329 builder.append_data(&mut header, name, *body).unwrap();
2330 }
2331 builder.into_inner().unwrap().finish().unwrap();
2332 }
2333
2334 #[test]
2335 fn real_zip_is_extracted_with_its_contents_and_nesting() {
2336 let dir = scratch("oxinav_test_extract_zip");
2337 let archive = dir.join("bundle.zip");
2338 write_zip(
2339 &archive,
2340 &[("top.txt", b"one"), ("nested/deep.txt", b"two")],
2341 );
2342 let dest = dir.join("out");
2343 std::fs::create_dir_all(&dest).unwrap();
2344
2345 let engine = OperationEngine::new(StdFilesystem);
2346 engine
2347 .execute(&Operation::ExtractArchive {
2348 archive,
2349 dest_dir: dest.clone(),
2350 })
2351 .unwrap();
2352
2353 assert_eq!(std::fs::read(dest.join("top.txt")).unwrap(), b"one");
2354 assert_eq!(std::fs::read(dest.join("nested/deep.txt")).unwrap(), b"two");
2355
2356 std::fs::remove_dir_all(&dir).ok();
2357 }
2358
2359 #[test]
2360 fn real_tar_gz_is_extracted_with_its_contents() {
2361 let dir = scratch("oxinav_test_extract_targz");
2362 let archive = dir.join("bundle.tar.gz");
2363 write_tar_gz(&archive, &[("a.txt", b"alpha"), ("sub/b.txt", b"beta")]);
2364 let dest = dir.join("out");
2365 std::fs::create_dir_all(&dest).unwrap();
2366
2367 let engine = OperationEngine::new(StdFilesystem);
2368 engine
2369 .execute(&Operation::ExtractArchive {
2370 archive,
2371 dest_dir: dest.clone(),
2372 })
2373 .unwrap();
2374
2375 assert_eq!(std::fs::read(dest.join("a.txt")).unwrap(), b"alpha");
2376 assert_eq!(std::fs::read(dest.join("sub/b.txt")).unwrap(), b"beta");
2377
2378 std::fs::remove_dir_all(&dir).ok();
2379 }
2380
2381 #[test]
2382 fn real_tar_gz_with_a_dot_root_entry_still_extracts() {
2383 let dir = scratch("oxinav_test_extract_dot_root");
2387 let archive = dir.join("rooted.tar.gz");
2388 write_tar_gz(
2389 &archive,
2390 &[
2391 ("./", b""),
2392 ("./top.txt", b"one"),
2393 ("./sub/deep.txt", b"two"),
2394 ],
2395 );
2396 let dest = dir.join("out");
2397 std::fs::create_dir_all(&dest).unwrap();
2398
2399 let engine = OperationEngine::new(StdFilesystem);
2400 engine
2401 .execute(&Operation::ExtractArchive {
2402 archive,
2403 dest_dir: dest.clone(),
2404 })
2405 .unwrap();
2406
2407 assert_eq!(std::fs::read(dest.join("top.txt")).unwrap(), b"one");
2408 assert_eq!(std::fs::read(dest.join("sub/deep.txt")).unwrap(), b"two");
2409
2410 std::fs::remove_dir_all(&dir).ok();
2411 }
2412
2413 #[test]
2414 fn real_zip_slip_entry_never_escapes_the_destination() {
2415 let dir = scratch("oxinav_test_extract_zipslip");
2416 let archive = dir.join("evil.zip");
2417 write_zip(&archive, &[("../escaped.txt", b"pwned")]);
2419 let dest = dir.join("out");
2420 std::fs::create_dir_all(&dest).unwrap();
2421
2422 let engine = OperationEngine::new(StdFilesystem);
2423 let result = engine.execute(&Operation::ExtractArchive {
2424 archive,
2425 dest_dir: dest.clone(),
2426 });
2427
2428 assert!(matches!(result, Err(OxiNavError::UnsafeArchiveEntry(_))));
2429 assert!(!dir.join("escaped.txt").exists());
2430
2431 std::fs::remove_dir_all(&dir).ok();
2432 }
2433
2434 #[test]
2435 fn real_entry_count_matches_the_archive() {
2436 let dir = scratch("oxinav_test_extract_count");
2437 let zip_path = dir.join("z.zip");
2438 write_zip(&zip_path, &[("a", b"1"), ("b", b"2"), ("c", b"3")]);
2439 let tgz_path = dir.join("t.tar.gz");
2440 write_tar_gz(&tgz_path, &[("a", b"1"), ("b", b"2")]);
2441
2442 let fs = StdFilesystem;
2443 assert_eq!(
2444 fs.count_archive_entries(&zip_path, ArchiveFormat::Zip)
2445 .unwrap(),
2446 3
2447 );
2448 assert_eq!(
2449 fs.count_archive_entries(&tgz_path, ArchiveFormat::TarGz)
2450 .unwrap(),
2451 2
2452 );
2453
2454 std::fs::remove_dir_all(&dir).ok();
2455 }
2456
2457 #[test]
2458 fn resolve_directory_accepts_an_existing_directory() {
2459 let engine = OperationEngine::new(MockFs::tree(&[("/home/me/code", None)]));
2460
2461 let target = engine
2462 .resolve_directory("/home/me/code", Path::new("/home/me"))
2463 .unwrap();
2464
2465 assert_eq!(target, PathBuf::from("/home/me/code"));
2466 }
2467
2468 #[test]
2469 fn resolve_directory_expands_a_leading_tilde() {
2470 let engine =
2471 OperationEngine::new(MockFs::tree(&[("/home/me", None), ("/home/me/code", None)]));
2472 let home = Path::new("/home/me");
2473
2474 assert_eq!(
2475 engine.resolve_directory("~/code", home).unwrap(),
2476 PathBuf::from("/home/me/code")
2477 );
2478 assert_eq!(
2480 engine.resolve_directory("~", home).unwrap(),
2481 PathBuf::from("/home/me")
2482 );
2483 }
2484
2485 #[test]
2486 fn resolve_directory_leaves_an_interior_tilde_alone() {
2487 let engine = OperationEngine::new(MockFs::tree(&[("/data/back~up", None)]));
2488
2489 assert_eq!(
2490 engine
2491 .resolve_directory("/data/back~up", Path::new("/home/me"))
2492 .unwrap(),
2493 PathBuf::from("/data/back~up")
2494 );
2495 }
2496
2497 #[test]
2498 fn resolve_directory_rejects_a_missing_path() {
2499 let engine = OperationEngine::new(MockFs::tree(&[]));
2500
2501 let result = engine.resolve_directory("/nope", Path::new("/home/me"));
2502
2503 assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
2504 }
2505
2506 #[test]
2507 fn resolve_directory_rejects_a_file() {
2508 let engine = OperationEngine::new(MockFs::with(&["/home/me/notes.txt"]));
2509
2510 let result = engine.resolve_directory("/home/me/notes.txt", Path::new("/home/me"));
2511
2512 assert!(matches!(result, Err(OxiNavError::NotADirectory(_))));
2513 }
2514
2515 #[test]
2516 fn resolve_directory_rejects_a_blank_input() {
2517 let engine = OperationEngine::new(MockFs::tree(&[("/home/me", None)]));
2518
2519 assert!(engine
2520 .resolve_directory(" ", Path::new("/home/me"))
2521 .is_err());
2522 }
2523
2524 #[test]
2525 fn resolve_directory_trims_surrounding_whitespace() {
2526 let engine = OperationEngine::new(MockFs::tree(&[("/home/me/code", None)]));
2527
2528 assert_eq!(
2529 engine
2530 .resolve_directory(" /home/me/code ", Path::new("/home/me"))
2531 .unwrap(),
2532 PathBuf::from("/home/me/code")
2533 );
2534 }
2535
2536 #[test]
2537 fn read_capped_stops_at_the_cap() {
2538 let engine = OperationEngine::new(MockFs::tree(&[("/big", Some(4096))]));
2539
2540 let bytes = engine.read_capped(Path::new("/big"), 100).unwrap();
2541
2542 assert_eq!(bytes.len(), 100);
2543 }
2544
2545 #[test]
2546 fn read_capped_missing_source_errors() {
2547 let engine = OperationEngine::new(MockFs::with(&[]));
2548
2549 let result = engine.read_capped(Path::new("/gone"), 100);
2550
2551 assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
2552 }
2553
2554 #[test]
2555 fn copy_missing_source_errors() {
2556 let engine = OperationEngine::new(MockFs::with(&[]));
2557 let result = engine.execute(&Operation::Copy {
2558 src: "/a".into(),
2559 dest: "/b".into(),
2560 });
2561 assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
2562 }
2563
2564 #[test]
2565 fn copy_existing_dest_errors() {
2566 let engine = OperationEngine::new(MockFs::with(&["/a", "/b"]));
2567 let result = engine.execute(&Operation::Copy {
2568 src: "/a".into(),
2569 dest: "/b".into(),
2570 });
2571 assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
2572 }
2573
2574 #[test]
2575 fn delete_missing_source_errors() {
2576 let engine = OperationEngine::new(MockFs::with(&[]));
2577 let result = engine.execute(&Operation::Delete { path: "/a".into() });
2578 assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
2579 }
2580
2581 #[test]
2582 fn create_dir_existing_errors() {
2583 let engine = OperationEngine::new(MockFs::with(&["/dir"]));
2584 let result = engine.execute(&Operation::CreateDir {
2585 path: "/dir".into(),
2586 });
2587 assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
2588 }
2589
2590 #[test]
2591 fn exists_reports_true_for_present_path() {
2592 let engine = OperationEngine::new(MockFs::with(&["/a"]));
2593 assert!(engine.exists(Path::new("/a")));
2594 }
2595
2596 #[test]
2597 fn exists_reports_false_for_missing_path() {
2598 let engine = OperationEngine::new(MockFs::with(&["/a"]));
2599 assert!(!engine.exists(Path::new("/b")));
2600 }
2601
2602 #[test]
2603 fn recursive_copy_emits_progress_per_file() {
2604 let engine = OperationEngine::new(MockFs::tree(&[
2606 ("/src", None),
2607 ("/src/a.txt", Some(10)),
2608 ("/src/b.txt", Some(20)),
2609 ("/src/sub", None),
2610 ("/src/sub/c.txt", Some(30)),
2611 ]));
2612 let cancel = AtomicBool::new(false);
2613 let mut ticks = Vec::new();
2614 let outcome = engine
2615 .execute_with_progress(
2616 &Operation::Copy {
2617 src: "/src".into(),
2618 dest: "/dst".into(),
2619 },
2620 &cancel,
2621 &mut |p| ticks.push(p),
2622 )
2623 .unwrap();
2624
2625 assert_eq!(outcome, OperationOutcome::Completed);
2626 assert_eq!(
2628 ticks.iter().map(|p| p.items_done).collect::<Vec<_>>(),
2629 vec![1, 2, 3]
2630 );
2631 assert!(ticks
2633 .iter()
2634 .all(|p| p.items_total == 3 && p.bytes_total == 60));
2635 assert!(ticks.windows(2).all(|w| w[0].bytes_done <= w[1].bytes_done));
2637 assert_eq!(ticks.last().unwrap().bytes_done, 60);
2638 assert!(engine.exists(Path::new("/dst/a.txt")));
2640 assert!(engine.exists(Path::new("/dst/b.txt")));
2641 assert!(engine.exists(Path::new("/dst/sub/c.txt")));
2642 }
2643
2644 #[test]
2645 fn estimate_totals_counts_files_and_bytes() {
2646 let engine = OperationEngine::new(MockFs::tree(&[
2647 ("/src", None),
2648 ("/src/a.txt", Some(10)),
2649 ("/src/sub", None),
2650 ("/src/sub/b.txt", Some(30)),
2651 ]));
2652 assert_eq!(
2654 engine.estimate_totals(&Operation::Copy {
2655 src: "/src".into(),
2656 dest: "/dst".into(),
2657 }),
2658 (2, 40)
2659 );
2660 assert_eq!(
2662 engine.estimate_totals(&Operation::Delete {
2663 path: "/src/a.txt".into(),
2664 }),
2665 (1, 10)
2666 );
2667 }
2668
2669 #[test]
2670 fn cancel_stops_before_next_item() {
2671 let engine = OperationEngine::new(MockFs::tree(&[
2672 ("/src", None),
2673 ("/src/a", Some(1)),
2674 ("/src/b", Some(1)),
2675 ("/src/c", Some(1)),
2676 ]));
2677 let cancel = Arc::new(AtomicBool::new(false));
2678 let flag = cancel.clone();
2679 let mut ticks = 0usize;
2680 let outcome = engine
2681 .execute_with_progress(
2682 &Operation::Copy {
2683 src: "/src".into(),
2684 dest: "/dst".into(),
2685 },
2686 &cancel,
2687 &mut |_| {
2689 ticks += 1;
2690 flag.store(true, Ordering::Relaxed);
2691 },
2692 )
2693 .unwrap();
2694
2695 assert_eq!(outcome, OperationOutcome::Cancelled);
2696 assert_eq!(ticks, 1);
2698 let copied = ["/dst/a", "/dst/b", "/dst/c"]
2700 .iter()
2701 .filter(|p| engine.exists(&PathBuf::from(*p)))
2702 .count();
2703 assert_eq!(copied, 1);
2704 }
2705}