1use std::{fs, io};
2use std::path::Path;
3use std::io::Error;
4use std::io::ErrorKind::NotFound;
5
6pub fn copy(src_file: &str, dst_file: &str) -> io::Result<()> {
18 if !Path::new(src_file).exists() {
19 return Err(Error::new(NotFound, format!("源文件不存在: {}", src_file)));
20 }
21 create_parent_dir(dst_file)?;
22 fs::copy(src_file, dst_file)?;
23 Ok(())
24}
25
26pub fn rename(src_file: &str, dst_file: &str) -> io::Result<()> {
38 if !Path::new(src_file).exists() {
39 return Err(Error::new(NotFound, format!("源文件不存在: {}", src_file)));
40 }
41 create_parent_dir(dst_file)?;
42 fs::rename(src_file, dst_file)?;
43 Ok(())
44}
45
46pub fn create_parent_dir(dst_file: &str) -> io::Result<()> {
54 if let Some(parent_dir) = Path::new(dst_file).parent() {
55 if !parent_dir.exists() {
56 fs::create_dir_all(parent_dir)?;
57 }
58 } else {
59 return Err(Error::new(NotFound, format!("目标文件路径不合法: {}", dst_file)));
60 }
61 Ok(())
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 #[test]
69 fn test_file_copy() {
70 if let Err(e) = copy("/opt/light-tool/tt.txt", "/opt/light-tool/tt/1/tt.txt") {
71 println!("file copy error: {}", e);
72 }
73 }
74
75 #[test]
76 fn test_file_move() {
77 if let Err(e) = rename("/opt/light-tool/tt.txt", "/opt/light-tool/tt/1/tt.txt") {
78 println!("file move error: {}", e);
79 }
80 }
81
82 #[test]
83 fn test_create_parent_dir() {
84 if let Err(e) = create_parent_dir("/opt/light-tool/tt/1/tt.txt") {
85 println!("create parent dir error: {}", e);
86 }
87 }
88}