use std::path::{Path, PathBuf};
use crate::Forge;
pub struct Move {
from: PathBuf,
}
impl Move {
pub fn new(from: impl AsRef<Path>) -> Self {
Self {
from: from.as_ref().to_path_buf(),
}
}
}
impl Forge for Move {
type Error = std::io::Error;
fn forge(&self, into: impl AsRef<Path>) -> Result<(), Self::Error> {
let to = into.as_ref();
std::fs::rename(&self.from, to)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn test_move_renames_file() {
let temp_dir = tempdir().unwrap();
let source_path = temp_dir.path().join("source.txt");
let test_content = "Test content";
std::fs::write(&source_path, test_content).unwrap();
let dest_path = temp_dir.path().join("destination.txt");
let mover = Move::new(&source_path);
let result = mover.forge(&dest_path);
assert!(result.is_ok());
assert!(!source_path.exists());
assert!(dest_path.exists());
let content = std::fs::read_to_string(&dest_path).unwrap();
assert_eq!(content, test_content);
}
#[test]
fn test_move_fails_with_nonexistent_source() {
let temp_dir = tempdir().unwrap();
let source_path = temp_dir.path().join("nonexistent.txt");
let dest_path = temp_dir.path().join("destination.txt");
let mover = Move::new(&source_path);
let result = mover.forge(&dest_path);
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::NotFound);
}
#[test]
fn test_move_across_directories() {
let source_dir = tempdir().unwrap();
let dest_dir = tempdir().unwrap();
let source_path = source_dir.path().join("source.txt");
let test_content = "Cross-directory move test";
std::fs::write(&source_path, test_content).unwrap();
let dest_path = dest_dir.path().join("moved.txt");
let mover = Move::new(&source_path);
let result = mover.forge(&dest_path);
if result.is_ok() {
assert!(!source_path.exists());
assert!(dest_path.exists());
let content = std::fs::read_to_string(&dest_path).unwrap();
assert_eq!(content, test_content);
} else {
assert!(result.is_err());
}
}
}