Skip to content

Commit 0fad16c

Browse files
authored
使用cp -r来复制目录 (#23)
* 使用cp -r来复制目录
1 parent 80d3f38 commit 0fad16c

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

src/utils/file.rs

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1-
use std::{fs::File, path::Path};
1+
use std::{
2+
fs::File,
3+
path::Path,
4+
process::{Command, Stdio},
5+
};
26

37
use reqwest::{blocking::ClientBuilder, Url};
48

9+
use super::stdio::StdioUtils;
10+
511
pub struct FileUtils;
612

713
impl FileUtils {
@@ -40,20 +46,24 @@ impl FileUtils {
4046

4147
/// 递归地复制给定目录下所有文件到另一个文件夹中
4248
pub fn copy_dir_all(src: &Path, dst: &Path) -> Result<(), String> {
43-
if src.is_dir() {
44-
std::fs::create_dir_all(dst).map_err(|e| e.to_string())?;
45-
for entry in std::fs::read_dir(src).map_err(|e| e.to_string())? {
46-
let entry = entry.map_err(|e| e.to_string())?;
47-
let path = entry.path();
48-
let dst_path = dst.join(path.file_name().unwrap());
49-
if path.is_dir() {
50-
FileUtils::copy_dir_all(&path, &dst_path).map_err(|e| e.to_string())?;
51-
} else {
52-
std::fs::copy(&path, &dst_path).map_err(|e| e.to_string())?;
53-
}
54-
}
55-
} else {
56-
return Err(format!("No such source directory:{:?}", src));
49+
let mut cmd = Command::new("cp");
50+
cmd.arg("-r").arg("./").arg(dst);
51+
52+
cmd.current_dir(src);
53+
54+
// 创建子进程,执行命令
55+
let proc: std::process::Child = cmd
56+
.stderr(Stdio::piped())
57+
.spawn()
58+
.map_err(|e| e.to_string())?;
59+
let output = proc.wait_with_output().map_err(|e| e.to_string())?;
60+
61+
if !output.status.success() {
62+
return Err(format!(
63+
"copy_dir_all failed, status: {:?}, stderr: {:?}",
64+
output.status,
65+
StdioUtils::tail_n_str(StdioUtils::stderr_to_lines(&output.stderr), 5)
66+
));
5767
}
5868
Ok(())
5969
}

0 commit comments

Comments
 (0)