use crate::archive::{
classify_entry_path, detect_format, ArchiveEntry, ArchiveFormat, EntryKind, EntryTarget,
};
use crate::error::OxiNavError;
use crate::pane::matches_filter;
use crate::search::{pattern_error, snippet, SearchEnd, SearchHit, SearchQuery, MAX_HITS};
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Debug, Clone)]
pub enum Operation {
Copy {
src: PathBuf,
dest: PathBuf,
},
Move {
src: PathBuf,
dest: PathBuf,
},
Rename {
src: PathBuf,
dest: PathBuf,
},
Delete {
path: PathBuf,
},
CreateDir {
path: PathBuf,
},
CreateFile {
path: PathBuf,
},
CreateSymlink {
source: PathBuf,
link: PathBuf,
},
ExtractArchive {
archive: PathBuf,
dest_dir: PathBuf,
},
CreateArchive {
sources: Vec<PathBuf>,
base_dir: PathBuf,
archive: PathBuf,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OperationStatus {
Pending,
InProgress,
Done,
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Progress {
pub current: PathBuf,
pub items_done: usize,
pub items_total: usize,
pub bytes_done: u64,
pub bytes_total: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperationOutcome {
Completed,
Cancelled,
}
pub trait Filesystem: Send + Sync {
fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError>;
fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError>;
fn delete(&self, path: &Path) -> Result<(), OxiNavError>;
fn create_dir(&self, path: &Path) -> Result<(), OxiNavError>;
fn create_file(&self, path: &Path) -> Result<(), OxiNavError>;
fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError>;
fn exists(&self, path: &Path) -> bool;
fn is_symlink(&self, path: &Path) -> bool;
fn is_dir(&self, path: &Path) -> bool;
fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError>;
fn size(&self, path: &Path) -> u64;
fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError>;
fn count_archive_entries(
&self,
archive: &Path,
format: ArchiveFormat,
) -> Result<usize, OxiNavError>;
fn extract_archive(
&self,
archive: &Path,
dest_dir: &Path,
format: ArchiveFormat,
on_entry: &mut dyn FnMut(&Path),
) -> Result<(), OxiNavError>;
fn write_archive(
&self,
archive: &Path,
format: ArchiveFormat,
entries: &[ArchiveEntry],
on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
) -> Result<ControlFlow<()>, OxiNavError>;
fn search(
&self,
root: &Path,
query: &SearchQuery,
cancel: &AtomicBool,
on_hit: &mut dyn FnMut(SearchHit) -> ControlFlow<()>,
) -> Result<ControlFlow<()>, OxiNavError>;
}
pub struct OperationEngine<F: Filesystem> {
fs: F,
}
#[derive(Debug, Clone, Copy)]
pub struct StdFilesystem;
impl Filesystem for StdFilesystem {
fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
if src.is_dir() {
copy_dir_recursive(src, dest).map_err(|source| OxiNavError::Io {
path: dest.to_path_buf(),
source,
})
} else {
std::fs::copy(src, dest)
.map(|_| ())
.map_err(|source| OxiNavError::Io {
path: dest.to_path_buf(),
source,
})
}
}
fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
std::fs::rename(src, dest).map_err(|source| OxiNavError::Io {
path: dest.to_path_buf(),
source,
})
}
fn delete(&self, path: &Path) -> Result<(), OxiNavError> {
let result = if path.is_dir() {
std::fs::remove_dir_all(path)
} else {
std::fs::remove_file(path)
};
result.map_err(|source| OxiNavError::Io {
path: path.to_path_buf(),
source,
})
}
fn create_dir(&self, path: &Path) -> Result<(), OxiNavError> {
std::fs::create_dir(path).map_err(|source| OxiNavError::Io {
path: path.to_path_buf(),
source,
})
}
fn create_file(&self, path: &Path) -> Result<(), OxiNavError> {
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map(|_| ())
.map_err(|source| OxiNavError::Io {
path: path.to_path_buf(),
source,
})
}
fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError> {
#[cfg(unix)]
let result = std::os::unix::fs::symlink(source, link);
#[cfg(windows)]
let result = if source.is_dir() {
std::os::windows::fs::symlink_dir(source, link)
} else {
std::os::windows::fs::symlink_file(source, link)
};
result.map_err(|source| OxiNavError::Io {
path: link.to_path_buf(),
source,
})
}
fn exists(&self, path: &Path) -> bool {
path.exists()
}
fn is_symlink(&self, path: &Path) -> bool {
path.is_symlink()
}
fn is_dir(&self, path: &Path) -> bool {
path.is_dir()
}
fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError> {
let entries = std::fs::read_dir(path).map_err(|source| OxiNavError::Io {
path: path.to_path_buf(),
source,
})?;
let mut out = Vec::new();
for entry in entries {
let entry = entry.map_err(|source| OxiNavError::Io {
path: path.to_path_buf(),
source,
})?;
out.push(entry.path());
}
Ok(out)
}
fn size(&self, path: &Path) -> u64 {
std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
}
fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
use std::io::Read;
let io_error = |source| OxiNavError::Io {
path: path.to_path_buf(),
source,
};
let file = std::fs::File::open(path).map_err(io_error)?;
let mut buffer = Vec::new();
file.take(max as u64)
.read_to_end(&mut buffer)
.map_err(io_error)?;
Ok(buffer)
}
fn count_archive_entries(
&self,
archive: &Path,
format: ArchiveFormat,
) -> Result<usize, OxiNavError> {
let file = open_archive(archive)?;
match format {
ArchiveFormat::Zip => {
let zip = zip::ZipArchive::new(file).map_err(|e| archive_error(archive, e))?;
Ok(zip.len())
}
ArchiveFormat::Tar => {
let mut tar = tar::Archive::new(file);
let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
Ok(entries.count())
}
ArchiveFormat::TarGz => {
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
Ok(entries.count())
}
}
}
fn extract_archive(
&self,
archive: &Path,
dest_dir: &Path,
format: ArchiveFormat,
on_entry: &mut dyn FnMut(&Path),
) -> Result<(), OxiNavError> {
let file = open_archive(archive)?;
match format {
ArchiveFormat::Zip => {
let mut zip = zip::ZipArchive::new(file).map_err(|e| archive_error(archive, e))?;
for index in 0..zip.len() {
let mut entry = zip.by_index(index).map_err(|e| archive_error(archive, e))?;
let raw = entry.name().to_string();
let Some(target) = resolve_entry(dest_dir, &raw)? else {
continue;
};
if entry.is_dir() {
create_dir_all(&target)?;
} else {
if let Some(parent) = target.parent() {
create_dir_all(parent)?;
}
let mut out =
std::fs::File::create(&target).map_err(|source| OxiNavError::Io {
path: target.clone(),
source,
})?;
std::io::copy(&mut entry, &mut out).map_err(|source| OxiNavError::Io {
path: target.clone(),
source,
})?;
}
#[cfg(unix)]
if let Some(mode) = entry.unix_mode() {
use std::os::unix::fs::PermissionsExt;
let permissions = std::fs::Permissions::from_mode(mode & 0o777);
std::fs::set_permissions(&target, permissions).map_err(|source| {
OxiNavError::Io {
path: target.clone(),
source,
}
})?;
}
on_entry(&target);
}
Ok(())
}
ArchiveFormat::Tar => extract_tar(tar::Archive::new(file), archive, dest_dir, on_entry),
ArchiveFormat::TarGz => extract_tar(
tar::Archive::new(flate2::read::GzDecoder::new(file)),
archive,
dest_dir,
on_entry,
),
}
}
fn write_archive(
&self,
archive: &Path,
format: ArchiveFormat,
entries: &[ArchiveEntry],
on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
) -> Result<ControlFlow<()>, OxiNavError> {
let name = archive.file_name().unwrap_or_default().to_string_lossy();
let temp = archive.with_file_name(format!(".{name}.oxinav-partial"));
let io_error = |path: &Path| {
let path = path.to_path_buf();
move |source| OxiNavError::Io { path, source }
};
let written = (|| {
let file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)
.map_err(io_error(&temp))?;
let file = match format {
ArchiveFormat::Zip => write_zip(file, archive, entries, on_entry)?,
ArchiveFormat::Tar => write_tar(file, archive, entries, on_entry)?,
ArchiveFormat::TarGz => {
let encoder =
flate2::write::GzEncoder::new(file, flate2::Compression::default());
match write_tar(encoder, archive, entries, on_entry)? {
Some(encoder) => Some(encoder.finish().map_err(io_error(&temp))?),
None => None,
}
}
};
let Some(file) = file else {
return Ok(ControlFlow::Break(()));
};
file.sync_all().map_err(io_error(&temp))?;
std::fs::rename(&temp, archive).map_err(io_error(archive))?;
Ok(ControlFlow::Continue(()))
})();
if !matches!(written, Ok(ControlFlow::Continue(()))) {
let _ = std::fs::remove_file(&temp);
}
written
}
fn search(
&self,
root: &Path,
query: &SearchQuery,
cancel: &AtomicBool,
on_hit: &mut dyn FnMut(SearchHit) -> ControlFlow<()>,
) -> Result<ControlFlow<()>, OxiNavError> {
use grep_regex::RegexMatcherBuilder;
use grep_searcher::{sinks::Lossy, BinaryDetection, SearcherBuilder};
let matcher = RegexMatcherBuilder::new()
.case_insensitive(query.case_insensitive)
.line_terminator(Some(b'\n'))
.build(&query.pattern)
.map_err(|error| OxiNavError::InvalidPattern(pattern_error(&error.to_string())))?;
let mut searcher = SearcherBuilder::new()
.binary_detection(BinaryDetection::quit(b'\0'))
.line_number(true)
.build();
let walker = ignore::WalkBuilder::new(root)
.hidden(!query.include_hidden)
.sort_by_file_name(|a, b| a.cmp(b))
.build();
for entry in walker {
if cancel.load(Ordering::Relaxed) {
return Ok(ControlFlow::Break(()));
}
let Ok(entry) = entry else { continue };
if !entry.file_type().is_some_and(|kind| kind.is_file()) {
continue;
}
if let Some(glob) = &query.name_glob {
let name = entry.file_name().to_string_lossy();
if !matches_filter(&name, glob) {
continue;
}
}
let mut flow = ControlFlow::Continue(());
let path = entry.path();
let _ = searcher.search_path(
&matcher,
path,
Lossy(|line, text| {
flow = on_hit(SearchHit {
path: path.to_path_buf(),
line,
text: snippet(text),
});
Ok(flow.is_continue())
}),
);
if flow.is_break() {
return Ok(ControlFlow::Break(()));
}
}
Ok(ControlFlow::Continue(()))
}
}
fn zip_entry_name(entry: &ArchiveEntry) -> Result<String, OxiNavError> {
let parts: Option<Vec<&str>> = entry
.name
.components()
.map(|part| part.as_os_str().to_str())
.collect();
parts
.map(|parts| parts.join("/"))
.ok_or_else(|| OxiNavError::Io {
path: entry.source.clone(),
source: std::io::Error::other("zip entry names must be UTF-8"),
})
}
fn unix_mode(path: &Path) -> Option<u32> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::symlink_metadata(path)
.ok()
.map(|metadata| metadata.permissions().mode() & 0o7777)
}
#[cfg(not(unix))]
{
let _ = path;
None
}
}
fn zip_time(path: &Path) -> Option<zip::DateTime> {
use chrono::{Datelike, Timelike};
let modified = std::fs::symlink_metadata(path).ok()?.modified().ok()?;
let local: chrono::DateTime<chrono::Local> = modified.into();
zip::DateTime::from_date_and_time(
u16::try_from(local.year()).ok()?,
local.month() as u8,
local.day() as u8,
local.hour() as u8,
local.minute() as u8,
local.second() as u8,
)
.ok()
}
fn write_zip(
file: std::fs::File,
archive: &Path,
entries: &[ArchiveEntry],
on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
) -> Result<Option<std::fs::File>, OxiNavError> {
use zip::write::SimpleFileOptions;
let mut zip = zip::ZipWriter::new(file);
for entry in entries {
let name = zip_entry_name(entry)?;
let source_error = |source| OxiNavError::Io {
path: entry.source.clone(),
source,
};
let mut options =
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
if let Some(mode) = unix_mode(&entry.source) {
options = options.unix_permissions(mode);
}
if let Some(time) = zip_time(&entry.source) {
options = options.last_modified_time(time);
}
match entry.kind {
EntryKind::Dir => zip
.add_directory(name, options)
.map_err(|e| archive_error(archive, e))?,
EntryKind::Symlink => {
let target = std::fs::read_link(&entry.source).map_err(source_error)?;
zip.add_symlink(name, target.to_string_lossy(), options)
.map_err(|e| archive_error(archive, e))?;
}
EntryKind::File => {
let mut source = std::fs::File::open(&entry.source).map_err(source_error)?;
let len = source.metadata().map_err(source_error)?.len();
let options = options.large_file(len >= u64::from(u32::MAX));
zip.start_file(name, options)
.map_err(|e| archive_error(archive, e))?;
std::io::copy(&mut source, &mut zip).map_err(source_error)?;
}
}
if on_entry(&entry.source).is_break() {
return Ok(None);
}
}
zip.finish()
.map(Some)
.map_err(|e| archive_error(archive, e))
}
fn write_tar<W: std::io::Write>(
writer: W,
archive: &Path,
entries: &[ArchiveEntry],
on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
) -> Result<Option<W>, OxiNavError> {
let mut builder = tar::Builder::new(writer);
builder.follow_symlinks(false);
for entry in entries {
builder
.append_path_with_name(&entry.source, &entry.name)
.map_err(|source| OxiNavError::Io {
path: entry.source.clone(),
source,
})?;
if on_entry(&entry.source).is_break() {
return Ok(None);
}
}
builder
.into_inner()
.map(Some)
.map_err(|source| OxiNavError::Io {
path: archive.to_path_buf(),
source,
})
}
fn expand_home(input: &str, home: &Path) -> PathBuf {
match input.strip_prefix('~') {
Some("") => home.to_path_buf(),
Some(rest) => match rest.strip_prefix('/') {
Some(relative) => home.join(relative),
None => PathBuf::from(input),
},
None => PathBuf::from(input),
}
}
fn open_archive(archive: &Path) -> Result<std::fs::File, OxiNavError> {
std::fs::File::open(archive).map_err(|source| OxiNavError::Io {
path: archive.to_path_buf(),
source,
})
}
fn archive_error<E: std::fmt::Display>(archive: &Path, error: E) -> OxiNavError {
OxiNavError::Io {
path: archive.to_path_buf(),
source: std::io::Error::other(error.to_string()),
}
}
fn create_dir_all(path: &Path) -> Result<(), OxiNavError> {
std::fs::create_dir_all(path).map_err(|source| OxiNavError::Io {
path: path.to_path_buf(),
source,
})
}
fn resolve_entry(dest_dir: &Path, raw: &str) -> Result<Option<PathBuf>, OxiNavError> {
match classify_entry_path(Path::new(raw)) {
EntryTarget::Within(relative) => Ok(Some(dest_dir.join(relative))),
EntryTarget::ArchiveRoot => Ok(None),
EntryTarget::Escaping => Err(OxiNavError::UnsafeArchiveEntry(raw.to_string())),
}
}
fn extract_tar<R: std::io::Read>(
mut tar: tar::Archive<R>,
archive: &Path,
dest_dir: &Path,
on_entry: &mut dyn FnMut(&Path),
) -> Result<(), OxiNavError> {
let entries = tar.entries().map_err(|e| archive_error(archive, e))?;
for entry in entries {
let mut entry = entry.map_err(|e| archive_error(archive, e))?;
let raw = entry
.path()
.map_err(|e| archive_error(archive, e))?
.to_string_lossy()
.into_owned();
let Some(target) = resolve_entry(dest_dir, &raw)? else {
continue;
};
if entry.header().entry_type().is_dir() {
create_dir_all(&target)?;
} else {
if let Some(parent) = target.parent() {
create_dir_all(parent)?;
}
entry
.unpack(&target)
.map_err(|e| archive_error(archive, e))?;
}
on_entry(&target);
}
Ok(())
}
impl<F: Filesystem> OperationEngine<F> {
pub fn new(fs: F) -> Self {
Self { fs }
}
pub fn exists(&self, path: &Path) -> bool {
self.fs.exists(path)
}
pub fn resolve_directory(&self, input: &str, home: &Path) -> Result<PathBuf, OxiNavError> {
let trimmed = input.trim();
if trimmed.is_empty() {
return Err(OxiNavError::SourceNotFound(PathBuf::from(trimmed)));
}
let expanded = expand_home(trimmed, home);
if !self.fs.exists(&expanded) {
return Err(OxiNavError::SourceNotFound(expanded));
}
if !self.fs.is_dir(&expanded) {
return Err(OxiNavError::NotADirectory(expanded));
}
Ok(expanded)
}
fn check_extractable(
&self,
archive: &Path,
dest_dir: &Path,
) -> Result<ArchiveFormat, OxiNavError> {
if !self.fs.exists(archive) {
return Err(OxiNavError::SourceNotFound(archive.to_path_buf()));
}
if !self.fs.exists(dest_dir) {
return Err(OxiNavError::SourceNotFound(dest_dir.to_path_buf()));
}
detect_format(archive).ok_or_else(|| OxiNavError::UnsupportedArchive(archive.to_path_buf()))
}
fn check_packable(
&self,
sources: &[PathBuf],
archive: &Path,
) -> Result<ArchiveFormat, OxiNavError> {
let format = detect_format(archive)
.ok_or_else(|| OxiNavError::UnsupportedArchive(archive.to_path_buf()))?;
if self.fs.exists(archive) || self.fs.is_symlink(archive) {
return Err(OxiNavError::DestinationExists(archive.to_path_buf()));
}
if let Some(missing) = sources
.iter()
.find(|source| !self.fs.exists(source) && !self.fs.is_symlink(source))
{
return Err(OxiNavError::SourceNotFound(missing.clone()));
}
Ok(format)
}
fn archive_entries(
&self,
sources: &[PathBuf],
base_dir: &Path,
) -> Result<Vec<ArchiveEntry>, OxiNavError> {
let mut entries = Vec::new();
for source in sources {
self.collect_entries(source, base_dir, &mut entries)?;
}
Ok(entries)
}
fn collect_entries(
&self,
path: &Path,
base_dir: &Path,
entries: &mut Vec<ArchiveEntry>,
) -> Result<(), OxiNavError> {
let name = match path.strip_prefix(base_dir) {
Ok(relative) => relative.to_path_buf(),
Err(_) => PathBuf::from(path.file_name().unwrap_or_default()),
};
let kind = if self.fs.is_symlink(path) {
EntryKind::Symlink
} else if self.fs.is_dir(path) {
EntryKind::Dir
} else {
EntryKind::File
};
entries.push(ArchiveEntry {
source: path.to_path_buf(),
name,
kind,
});
if kind == EntryKind::Dir {
let mut children = self.fs.read_dir(path)?;
children.sort();
for child in children {
self.collect_entries(&child, base_dir, entries)?;
}
}
Ok(())
}
pub fn search(
&self,
root: &Path,
query: &SearchQuery,
cancel: &AtomicBool,
on_hit: &mut dyn FnMut(SearchHit),
) -> Result<SearchEnd, OxiNavError> {
let mut count = 0;
let mut capped = false;
let flow = self.fs.search(root, query, cancel, &mut |hit| {
if count == MAX_HITS {
capped = true;
return ControlFlow::Break(());
}
count += 1;
on_hit(hit);
ControlFlow::Continue(())
})?;
Ok(if capped {
SearchEnd::Capped
} else if flow.is_break() {
SearchEnd::Stopped
} else {
SearchEnd::Finished
})
}
pub fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
if !self.fs.exists(path) {
return Err(OxiNavError::SourceNotFound(path.to_path_buf()));
}
self.fs.read_capped(path, max)
}
pub fn execute(&self, op: &Operation) -> Result<(), OxiNavError> {
match op {
Operation::Copy { src, dest } => {
if !self.fs.exists(src) {
return Err(OxiNavError::SourceNotFound(src.clone()));
}
if self.fs.exists(dest) {
return Err(OxiNavError::DestinationExists(dest.clone()));
}
self.fs.copy(src, dest)
}
Operation::Move { src, dest } => {
if !self.fs.exists(src) {
return Err(OxiNavError::SourceNotFound(src.clone()));
}
if self.fs.exists(dest) {
return Err(OxiNavError::DestinationExists(dest.clone()));
}
match self.fs.rename(src, dest) {
Ok(()) => Ok(()),
Err(_) => {
self.fs.copy(src, dest)?;
self.fs.delete(src)
}
}
}
Operation::Rename { src, dest } => {
if !self.fs.exists(src) {
return Err(OxiNavError::SourceNotFound(src.clone()));
}
if self.fs.exists(dest) {
return Err(OxiNavError::DestinationExists(dest.clone()));
}
self.fs.rename(src, dest)
}
Operation::Delete { path } => {
if !self.fs.exists(path) {
return Err(OxiNavError::SourceNotFound(path.clone()));
}
self.fs.delete(path)
}
Operation::CreateDir { path } => {
if self.fs.exists(path) {
return Err(OxiNavError::DestinationExists(path.clone()));
}
self.fs.create_dir(path)
}
Operation::CreateFile { path } => {
if self.fs.exists(path) {
return Err(OxiNavError::DestinationExists(path.clone()));
}
self.fs.create_file(path)
}
Operation::CreateSymlink { source, link } => {
if !self.fs.exists(source) {
return Err(OxiNavError::SourceNotFound(source.clone()));
}
if self.fs.exists(link) {
return Err(OxiNavError::DestinationExists(link.clone()));
}
self.fs.create_symlink(source, link)
}
Operation::ExtractArchive { archive, dest_dir } => {
let format = self.check_extractable(archive, dest_dir)?;
self.fs
.extract_archive(archive, dest_dir, format, &mut |_| {})
}
Operation::CreateArchive { .. } => self
.execute_with_progress(op, &AtomicBool::new(false), &mut |_| {})
.map(|_| ()),
}
}
pub fn execute_with_progress(
&self,
op: &Operation,
cancel: &AtomicBool,
on_progress: &mut dyn FnMut(Progress),
) -> Result<OperationOutcome, OxiNavError> {
match op {
Operation::Copy { src, dest } => {
if !self.fs.exists(src) {
return Err(OxiNavError::SourceNotFound(src.clone()));
}
if self.fs.exists(dest) {
return Err(OxiNavError::DestinationExists(dest.clone()));
}
let (items_total, bytes_total) = self.walk_totals(src);
let mut state = ProgressState::new(items_total, bytes_total);
self.copy_recursive(src, dest, cancel, &mut state, on_progress)?;
Ok(outcome(cancel))
}
Operation::Delete { path } => {
if !self.fs.exists(path) {
return Err(OxiNavError::SourceNotFound(path.clone()));
}
let (items_total, bytes_total) = self.walk_totals(path);
let mut state = ProgressState::new(items_total, bytes_total);
self.delete_recursive(path, cancel, &mut state, on_progress)?;
Ok(outcome(cancel))
}
Operation::Move { src, dest } => {
if !self.fs.exists(src) {
return Err(OxiNavError::SourceNotFound(src.clone()));
}
if self.fs.exists(dest) {
return Err(OxiNavError::DestinationExists(dest.clone()));
}
let (items_total, bytes_total) = self.walk_totals(src);
if self.fs.rename(src, dest).is_ok() {
on_progress(Progress {
current: src.clone(),
items_done: items_total,
items_total,
bytes_done: bytes_total,
bytes_total,
});
return Ok(OperationOutcome::Completed);
}
let mut state = ProgressState::new(items_total, bytes_total);
self.copy_recursive(src, dest, cancel, &mut state, on_progress)?;
if cancel.load(Ordering::Relaxed) {
return Ok(OperationOutcome::Cancelled);
}
self.fs.delete(src)?;
Ok(OperationOutcome::Completed)
}
Operation::Rename { dest, .. } => {
self.execute(op)?;
on_progress(single_tick(dest.clone()));
Ok(OperationOutcome::Completed)
}
Operation::CreateSymlink { link, .. } => {
self.execute(op)?;
on_progress(single_tick(link.clone()));
Ok(OperationOutcome::Completed)
}
Operation::ExtractArchive { archive, dest_dir } => {
let format = self.check_extractable(archive, dest_dir)?;
let items_total = self.fs.count_archive_entries(archive, format)?;
let mut items_done = 0;
self.fs
.extract_archive(archive, dest_dir, format, &mut |written| {
items_done += 1;
on_progress(Progress {
current: written.to_path_buf(),
items_done,
items_total,
bytes_done: 0,
bytes_total: 0,
});
})?;
Ok(OperationOutcome::Completed)
}
Operation::CreateDir { path } | Operation::CreateFile { path } => {
self.execute(op)?;
on_progress(single_tick(path.clone()));
Ok(OperationOutcome::Completed)
}
Operation::CreateArchive {
sources,
base_dir,
archive,
} => {
let format = self.check_packable(sources, archive)?;
let entries = self.archive_entries(sources, base_dir)?;
let sizes: Vec<u64> = entries
.iter()
.map(|entry| match entry.kind {
EntryKind::File => self.fs.size(&entry.source),
EntryKind::Dir | EntryKind::Symlink => 0,
})
.collect();
let mut state = ProgressState::new(entries.len(), sizes.iter().sum());
if cancel.load(Ordering::Relaxed) {
return Ok(OperationOutcome::Cancelled);
}
let flow = self
.fs
.write_archive(archive, format, &entries, &mut |written| {
state.advance(sizes[state.items_done]);
on_progress(state.snapshot(written));
if cancel.load(Ordering::Relaxed) {
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
})?;
Ok(if flow.is_break() {
OperationOutcome::Cancelled
} else {
OperationOutcome::Completed
})
}
}
}
pub fn estimate_totals(&self, op: &Operation) -> (usize, u64) {
match op {
Operation::Copy { src, .. } | Operation::Move { src, .. } => self.walk_totals(src),
Operation::Delete { path } => self.walk_totals(path),
Operation::Rename { .. }
| Operation::CreateDir { .. }
| Operation::CreateFile { .. }
| Operation::CreateSymlink { .. } => (1, 0),
Operation::ExtractArchive { archive, dest_dir } => self
.check_extractable(archive, dest_dir)
.and_then(|format| self.fs.count_archive_entries(archive, format))
.map(|items| (items, 0))
.unwrap_or((1, 0)),
Operation::CreateArchive {
sources, base_dir, ..
} => self
.archive_entries(sources, base_dir)
.map(|entries| {
let bytes = entries
.iter()
.filter(|entry| entry.kind == EntryKind::File)
.map(|entry| self.fs.size(&entry.source))
.sum();
(entries.len(), bytes)
})
.unwrap_or((1, 0)),
}
}
fn walk_totals(&self, path: &Path) -> (usize, u64) {
if self.fs.is_dir(path) {
let mut items = 0;
let mut bytes = 0;
if let Ok(children) = self.fs.read_dir(path) {
for child in &children {
let (i, b) = self.walk_totals(child);
items += i;
bytes += b;
}
}
(items, bytes)
} else {
(1, self.fs.size(path))
}
}
fn copy_recursive(
&self,
src: &Path,
dest: &Path,
cancel: &AtomicBool,
state: &mut ProgressState,
on_progress: &mut dyn FnMut(Progress),
) -> Result<(), OxiNavError> {
if cancel.load(Ordering::Relaxed) {
return Ok(());
}
if self.fs.is_dir(src) {
self.fs.create_dir(dest)?;
for child in self.fs.read_dir(src)? {
if cancel.load(Ordering::Relaxed) {
return Ok(());
}
let child_dest = match child.file_name() {
Some(name) => dest.join(name),
None => dest.to_path_buf(),
};
self.copy_recursive(&child, &child_dest, cancel, state, on_progress)?;
}
} else {
self.fs.copy(src, dest)?;
state.advance(self.fs.size(src));
on_progress(state.snapshot(src));
}
Ok(())
}
fn delete_recursive(
&self,
path: &Path,
cancel: &AtomicBool,
state: &mut ProgressState,
on_progress: &mut dyn FnMut(Progress),
) -> Result<(), OxiNavError> {
if cancel.load(Ordering::Relaxed) {
return Ok(());
}
if self.fs.is_dir(path) {
for child in self.fs.read_dir(path)? {
if cancel.load(Ordering::Relaxed) {
return Ok(());
}
self.delete_recursive(&child, cancel, state, on_progress)?;
}
if cancel.load(Ordering::Relaxed) {
return Ok(());
}
self.fs.delete(path)?;
} else {
let bytes = self.fs.size(path);
self.fs.delete(path)?;
state.advance(bytes);
on_progress(state.snapshot(path));
}
Ok(())
}
}
struct ProgressState {
items_done: usize,
items_total: usize,
bytes_done: u64,
bytes_total: u64,
}
impl ProgressState {
fn new(items_total: usize, bytes_total: u64) -> Self {
Self {
items_done: 0,
items_total,
bytes_done: 0,
bytes_total,
}
}
fn advance(&mut self, bytes: u64) {
self.items_done += 1;
self.bytes_done += bytes;
}
fn snapshot(&self, current: &Path) -> Progress {
Progress {
current: current.to_path_buf(),
items_done: self.items_done,
items_total: self.items_total,
bytes_done: self.bytes_done,
bytes_total: self.bytes_total,
}
}
}
fn outcome(cancel: &AtomicBool) -> OperationOutcome {
if cancel.load(Ordering::Relaxed) {
OperationOutcome::Cancelled
} else {
OperationOutcome::Completed
}
}
fn single_tick(current: PathBuf) -> Progress {
Progress {
current,
items_done: 1,
items_total: 1,
bytes_done: 0,
bytes_total: 0,
}
}
fn copy_dir_recursive(src: &Path, dest: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dest)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let dest_path = dest.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_dir_recursive(&entry.path(), &dest_path)?;
} else {
std::fs::copy(entry.path(), &dest_path)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct MockFs {
nodes: Arc<Mutex<HashMap<PathBuf, Option<u64>>>>,
archives: Arc<Mutex<HashMap<PathBuf, Vec<String>>>>,
links: Arc<Mutex<HashSet<PathBuf>>>,
unreadable: Arc<Mutex<HashSet<PathBuf>>>,
packed: Arc<Mutex<PackedArchives>>,
contents: Arc<Mutex<HashMap<PathBuf, String>>>,
}
type PackedArchives = HashMap<PathBuf, Vec<(PathBuf, EntryKind)>>;
impl MockFs {
fn with(paths: &[&str]) -> Self {
Self {
nodes: Arc::new(Mutex::new(
paths.iter().map(|p| (PathBuf::from(p), Some(0))).collect(),
)),
archives: Arc::new(Mutex::new(HashMap::new())),
links: Arc::default(),
unreadable: Arc::default(),
packed: Arc::default(),
contents: Arc::default(),
}
}
fn with_archive(self, path: &str, entries: &[&str]) -> Self {
self.nodes
.lock()
.unwrap()
.insert(PathBuf::from(path), Some(0));
self.archives.lock().unwrap().insert(
PathBuf::from(path),
entries.iter().map(|e| e.to_string()).collect(),
);
self
}
fn with_content(self, path: &str, text: &str) -> Self {
{
let mut nodes = self.nodes.lock().unwrap();
let path = PathBuf::from(path);
let mut parent = path.parent();
while let Some(dir) = parent {
nodes.entry(dir.to_path_buf()).or_insert(None);
parent = dir.parent();
}
nodes.insert(path.clone(), Some(text.len() as u64));
self.contents.lock().unwrap().insert(path, text.to_string());
}
self
}
fn with_link(self, path: &str) -> Self {
self.links.lock().unwrap().insert(PathBuf::from(path));
self
}
fn with_unreadable(self, path: &str) -> Self {
self.unreadable.lock().unwrap().insert(PathBuf::from(path));
self
}
fn packed(&self, archive: &str) -> Vec<(String, EntryKind)> {
self.packed
.lock()
.unwrap()
.get(Path::new(archive))
.map(|entries| {
entries
.iter()
.map(|(name, kind)| (name.display().to_string(), *kind))
.collect()
})
.unwrap_or_default()
}
fn archive_entries(&self, archive: &Path) -> Vec<String> {
self.archives
.lock()
.unwrap()
.get(archive)
.cloned()
.unwrap_or_default()
}
fn tree(entries: &[(&str, Option<u64>)]) -> Self {
Self {
nodes: Arc::new(Mutex::new(
entries
.iter()
.map(|(p, size)| (PathBuf::from(p), *size))
.collect(),
)),
archives: Arc::new(Mutex::new(HashMap::new())),
links: Arc::default(),
unreadable: Arc::default(),
packed: Arc::default(),
contents: Arc::default(),
}
}
}
impl Filesystem for MockFs {
fn copy(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
let mut nodes = self.nodes.lock().unwrap();
let value = nodes.get(src).copied().unwrap_or(Some(0));
nodes.insert(dest.to_path_buf(), value);
Ok(())
}
fn rename(&self, src: &Path, dest: &Path) -> Result<(), OxiNavError> {
let mut nodes = self.nodes.lock().unwrap();
let value = nodes.remove(src).unwrap_or(Some(0));
nodes.insert(dest.to_path_buf(), value);
Ok(())
}
fn delete(&self, path: &Path) -> Result<(), OxiNavError> {
let mut nodes = self.nodes.lock().unwrap();
nodes.remove(path);
let prefix = format!("{}/", path.display());
nodes.retain(|p, _| !p.display().to_string().starts_with(&prefix));
Ok(())
}
fn create_dir(&self, path: &Path) -> Result<(), OxiNavError> {
self.nodes.lock().unwrap().insert(path.to_path_buf(), None);
Ok(())
}
fn create_file(&self, path: &Path) -> Result<(), OxiNavError> {
self.nodes
.lock()
.unwrap()
.insert(path.to_path_buf(), Some(0));
Ok(())
}
fn create_symlink(&self, source: &Path, link: &Path) -> Result<(), OxiNavError> {
let mut nodes = self.nodes.lock().unwrap();
let value = nodes.get(source).copied().unwrap_or(Some(0));
nodes.insert(link.to_path_buf(), value);
Ok(())
}
fn exists(&self, path: &Path) -> bool {
self.nodes.lock().unwrap().contains_key(path)
}
fn is_symlink(&self, path: &Path) -> bool {
self.links.lock().unwrap().contains(path)
}
fn is_dir(&self, path: &Path) -> bool {
matches!(self.nodes.lock().unwrap().get(path), Some(None))
}
fn read_dir(&self, path: &Path) -> Result<Vec<PathBuf>, OxiNavError> {
let nodes = self.nodes.lock().unwrap();
Ok(nodes
.keys()
.filter(|p| p.parent() == Some(path))
.cloned()
.collect())
}
fn size(&self, path: &Path) -> u64 {
match self.nodes.lock().unwrap().get(path) {
Some(Some(size)) => *size,
_ => 0,
}
}
fn read_capped(&self, path: &Path, max: usize) -> Result<Vec<u8>, OxiNavError> {
let len = (self.size(path) as usize).min(max);
Ok(vec![b'a'; len])
}
fn count_archive_entries(
&self,
archive: &Path,
_format: ArchiveFormat,
) -> Result<usize, OxiNavError> {
Ok(self.archive_entries(archive).len())
}
fn extract_archive(
&self,
archive: &Path,
dest_dir: &Path,
_format: ArchiveFormat,
on_entry: &mut dyn FnMut(&Path),
) -> Result<(), OxiNavError> {
for raw in self.archive_entries(archive) {
let Some(target) = resolve_entry(dest_dir, &raw)? else {
continue;
};
self.nodes.lock().unwrap().insert(target.clone(), Some(0));
on_entry(&target);
}
Ok(())
}
fn write_archive(
&self,
archive: &Path,
_format: ArchiveFormat,
entries: &[ArchiveEntry],
on_entry: &mut dyn FnMut(&Path) -> ControlFlow<()>,
) -> Result<ControlFlow<()>, OxiNavError> {
let mut written = Vec::new();
for entry in entries {
if self.unreadable.lock().unwrap().contains(&entry.source) {
return Err(OxiNavError::Io {
path: entry.source.clone(),
source: std::io::Error::from(std::io::ErrorKind::PermissionDenied),
});
}
written.push((entry.name.clone(), entry.kind));
if on_entry(&entry.source).is_break() {
return Ok(ControlFlow::Break(()));
}
}
self.nodes
.lock()
.unwrap()
.insert(archive.to_path_buf(), Some(0));
self.packed
.lock()
.unwrap()
.insert(archive.to_path_buf(), written);
Ok(ControlFlow::Continue(()))
}
fn search(
&self,
root: &Path,
query: &SearchQuery,
cancel: &AtomicBool,
on_hit: &mut dyn FnMut(SearchHit) -> ControlFlow<()>,
) -> Result<ControlFlow<()>, OxiNavError> {
let fold = |text: &str| {
if query.case_insensitive {
text.to_lowercase()
} else {
text.to_string()
}
};
let needle = fold(&query.pattern);
let mut files: Vec<(PathBuf, String)> = self
.contents
.lock()
.unwrap()
.iter()
.map(|(path, text)| (path.clone(), text.clone()))
.collect();
files.sort();
for (path, text) in files {
if cancel.load(Ordering::Relaxed) {
return Ok(ControlFlow::Break(()));
}
let Ok(relative) = path.strip_prefix(root) else {
continue;
};
let hidden = relative
.components()
.any(|part| part.as_os_str().to_string_lossy().starts_with('.'));
if hidden && !query.include_hidden {
continue;
}
let name = path.file_name().unwrap_or_default().to_string_lossy();
if let Some(glob) = &query.name_glob {
if !matches_filter(&name, glob) {
continue;
}
}
for (index, line) in text.lines().enumerate() {
if fold(line).contains(&needle) {
let hit = SearchHit {
path: path.clone(),
line: index as u64 + 1,
text: snippet(line),
};
if on_hit(hit).is_break() {
return Ok(ControlFlow::Break(()));
}
}
}
}
Ok(ControlFlow::Continue(()))
}
}
fn query(pattern: &str, include_hidden: bool, name_glob: Option<&str>) -> SearchQuery {
let mut pane = crate::pane::Pane::new(PathBuf::from("/"));
pane.show_hidden = include_hidden;
pane.filter = name_glob.map(str::to_string);
SearchQuery::new(pattern, &pane).unwrap()
}
fn search_all(
engine: &OperationEngine<MockFs>,
query: &SearchQuery,
) -> (Vec<String>, SearchEnd) {
let mut hits = Vec::new();
let end = engine
.search(
Path::new("/proj"),
query,
&AtomicBool::new(false),
&mut |hit| {
hits.push(format!("{}:{}:{}", hit.path.display(), hit.line, hit.text));
},
)
.unwrap();
(hits, end)
}
#[test]
fn search_finds_matches_recursively_in_order() {
let fs = MockFs::with(&[])
.with_content("/proj/src/b.rs", "x\nfn main() {}\n")
.with_content("/proj/a.rs", "fn main()")
.with_content("/elsewhere/c.rs", "fn main()");
let engine = OperationEngine::new(fs);
let (hits, end) = search_all(&engine, &query("fn main", false, None));
assert_eq!(
hits,
vec!["/proj/a.rs:1:fn main()", "/proj/src/b.rs:2:fn main() {}"]
);
assert_eq!(end, SearchEnd::Finished);
}
#[test]
fn search_skips_hidden_files_unless_the_pane_shows_them() {
let fs = MockFs::with(&[])
.with_content("/proj/.env", "token")
.with_content("/proj/.git/config", "token")
.with_content("/proj/a.txt", "token");
let engine = OperationEngine::new(fs);
assert_eq!(search_all(&engine, &query("token", false, None)).0.len(), 1);
assert_eq!(search_all(&engine, &query("token", true, None)).0.len(), 3);
}
#[test]
fn search_follows_the_pane_name_filter() {
let fs = MockFs::with(&[])
.with_content("/proj/a.rs", "needle")
.with_content("/proj/a.md", "needle");
let engine = OperationEngine::new(fs);
let (hits, _) = search_all(&engine, &query("needle", false, Some("*.rs")));
assert_eq!(hits, vec!["/proj/a.rs:1:needle"]);
}
#[test]
fn search_stops_at_the_cap() {
let text = "hit\n".repeat(MAX_HITS + 5);
let fs = MockFs::with(&[]).with_content("/proj/many.txt", &text);
let engine = OperationEngine::new(fs);
let (hits, end) = search_all(&engine, &query("hit", false, None));
assert_eq!(hits.len(), MAX_HITS);
assert_eq!(end, SearchEnd::Capped);
}
#[test]
fn exactly_the_cap_is_not_capped() {
let text = "hit\n".repeat(MAX_HITS);
let fs = MockFs::with(&[]).with_content("/proj/many.txt", &text);
let engine = OperationEngine::new(fs);
let (hits, end) = search_all(&engine, &query("hit", false, None));
assert_eq!(hits.len(), MAX_HITS);
assert_eq!(end, SearchEnd::Finished);
}
#[test]
fn cancelling_a_search_stops_it() {
let fs = MockFs::with(&[])
.with_content("/proj/a.txt", "hit")
.with_content("/proj/b.txt", "hit");
let engine = OperationEngine::new(fs);
let cancel = AtomicBool::new(false);
let mut hits = 0;
let end = engine
.search(
Path::new("/proj"),
&query("hit", false, None),
&cancel,
&mut |_| {
hits += 1;
cancel.store(true, Ordering::Relaxed);
},
)
.unwrap();
assert_eq!(hits, 1);
assert_eq!(end, SearchEnd::Stopped);
}
#[test]
fn mock_search_applies_smart_case() {
let fs = MockFs::with(&[]).with_content("/proj/a.txt", "TODO\nTodo\ntodo");
let engine = OperationEngine::new(fs);
assert_eq!(search_all(&engine, &query("todo", false, None)).0.len(), 3);
assert_eq!(search_all(&engine, &query("Todo", false, None)).0.len(), 1);
}
fn pack(sources: &[&str], base_dir: &str, archive: &str) -> Operation {
Operation::CreateArchive {
sources: sources.iter().map(PathBuf::from).collect(),
base_dir: PathBuf::from(base_dir),
archive: PathBuf::from(archive),
}
}
fn packing_tree() -> MockFs {
MockFs::tree(&[
("/w", None),
("/w/src", None),
("/w/src/main.rs", Some(10)),
("/w/src/lib.rs", Some(20)),
("/w/src/empty", None),
("/w/notes.txt", Some(5)),
("/out", None),
])
}
#[test]
fn packing_names_entries_relative_to_the_base_directory() {
let fs = packing_tree();
let engine = OperationEngine::new(fs.clone());
engine
.execute(&pack(&["/w/src", "/w/notes.txt"], "/w", "/out/a.zip"))
.unwrap();
assert_eq!(
fs.packed("/out/a.zip"),
vec![
("src".to_string(), EntryKind::Dir),
("src/empty".to_string(), EntryKind::Dir),
("src/lib.rs".to_string(), EntryKind::File),
("src/main.rs".to_string(), EntryKind::File),
("notes.txt".to_string(), EntryKind::File),
]
);
}
#[test]
fn packing_does_not_follow_symlinks() {
let fs = MockFs::tree(&[
("/w", None),
("/w/big", None),
("/w/big/huge.bin", Some(1_000)),
("/w/link", None),
("/w/link/huge.bin", Some(1_000)),
("/out", None),
])
.with_link("/w/link");
let engine = OperationEngine::new(fs.clone());
engine
.execute(&pack(&["/w/link"], "/w", "/out/a.tar"))
.unwrap();
assert_eq!(
fs.packed("/out/a.tar"),
vec![("link".to_string(), EntryKind::Symlink)]
);
}
#[test]
fn packing_reports_progress_against_a_known_total() {
let fs = packing_tree();
let engine = OperationEngine::new(fs);
let mut ticks = Vec::new();
let outcome = engine
.execute_with_progress(
&pack(&["/w/src"], "/w", "/out/a.tar.gz"),
&AtomicBool::new(false),
&mut |p| ticks.push(p),
)
.unwrap();
assert_eq!(outcome, OperationOutcome::Completed);
assert_eq!(ticks.len(), 4);
assert!(ticks
.iter()
.all(|p| p.items_total == 4 && p.bytes_total == 30));
assert_eq!(ticks.last().unwrap().items_done, 4);
assert_eq!(ticks.last().unwrap().bytes_done, 30);
assert_eq!(
engine.estimate_totals(&pack(&["/w/src"], "/w", "/out/a.tar.gz")),
(4, 30)
);
}
#[test]
fn packing_refuses_an_existing_destination() {
let fs = packing_tree();
fs.nodes
.lock()
.unwrap()
.insert(PathBuf::from("/out/a.zip"), Some(7));
let engine = OperationEngine::new(fs.clone());
let result = engine.execute(&pack(&["/w/notes.txt"], "/w", "/out/a.zip"));
assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
assert!(fs.packed("/out/a.zip").is_empty());
assert_eq!(fs.size(Path::new("/out/a.zip")), 7);
}
#[test]
fn packing_refuses_an_unsupported_extension() {
let fs = packing_tree();
let engine = OperationEngine::new(fs.clone());
let result = engine.execute(&pack(&["/w/notes.txt"], "/w", "/out/a.rar"));
assert!(matches!(result, Err(OxiNavError::UnsupportedArchive(_))));
assert!(!fs.exists(Path::new("/out/a.rar")));
}
#[test]
fn packing_refuses_a_missing_source() {
let engine = OperationEngine::new(packing_tree());
let result = engine.execute(&pack(&["/w/gone.txt"], "/w", "/out/a.zip"));
assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
}
#[test]
fn cancelling_packing_leaves_no_archive() {
let fs = packing_tree();
let engine = OperationEngine::new(fs.clone());
let cancel = AtomicBool::new(false);
let mut ticks = 0;
let outcome = engine
.execute_with_progress(&pack(&["/w/src"], "/w", "/out/a.zip"), &cancel, &mut |_| {
ticks += 1;
cancel.store(true, Ordering::Relaxed);
})
.unwrap();
assert_eq!(outcome, OperationOutcome::Cancelled);
assert_eq!(ticks, 1);
assert!(!fs.exists(Path::new("/out/a.zip")));
}
#[test]
fn an_unreadable_file_fails_packing_and_names_it() {
let fs = packing_tree().with_unreadable("/w/src/main.rs");
let engine = OperationEngine::new(fs.clone());
let result = engine.execute(&pack(&["/w/src"], "/w", "/out/a.zip"));
match result {
Err(OxiNavError::Io { path, .. }) => assert_eq!(path, PathBuf::from("/w/src/main.rs")),
other => panic!("expected an I/O error naming the file, got {other:?}"),
}
assert!(!fs.exists(Path::new("/out/a.zip")));
}
fn scratch_dir(test: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("oxinav_{test}_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn snapshot(root: &Path) -> Vec<(String, String)> {
fn walk(root: &Path, dir: &Path, out: &mut Vec<(String, String)>) {
let mut children: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().path())
.collect();
children.sort();
for child in children {
let name = child.strip_prefix(root).unwrap().display().to_string();
if child.is_symlink() {
let target = std::fs::read_link(&child).unwrap();
out.push((name, format!("<link {}>", target.display())));
} else if child.is_dir() {
out.push((name, "<dir>".to_string()));
walk(root, &child, out);
} else {
out.push((name, std::fs::read_to_string(&child).unwrap()));
}
}
}
let mut out = Vec::new();
walk(root, root, &mut out);
out
}
fn round_trip(test: &str, name: &str) -> (PathBuf, PathBuf, PathBuf) {
let work = scratch_dir(test);
let tree = work.join("tree");
std::fs::create_dir_all(tree.join("sub/empty")).unwrap();
std::fs::write(tree.join("a.txt"), "alpha").unwrap();
std::fs::write(tree.join("sub/b.txt"), "beta").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(
tree.join("sub/b.txt"),
std::fs::Permissions::from_mode(0o750),
)
.unwrap();
}
let engine = OperationEngine::new(StdFilesystem);
let archive = work.join(name);
engine
.execute(&Operation::CreateArchive {
sources: vec![tree.clone()],
base_dir: work.clone(),
archive: archive.clone(),
})
.unwrap();
let out = work.join("out");
std::fs::create_dir(&out).unwrap();
engine
.execute(&Operation::ExtractArchive {
archive: archive.clone(),
dest_dir: out.clone(),
})
.unwrap();
(work, archive, out)
}
#[cfg(unix)]
fn mode(path: &Path) -> u32 {
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path).unwrap().permissions().mode() & 0o777
}
#[test]
fn every_format_round_trips_through_extraction() {
for (test, name) in [
("rt_zip", "x.zip"),
("rt_tar", "x.tar"),
("rt_tgz", "x.tar.gz"),
] {
let (work, _, out) = round_trip(test, name);
assert_eq!(
snapshot(&out.join("tree")),
snapshot(&work.join("tree")),
"{name}"
);
#[cfg(unix)]
assert_eq!(mode(&out.join("tree/sub/b.txt")), 0o750, "{name}");
std::fs::remove_dir_all(&work).unwrap();
}
}
#[test]
fn zip_entries_keep_their_modification_date() {
let (work, archive, _) = round_trip("zip_time", "t.zip");
let mut zip = zip::ZipArchive::new(std::fs::File::open(&archive).unwrap()).unwrap();
let entry = zip.by_name("tree/a.txt").unwrap();
let year = entry.last_modified().map(|time| time.year());
assert!(year.is_some_and(|year| year > 2000), "{year:?}");
std::fs::remove_dir_all(&work).unwrap();
}
#[cfg(unix)]
#[test]
fn symlinks_are_packed_as_links() {
let work = scratch_dir("pack_links");
let outside = work.join("outside");
std::fs::create_dir(&outside).unwrap();
std::fs::write(outside.join("big.bin"), "lots").unwrap();
std::os::unix::fs::symlink(&outside, work.join("link")).unwrap();
let engine = OperationEngine::new(StdFilesystem);
for name in ["l.tar", "l.zip"] {
engine
.execute(&Operation::CreateArchive {
sources: vec![work.join("link")],
base_dir: work.clone(),
archive: work.join(name),
})
.unwrap();
}
let tar_entries: Vec<_> =
tar::Archive::new(std::fs::File::open(work.join("l.tar")).unwrap())
.entries()
.unwrap()
.map(|e| e.unwrap().header().entry_type())
.collect();
assert_eq!(tar_entries, vec![tar::EntryType::Symlink]);
let mut zip =
zip::ZipArchive::new(std::fs::File::open(work.join("l.zip")).unwrap()).unwrap();
assert_eq!(zip.len(), 1);
assert!(zip.by_index(0).unwrap().is_symlink());
std::fs::remove_dir_all(&work).unwrap();
}
#[test]
fn cancelled_packing_leaves_neither_archive_nor_temp_file() {
let work = scratch_dir("pack_cancel");
for i in 0..5 {
std::fs::write(work.join(format!("f{i}.txt")), "x").unwrap();
}
let engine = OperationEngine::new(StdFilesystem);
let cancel = AtomicBool::new(false);
let archive = work.join("out.tar.gz");
let sources = (0..5).map(|i| work.join(format!("f{i}.txt"))).collect();
let outcome = engine
.execute_with_progress(
&Operation::CreateArchive {
sources,
base_dir: work.clone(),
archive: archive.clone(),
},
&cancel,
&mut |_| cancel.store(true, Ordering::Relaxed),
)
.unwrap();
assert_eq!(outcome, OperationOutcome::Cancelled);
assert!(!archive.exists());
assert!(!work.join(".out.tar.gz.oxinav-partial").exists());
std::fs::remove_dir_all(&work).unwrap();
}
fn search_tree(test: &str) -> PathBuf {
let root = scratch_dir(test);
std::fs::create_dir_all(root.join(".git")).unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::create_dir_all(root.join("target")).unwrap();
std::fs::write(root.join(".gitignore"), "target/\n").unwrap();
std::fs::write(root.join("src/b.rs"), "// TODO later\nfn main() {}\n").unwrap();
std::fs::write(root.join("a.md"), "todo: write docs\nTodo list\n").unwrap();
std::fs::write(root.join("target/out.rs"), "fn main() {}\n").unwrap();
std::fs::write(root.join("blob.bin"), b"fn main\0\x01\x02").unwrap();
std::fs::write(root.join(".env"), "fn main\n").unwrap();
root
}
fn std_search(root: &Path, pattern: &str) -> Result<Vec<String>, OxiNavError> {
let engine = OperationEngine::new(StdFilesystem);
let query = query(pattern, false, None);
let mut hits = Vec::new();
engine.search(root, &query, &AtomicBool::new(false), &mut |hit| {
let name = hit
.path
.strip_prefix(root)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
hits.push(format!("{name}:{}:{}", hit.line, hit.text));
})?;
Ok(hits)
}
#[test]
fn ripgrep_backend_skips_ignored_binary_and_hidden_files() {
let root = search_tree("rg_scope");
assert_eq!(
std_search(&root, r"fn\s+main").unwrap(),
vec!["src/b.rs:2:fn main() {}"]
);
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn ripgrep_backend_applies_smart_case_in_a_stable_order() {
let root = search_tree("rg_case");
assert_eq!(
std_search(&root, "todo").unwrap(),
vec![
"a.md:1:todo: write docs",
"a.md:2:Todo list",
"src/b.rs:1:// TODO later",
]
);
assert_eq!(std_search(&root, "Todo").unwrap(), vec!["a.md:2:Todo list"]);
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn ripgrep_backend_rejects_an_invalid_regex() {
let root = search_tree("rg_invalid");
assert!(matches!(
std_search(&root, "foo("),
Err(OxiNavError::InvalidPattern(_))
));
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn create_file_creates_an_empty_file() {
let fs = MockFs::with(&[]);
let engine = OperationEngine::new(fs);
engine
.execute(&Operation::CreateFile {
path: "/new.txt".into(),
})
.unwrap();
assert!(engine.exists(Path::new("/new.txt")));
}
#[test]
fn create_file_rejects_an_existing_name() {
let engine = OperationEngine::new(MockFs::with(&["/taken.txt"]));
let result = engine.execute(&Operation::CreateFile {
path: "/taken.txt".into(),
});
assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
}
#[test]
fn create_file_rejects_an_existing_directory_name() {
let engine = OperationEngine::new(MockFs::tree(&[("/dir", None)]));
let result = engine.execute(&Operation::CreateFile {
path: "/dir".into(),
});
assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
}
#[test]
fn create_symlink_creates_a_link_at_the_target_path() {
let engine = OperationEngine::new(MockFs::with(&["/src.txt"]));
engine
.execute(&Operation::CreateSymlink {
source: "/src.txt".into(),
link: "/other/link.txt".into(),
})
.unwrap();
assert!(engine.exists(Path::new("/other/link.txt")));
assert!(engine.exists(Path::new("/src.txt")));
}
#[test]
fn create_symlink_rejects_a_missing_source() {
let engine = OperationEngine::new(MockFs::with(&[]));
let result = engine.execute(&Operation::CreateSymlink {
source: "/gone.txt".into(),
link: "/link.txt".into(),
});
assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
assert!(!engine.exists(Path::new("/link.txt")));
}
#[test]
fn create_symlink_rejects_an_existing_link_path() {
let engine = OperationEngine::new(MockFs::with(&["/src.txt", "/link.txt"]));
let result = engine.execute(&Operation::CreateSymlink {
source: "/src.txt".into(),
link: "/link.txt".into(),
});
assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
}
#[test]
fn new_single_item_ops_estimate_one_item() {
let engine = OperationEngine::new(MockFs::with(&["/src.txt"]));
assert_eq!(
engine.estimate_totals(&Operation::CreateFile {
path: "/new.txt".into()
}),
(1, 0)
);
assert_eq!(
engine.estimate_totals(&Operation::CreateSymlink {
source: "/src.txt".into(),
link: "/link.txt".into(),
}),
(1, 0)
);
}
fn extract(archive: &str, dest: &str) -> Operation {
Operation::ExtractArchive {
archive: archive.into(),
dest_dir: dest.into(),
}
}
#[test]
fn extract_writes_entries_under_the_destination() {
let fs =
MockFs::tree(&[("/dest", None)]).with_archive("/a.zip", &["one.txt", "nested/two.txt"]);
let engine = OperationEngine::new(fs);
engine.execute(&extract("/a.zip", "/dest")).unwrap();
assert!(engine.exists(Path::new("/dest/one.txt")));
assert!(engine.exists(Path::new("/dest/nested/two.txt")));
}
#[test]
fn extract_rejects_an_unsupported_format_without_writing_anything() {
let fs = MockFs::tree(&[("/dest", None)]).with_archive("/a.rar", &["one.txt"]);
let engine = OperationEngine::new(fs);
let result = engine.execute(&extract("/a.rar", "/dest"));
assert!(matches!(result, Err(OxiNavError::UnsupportedArchive(_))));
assert!(!engine.exists(Path::new("/dest/one.txt")));
}
#[test]
fn extract_rejects_a_missing_archive() {
let engine = OperationEngine::new(MockFs::tree(&[("/dest", None)]));
let result = engine.execute(&extract("/gone.zip", "/dest"));
assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
}
#[test]
fn extract_rejects_a_missing_destination() {
let fs = MockFs::with(&[]).with_archive("/a.zip", &["one.txt"]);
let engine = OperationEngine::new(fs);
let result = engine.execute(&extract("/a.zip", "/nope"));
assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
}
#[test]
fn extract_refuses_an_entry_escaping_the_destination() {
let fs = MockFs::tree(&[("/dest", None)]).with_archive("/evil.zip", &["../../etc/passwd"]);
let engine = OperationEngine::new(fs);
let result = engine.execute(&extract("/evil.zip", "/dest"));
assert!(matches!(result, Err(OxiNavError::UnsafeArchiveEntry(_))));
assert!(!engine.exists(Path::new("/etc/passwd")));
}
#[test]
fn extract_reports_progress_per_entry_against_a_total_known_up_front() {
let fs = MockFs::tree(&[("/dest", None)])
.with_archive("/a.tar.gz", &["one.txt", "two.txt", "three.txt"]);
let engine = OperationEngine::new(fs);
let cancel = AtomicBool::new(false);
let mut seen: Vec<Progress> = Vec::new();
let outcome = engine
.execute_with_progress(&extract("/a.tar.gz", "/dest"), &cancel, &mut |p| {
seen.push(p)
})
.unwrap();
assert_eq!(outcome, OperationOutcome::Completed);
assert_eq!(seen.len(), 3);
assert!(seen.iter().all(|p| p.items_total == 3));
assert_eq!(
seen.iter().map(|p| p.items_done).collect::<Vec<_>>(),
vec![1, 2, 3]
);
}
#[test]
fn extract_estimates_the_archive_entry_count() {
let fs = MockFs::tree(&[("/dest", None)]).with_archive("/a.zip", &["one.txt", "two.txt"]);
let engine = OperationEngine::new(fs);
assert_eq!(engine.estimate_totals(&extract("/a.zip", "/dest")), (2, 0));
}
#[test]
fn extract_estimate_falls_back_to_one_item_when_unreadable() {
let engine = OperationEngine::new(MockFs::tree(&[("/dest", None)]));
assert_eq!(
engine.estimate_totals(&extract("/gone.zip", "/dest")),
(1, 0)
);
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(name);
std::fs::remove_dir_all(&dir).ok();
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn write_zip(path: &Path, entries: &[(&str, &[u8])]) {
use std::io::Write;
let file = std::fs::File::create(path).unwrap();
let mut zip = zip::ZipWriter::new(file);
for (name, body) in entries {
zip.start_file(*name, zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(body).unwrap();
}
zip.finish().unwrap();
}
fn write_tar_gz(path: &Path, entries: &[(&str, &[u8])]) {
let file = std::fs::File::create(path).unwrap();
let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());
let mut builder = tar::Builder::new(encoder);
for (name, body) in entries {
let mut header = tar::Header::new_gnu();
header.set_size(body.len() as u64);
header.set_mode(0o644);
header.set_cksum();
builder.append_data(&mut header, name, *body).unwrap();
}
builder.into_inner().unwrap().finish().unwrap();
}
#[test]
fn real_zip_is_extracted_with_its_contents_and_nesting() {
let dir = scratch("oxinav_test_extract_zip");
let archive = dir.join("bundle.zip");
write_zip(
&archive,
&[("top.txt", b"one"), ("nested/deep.txt", b"two")],
);
let dest = dir.join("out");
std::fs::create_dir_all(&dest).unwrap();
let engine = OperationEngine::new(StdFilesystem);
engine
.execute(&Operation::ExtractArchive {
archive,
dest_dir: dest.clone(),
})
.unwrap();
assert_eq!(std::fs::read(dest.join("top.txt")).unwrap(), b"one");
assert_eq!(std::fs::read(dest.join("nested/deep.txt")).unwrap(), b"two");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn real_tar_gz_is_extracted_with_its_contents() {
let dir = scratch("oxinav_test_extract_targz");
let archive = dir.join("bundle.tar.gz");
write_tar_gz(&archive, &[("a.txt", b"alpha"), ("sub/b.txt", b"beta")]);
let dest = dir.join("out");
std::fs::create_dir_all(&dest).unwrap();
let engine = OperationEngine::new(StdFilesystem);
engine
.execute(&Operation::ExtractArchive {
archive,
dest_dir: dest.clone(),
})
.unwrap();
assert_eq!(std::fs::read(dest.join("a.txt")).unwrap(), b"alpha");
assert_eq!(std::fs::read(dest.join("sub/b.txt")).unwrap(), b"beta");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn real_tar_gz_with_a_dot_root_entry_still_extracts() {
let dir = scratch("oxinav_test_extract_dot_root");
let archive = dir.join("rooted.tar.gz");
write_tar_gz(
&archive,
&[
("./", b""),
("./top.txt", b"one"),
("./sub/deep.txt", b"two"),
],
);
let dest = dir.join("out");
std::fs::create_dir_all(&dest).unwrap();
let engine = OperationEngine::new(StdFilesystem);
engine
.execute(&Operation::ExtractArchive {
archive,
dest_dir: dest.clone(),
})
.unwrap();
assert_eq!(std::fs::read(dest.join("top.txt")).unwrap(), b"one");
assert_eq!(std::fs::read(dest.join("sub/deep.txt")).unwrap(), b"two");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn real_zip_slip_entry_never_escapes_the_destination() {
let dir = scratch("oxinav_test_extract_zipslip");
let archive = dir.join("evil.zip");
write_zip(&archive, &[("../escaped.txt", b"pwned")]);
let dest = dir.join("out");
std::fs::create_dir_all(&dest).unwrap();
let engine = OperationEngine::new(StdFilesystem);
let result = engine.execute(&Operation::ExtractArchive {
archive,
dest_dir: dest.clone(),
});
assert!(matches!(result, Err(OxiNavError::UnsafeArchiveEntry(_))));
assert!(!dir.join("escaped.txt").exists());
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn real_entry_count_matches_the_archive() {
let dir = scratch("oxinav_test_extract_count");
let zip_path = dir.join("z.zip");
write_zip(&zip_path, &[("a", b"1"), ("b", b"2"), ("c", b"3")]);
let tgz_path = dir.join("t.tar.gz");
write_tar_gz(&tgz_path, &[("a", b"1"), ("b", b"2")]);
let fs = StdFilesystem;
assert_eq!(
fs.count_archive_entries(&zip_path, ArchiveFormat::Zip)
.unwrap(),
3
);
assert_eq!(
fs.count_archive_entries(&tgz_path, ArchiveFormat::TarGz)
.unwrap(),
2
);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn resolve_directory_accepts_an_existing_directory() {
let engine = OperationEngine::new(MockFs::tree(&[("/home/me/code", None)]));
let target = engine
.resolve_directory("/home/me/code", Path::new("/home/me"))
.unwrap();
assert_eq!(target, PathBuf::from("/home/me/code"));
}
#[test]
fn resolve_directory_expands_a_leading_tilde() {
let engine =
OperationEngine::new(MockFs::tree(&[("/home/me", None), ("/home/me/code", None)]));
let home = Path::new("/home/me");
assert_eq!(
engine.resolve_directory("~/code", home).unwrap(),
PathBuf::from("/home/me/code")
);
assert_eq!(
engine.resolve_directory("~", home).unwrap(),
PathBuf::from("/home/me")
);
}
#[test]
fn resolve_directory_leaves_an_interior_tilde_alone() {
let engine = OperationEngine::new(MockFs::tree(&[("/data/back~up", None)]));
assert_eq!(
engine
.resolve_directory("/data/back~up", Path::new("/home/me"))
.unwrap(),
PathBuf::from("/data/back~up")
);
}
#[test]
fn resolve_directory_rejects_a_missing_path() {
let engine = OperationEngine::new(MockFs::tree(&[]));
let result = engine.resolve_directory("/nope", Path::new("/home/me"));
assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
}
#[test]
fn resolve_directory_rejects_a_file() {
let engine = OperationEngine::new(MockFs::with(&["/home/me/notes.txt"]));
let result = engine.resolve_directory("/home/me/notes.txt", Path::new("/home/me"));
assert!(matches!(result, Err(OxiNavError::NotADirectory(_))));
}
#[test]
fn resolve_directory_rejects_a_blank_input() {
let engine = OperationEngine::new(MockFs::tree(&[("/home/me", None)]));
assert!(engine
.resolve_directory(" ", Path::new("/home/me"))
.is_err());
}
#[test]
fn resolve_directory_trims_surrounding_whitespace() {
let engine = OperationEngine::new(MockFs::tree(&[("/home/me/code", None)]));
assert_eq!(
engine
.resolve_directory(" /home/me/code ", Path::new("/home/me"))
.unwrap(),
PathBuf::from("/home/me/code")
);
}
#[test]
fn read_capped_stops_at_the_cap() {
let engine = OperationEngine::new(MockFs::tree(&[("/big", Some(4096))]));
let bytes = engine.read_capped(Path::new("/big"), 100).unwrap();
assert_eq!(bytes.len(), 100);
}
#[test]
fn read_capped_missing_source_errors() {
let engine = OperationEngine::new(MockFs::with(&[]));
let result = engine.read_capped(Path::new("/gone"), 100);
assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
}
#[test]
fn copy_missing_source_errors() {
let engine = OperationEngine::new(MockFs::with(&[]));
let result = engine.execute(&Operation::Copy {
src: "/a".into(),
dest: "/b".into(),
});
assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
}
#[test]
fn copy_existing_dest_errors() {
let engine = OperationEngine::new(MockFs::with(&["/a", "/b"]));
let result = engine.execute(&Operation::Copy {
src: "/a".into(),
dest: "/b".into(),
});
assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
}
#[test]
fn delete_missing_source_errors() {
let engine = OperationEngine::new(MockFs::with(&[]));
let result = engine.execute(&Operation::Delete { path: "/a".into() });
assert!(matches!(result, Err(OxiNavError::SourceNotFound(_))));
}
#[test]
fn create_dir_existing_errors() {
let engine = OperationEngine::new(MockFs::with(&["/dir"]));
let result = engine.execute(&Operation::CreateDir {
path: "/dir".into(),
});
assert!(matches!(result, Err(OxiNavError::DestinationExists(_))));
}
#[test]
fn exists_reports_true_for_present_path() {
let engine = OperationEngine::new(MockFs::with(&["/a"]));
assert!(engine.exists(Path::new("/a")));
}
#[test]
fn exists_reports_false_for_missing_path() {
let engine = OperationEngine::new(MockFs::with(&["/a"]));
assert!(!engine.exists(Path::new("/b")));
}
#[test]
fn recursive_copy_emits_progress_per_file() {
let engine = OperationEngine::new(MockFs::tree(&[
("/src", None),
("/src/a.txt", Some(10)),
("/src/b.txt", Some(20)),
("/src/sub", None),
("/src/sub/c.txt", Some(30)),
]));
let cancel = AtomicBool::new(false);
let mut ticks = Vec::new();
let outcome = engine
.execute_with_progress(
&Operation::Copy {
src: "/src".into(),
dest: "/dst".into(),
},
&cancel,
&mut |p| ticks.push(p),
)
.unwrap();
assert_eq!(outcome, OperationOutcome::Completed);
assert_eq!(
ticks.iter().map(|p| p.items_done).collect::<Vec<_>>(),
vec![1, 2, 3]
);
assert!(ticks
.iter()
.all(|p| p.items_total == 3 && p.bytes_total == 60));
assert!(ticks.windows(2).all(|w| w[0].bytes_done <= w[1].bytes_done));
assert_eq!(ticks.last().unwrap().bytes_done, 60);
assert!(engine.exists(Path::new("/dst/a.txt")));
assert!(engine.exists(Path::new("/dst/b.txt")));
assert!(engine.exists(Path::new("/dst/sub/c.txt")));
}
#[test]
fn estimate_totals_counts_files_and_bytes() {
let engine = OperationEngine::new(MockFs::tree(&[
("/src", None),
("/src/a.txt", Some(10)),
("/src/sub", None),
("/src/sub/b.txt", Some(30)),
]));
assert_eq!(
engine.estimate_totals(&Operation::Copy {
src: "/src".into(),
dest: "/dst".into(),
}),
(2, 40)
);
assert_eq!(
engine.estimate_totals(&Operation::Delete {
path: "/src/a.txt".into(),
}),
(1, 10)
);
}
#[test]
fn cancel_stops_before_next_item() {
let engine = OperationEngine::new(MockFs::tree(&[
("/src", None),
("/src/a", Some(1)),
("/src/b", Some(1)),
("/src/c", Some(1)),
]));
let cancel = Arc::new(AtomicBool::new(false));
let flag = cancel.clone();
let mut ticks = 0usize;
let outcome = engine
.execute_with_progress(
&Operation::Copy {
src: "/src".into(),
dest: "/dst".into(),
},
&cancel,
&mut |_| {
ticks += 1;
flag.store(true, Ordering::Relaxed);
},
)
.unwrap();
assert_eq!(outcome, OperationOutcome::Cancelled);
assert_eq!(ticks, 1);
let copied = ["/dst/a", "/dst/b", "/dst/c"]
.iter()
.filter(|p| engine.exists(&PathBuf::from(*p)))
.count();
assert_eq!(copied, 1);
}
}