1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use serde_derive::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
use crate::base::GlobPatterns;
use crate::error::{Error, ErrorKind};
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct FileSet {
pub from: String,
pub to: String,
pub filter: Option<GlobPatterns>,
pub mode: Option<i32>,
}
impl FileSet {
pub fn copy_to(&self, src: &str, dest: &Path) -> Result<(), Error> {
log::info!("FileSet::copy_to() src: {:?}, dest: {:?}", src, dest);
let dest_path = dest.join(&self.to);
let dest_dir = dest_path.parent().ok_or(Error::from_string(
ErrorKind::IoError,
format!("Failed to get parent dir of dest_path: {:?}", dest_path),
))?;
fs::create_dir_all(dest_dir).map_err(|err| {
Error::from_string(
ErrorKind::IoError,
format!(
"Failed to create directory `{:?}`, error: {:?}",
dest_dir, err
),
)
})?;
let src_pattern = format!("{}/{}", src, &self.from);
let entries = glob::glob(&src_pattern).map_err(|err| {
Error::from_string(
ErrorKind::GlobPatternError,
format!(
"Failed to crate glob pattern for {:?}, error: {:?}",
&src_pattern, err
),
)
})?;
let mut entry_not_match = true;
for entry in entries {
entry_not_match = false;
let entry = entry?;
let metadata = fs::metadata(&entry)?;
if metadata.is_file() {
fs::copy(&entry, &dest_path).map_err(|err| {
Error::from_string(
ErrorKind::IoError,
format!(
"Failed to copy file from `{:?}` to `{:?}`, err: {:?}",
&entry, &dest_path, err
),
)
})?;
} else if metadata.is_dir() {
fs::create_dir_all(&dest_path).map_err(|err| {
Error::from_string(
ErrorKind::IoError,
format!(
"Failed to create directory `{:?}`, error: {:?}",
&dest_path, err
),
)
})?;
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.copy_inside = true;
fs_extra::dir::copy(&entry, &dest_path, &options).map_err(|err| {
Error::from_string(
ErrorKind::IoError,
format!(
"Failed to copy folder from `{:?}` to `{:?}`, err: {:?}",
&entry, &dest_path, err
),
)
})?;
} else {
return Err(Error::from_string(
ErrorKind::IoError,
format!("Unsupported file type: {:?}", entry),
));
}
}
if entry_not_match {
Err(Error::from_string(
ErrorKind::GlobError,
format!("No file is matched with pattern `{}`", src_pattern),
))
} else {
Ok(())
}
}
}
pub fn copy_filesets(files: &[FileSet], src: &str, dest: &Path) -> Result<(), Error> {
log::info!(
"copy_filesets() files: {:?}, src: {:?}, dest: {:?}",
files,
src,
dest
);
for ref file in files {
file.copy_to(src, dest)?;
}
Ok(())
}