use crate::archive::{classify_entry_path, detect_format, ArchiveFormat, EntryTarget};
use crate::error::OxiNavError;
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 },
}
#[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_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>;
}
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> {
std::os::unix::fs::symlink(source, link).map_err(|source| OxiNavError::Io {
path: link.to_path_buf(),
source,
})
}
fn exists(&self, path: &Path) -> bool {
path.exists()
}
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,
})?;
}
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 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()))
}
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 |_| {})
}
}
}
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)
}
}
}
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)),
}
}
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;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct MockFs {
nodes: Arc<Mutex<HashMap<PathBuf, Option<u64>>>>,
archives: Arc<Mutex<HashMap<PathBuf, Vec<String>>>>,
}
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())),
}
}
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 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())),
}
}
}
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_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(())
}
}
#[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);
}
}