use std::fs; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use crate::error::{Result, RoneoError}; static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0); /// Lightweight zero-dependency RAII temporary directory (automatically deleted on `Drop`). #[derive(Debug)] pub struct TempDir { path: PathBuf, } impl TempDir { pub fn new() -> Result { Self::with_prefix("roneo") } pub fn with_prefix(prefix: &str) -> Result { let base = std::env::temp_dir(); let pid = std::process::id(); let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_nanos()); for _ in 0..64 { let seq = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed); let candidate = base.join(format!("{prefix}-{pid}-{nanos:x}-{seq}")); match create_private_dir(&candidate) { Ok(()) => return Ok(Self { path: candidate }), Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} Err(e) => return Err(RoneoError::io(&candidate, e)), } } Err(RoneoError::TemplateSource( "Failed to allocate a unique temporary directory".into(), )) } pub fn path(&self) -> &Path { &self.path } } impl Drop for TempDir { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.path); } } #[cfg(unix)] fn create_private_dir(path: &Path) -> std::io::Result<()> { use std::os::unix::fs::DirBuilderExt; fs::DirBuilder::new().mode(0o700).create(path) } #[cfg(not(unix))] fn create_private_dir(path: &Path) -> std::io::Result<()> { fs::create_dir(path) } /// Entry yielded while walking a directory tree on disk. #[derive(Debug, Clone)] pub struct DiskEntry { pub abs_path: PathBuf, pub rel_path: PathBuf, pub is_dir: bool, pub is_symlink: bool, } /// Recursively walk `root` in deterministic sorted filename order, calling `visitor` on each entry. /// When `visitor` returns `Ok(false)` for a directory, that directory's subtree is skipped. pub fn walk_dir_sorted(root: &Path, follow_symlinks: bool, mut visitor: F) -> Result<()> where F: FnMut(DiskEntry) -> Result, { walk_recursive(root, root, follow_symlinks, &mut visitor) } fn walk_recursive( root: &Path, current: &Path, follow_symlinks: bool, visitor: &mut F, ) -> Result<()> where F: FnMut(DiskEntry) -> Result, { let mut entries: Vec<_> = fs::read_dir(current) .map_err(|e| RoneoError::io(current, e))? .collect::, _>>() .map_err(|e| RoneoError::io(current, e))?; entries.sort_by_key(fs::DirEntry::file_name); for entry in entries { let abs_path = entry.path(); let rel_path = abs_path .strip_prefix(root) .map_or_else(|_| PathBuf::from(entry.file_name()), Path::to_path_buf); let sym_meta = fs::symlink_metadata(&abs_path).map_err(|e| RoneoError::io(&abs_path, e))?; let is_symlink = sym_meta.file_type().is_symlink(); let is_dir = if is_symlink && follow_symlinks { fs::metadata(&abs_path).is_ok_and(|m| m.is_dir()) } else { sym_meta.is_dir() }; let enter = visitor(DiskEntry { abs_path: abs_path.clone(), rel_path, is_dir, is_symlink, })?; if is_dir && enter { walk_recursive(root, &abs_path, follow_symlinks, visitor)?; } } Ok(()) } #[cfg(unix)] pub fn set_executable(dst: &Path) -> Result<()> { use std::os::unix::fs::PermissionsExt; fs::set_permissions(dst, fs::Permissions::from_mode(0o755)).map_err(|e| RoneoError::io(dst, e)) } #[cfg(not(unix))] pub fn set_executable(_dst: &Path) -> Result<()> { Ok(()) } #[cfg(unix)] pub fn file_mode_from_metadata(meta: &fs::Metadata) -> Option { use std::os::unix::fs::PermissionsExt; Some(meta.permissions().mode()) } #[cfg(not(unix))] pub fn file_mode_from_metadata(_meta: &fs::Metadata) -> Option { None } #[cfg(unix)] pub fn set_file_mode(dst: &Path, mode: u32) -> Result<()> { use std::os::unix::fs::PermissionsExt; fs::set_permissions(dst, fs::Permissions::from_mode(mode)).map_err(|e| RoneoError::io(dst, e)) } #[cfg(not(unix))] pub fn set_file_mode(_dst: &Path, _mode: u32) -> Result<()> { Ok(()) } #[cfg(unix)] pub fn copy_permissions(src: &Path, dst: &Path) -> Result<()> { let perms = fs::metadata(src) .map_err(|e| RoneoError::io(src, e))? .permissions(); fs::set_permissions(dst, perms).map_err(|e| RoneoError::io(dst, e)) } #[cfg(not(unix))] pub fn copy_permissions(_src: &Path, _dst: &Path) -> Result<()> { Ok(()) } #[cfg(unix)] pub fn create_symlink(target: &Path, link: &Path) -> Result<()> { std::os::unix::fs::symlink(target, link).map_err(|e| RoneoError::io(link, e)) } #[cfg(windows)] pub fn create_symlink(target: &Path, link: &Path) -> Result<()> { std::os::windows::fs::symlink_file(target, link).map_err(|e| RoneoError::io(link, e)) }