use crate::error::{VBError, VBResult};
use crate::state::file;
use crate::value::VBVariant;
use vb6core::error::err_number;
pub fn file_copy(source: &VBVariant, destination: &VBVariant) -> VBResult<()> {
let source_str = match source {
VBVariant::String(s) => s.as_str().to_string(),
_ => {
return Err(VBError::with_description(
13, "Type mismatch in FileCopy",
));
}
};
let dest_str = match destination {
VBVariant::String(s) => s.as_str().to_string(),
_ => {
return Err(VBError::with_description(
13, "Type mismatch in FileCopy",
));
}
};
file::copy_file(
std::path::Path::new(&source_str),
std::path::Path::new(&dest_str),
)
.map_err(|e| {
VBError::with_description(
match e.kind() {
std::io::ErrorKind::NotFound => err_number::FILE_NOT_FOUND, std::io::ErrorKind::PermissionDenied => err_number::PERMISSION_DENIED, _ => err_number::DEVICE_IO_ERROR, },
e.to_string(),
)
})?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::file::{self};
use vb6core::error::err_number;
#[test]
fn file_copy_copies_file() {
let _guard = crate::state::test_support::lock_test();
let dir = tempfile::tempdir().unwrap();
file::set_root(dir.path());
std::fs::write(dir.path().join("source.txt"), "Hello").unwrap();
file_copy(
&VBVariant::from_string("source.txt"),
&VBVariant::from_string("dest.txt"),
)
.unwrap();
assert!(dir.path().join("dest.txt").exists());
let content = std::fs::read_to_string(dir.path().join("dest.txt")).unwrap();
assert_eq!(content, "Hello");
}
#[test]
fn file_copy_overwrites_existing() {
let _guard = crate::state::test_support::lock_test();
let dir = tempfile::tempdir().unwrap();
file::set_root(dir.path());
std::fs::write(dir.path().join("source.txt"), "Hello").unwrap();
std::fs::write(dir.path().join("dest.txt"), "Old").unwrap();
file_copy(
&VBVariant::from_string("source.txt"),
&VBVariant::from_string("dest.txt"),
)
.unwrap();
let content = std::fs::read_to_string(dir.path().join("dest.txt")).unwrap();
assert_eq!(content, "Hello");
}
#[test]
fn file_copy_rejects_nonexistent_source() {
let _guard = crate::state::test_support::lock_test();
let dir = tempfile::tempdir().unwrap();
file::set_root(dir.path());
let result = file_copy(
&VBVariant::from_string("nonexistent.txt"),
&VBVariant::from_string("dest.txt"),
);
assert!(result.is_err());
assert_eq!(result.unwrap_err().number, err_number::FILE_NOT_FOUND);
}
#[test]
fn file_copy_rejects_non_string() {
let _guard = crate::state::test_support::lock_test();
let result = file_copy(&VBVariant::Long(42), &VBVariant::from_string("dest.txt"));
assert!(result.is_err());
assert_eq!(result.unwrap_err().number, err_number::TYPE_MISMATCH);
let result = file_copy(&VBVariant::from_string("source.txt"), &VBVariant::Long(42));
assert!(result.is_err());
assert_eq!(result.unwrap_err().number, err_number::TYPE_MISMATCH);
}
}