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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
extern crate walkdir;
use walkdir::WalkDir;
use std::path::PathBuf;
extern crate chrono;
#[allow(unused_imports)]
use chrono::offset::{Utc, Local};
use chrono::DateTime;
use std::time::SystemTime;
#[allow(dead_code)]
pub fn log_config_path() -> Result<String, &'static str> {
let pathexe = match std::env::current_exe(){
Ok(res) => res,
Err(err) => {
error!("In log_config_path, current_exe(): {}", err);
return Err("log_config_path, failed!");
}
};
let root=pathexe.parent().unwrap();
let parent=root.file_name().unwrap().to_str().unwrap();
let res = if parent == "debug" || parent == "release" {
root.parent().unwrap()
.parent().unwrap()
.to_str().unwrap()
} else {
root.to_str().unwrap()
};
Ok(res.to_owned())
}
#[allow(dead_code)]
pub fn rename_log_with_timestamp(pathstr: &str) -> Result<(), &'static str> {
let path=PathBuf::from(&pathstr);
let md = match std::fs::metadata(&path){
Ok(res) => res,
Err(err) => {
error!("in rename_log_with_timestamp, log file {} does not exist: {}", pathstr, err);
return Ok(())
}
};
if !md.is_file(){
error!("in rename_log_with_timestamp, log {} is NOT a file!", pathstr);
return Err("log file is not one file!")
}
if md.len()==0{
info!("{} is empty!", pathstr);
return Ok(())
}
let system_time = SystemTime::now();
let datetime: DateTime<Local> = system_time.into();
let post_ts=datetime.format("%Y%m%d_%H%M%S");
let ext=if path.extension().is_none(){""}else{path.extension().unwrap().to_str().unwrap()};
let base=path.file_stem().unwrap().to_str().unwrap();
let dir=path.parent().unwrap().to_str().unwrap();
let dest_file=if ext.len()==0{format!("{}/{}_{}", dir, base, post_ts)}else{format!("{}/{}_{}.{}", dir, base, post_ts, ext)};
match FileStatus::copy_file(pathstr, &dest_file){
Ok(_) => (),
Err(err) => {
error!("In rename_log_with_timestamp, copy_file({}, {}):{}", pathstr, &dest_file, err);
return Err("Failed in rename_log_with_timestamp!");
}
};
match FileStatus::delete_file(pathstr){
Ok(_) => (),
Err(err) => {
error!("In rename_log_with_timestamp, delete_file({}):{}", pathstr, err);
return Err("Failed in rename_log_with_timestamp!");
}
};
Ok(())
}
#[allow(dead_code)]
#[derive(Debug)]
pub struct FileStatus {
path: String,
name: String,
isdir: bool,
filetype: String,
size: u64,
dt_modified: String,
dt_accessed: String,
dt_created: String,
}
impl FileStatus {
#[allow(dead_code)]
pub fn get_status(path: &PathBuf) -> Result<FileStatus, &'static str> {
let ext=if path.extension().is_none(){""}else{path.extension().unwrap().to_str().unwrap()};
let filename=path.file_name().unwrap().to_str().unwrap();
let dir=path.parent().unwrap().to_str().unwrap();
let md = std::fs::metadata(path).unwrap();
let res=FileStatus {
path: dir.to_string()
, name: filename.to_string()
, isdir: md.is_dir()
, filetype: ext.to_string()
, size: md.len()
,dt_modified: if let Ok(time) = md.modified() {
let datetime: chrono::DateTime<chrono::offset::Local> = time.into();
datetime.format("%Y-%m-%d %H:%M:%S").to_string()
}else{return Err("failed to get modified time!");}
,dt_accessed: if let Ok(time) = md.accessed() {
let datetime: chrono::DateTime<chrono::offset::Local> = time.into();
datetime.format("%Y-%m-%d %H:%M:%S").to_string()
}else{return Err("failed to get accessed time!");}
,dt_created: if let Ok(time) = md.created() {
let datetime: chrono::DateTime<chrono::offset::Local> = time.into();
datetime.format("%Y-%m-%d %H:%M:%S").to_string()
}else{return Err("failed to get created time!");}
};
Ok(res)
}
#[allow(dead_code)]
pub fn get_file_status_under_folder(path: &str,
delimiter: &str,
mntpoint: &str,
) -> Result<String, &'static str> {
let pathori=PathBuf::from(path);
let pathcrt=if pathori.is_relative(){
std::env::current_dir().unwrap().join(path)
} else {pathori};
let dir=WalkDir::new(pathcrt.to_str().unwrap());
let mut res="".to_string();
for e in dir.into_iter().filter_map(|e| e.ok()){
if e.metadata().unwrap().is_file(){
let buf = PathBuf::from(e.path());
let fs=FileStatus::get_status(&buf).unwrap();
let mntpointpath=&fs.path.replace("/mnt/", mntpoint);
res.push_str(&fs.name);res.push_str(delimiter);
res.push_str(mntpointpath);res.push_str(delimiter);
res.push_str(&fs.filetype);res.push_str(delimiter);
res.push_str(mntpointpath);res.push_str("/");
res.push_str(&fs.name);res.push_str(delimiter);
res.push_str(&fs.size.to_string());res.push_str(delimiter);
res.push_str(&fs.dt_created);res.push_str("\n");
}
}
Ok(res)
}
#[allow(dead_code)]
pub fn delete_file(path: &str,
) -> Result<(), &'static str> {
let md = match std::fs::metadata(path){
Ok(res) => res,
Err(err) => {
error!("In FileStatus::delete_file(), std::fs::metadata errored:\n{}: {}", path, err);
return Err("Failed to delete_file!");
},
};
if md.is_file(){
match std::fs::remove_file(path){
Ok(_) => (),
Err(err) => {
error!("In FileStatus::delete_file({}), std::fs::remove_file errored:\n{}", path, err);
return Err("Failed to delete_file!");
},
}
} else {
error!("In FileStatus::delete_file({}), it is not a file!", path);
return Err("Failed to delete_file!");
}
Ok(())
}
#[allow(dead_code)]
pub fn copy_file(ori_path: &str,
dest_path: &str,
) -> Result<(), &'static str> {
let md = match std::fs::metadata(ori_path){
Ok(res) => res,
Err(err) => {
error!("In FileStatus::copy_file(), std::fs::metadata errored:\n{}: {}", ori_path, err);
return Err("Failed to copy_file!");
},
};
if !md.is_file(){
error!("In FileStatus::copy_file({}), it is not a file!", ori_path);
return Err("Failed to copy_file!");
}
if std::path::Path::new(dest_path).exists(){
error!("In FileStatus::copy_file(), destination file {} already exists!", dest_path);
return Err("Failed to copy_file!");
}
let dir=std::path::Path::new(dest_path).parent().unwrap();
if !dir.exists() {
match std::fs::create_dir_all(dir.to_str().unwrap()){
Ok(_) => (),
Err(err) => {
error!("In FileStatus::copy_file({}, {}), std::fs::create_dir_all errored:\n{}", ori_path, dest_path, err);
return Err("Failed to copy_file!");
}
};
}
match std::fs::copy(ori_path, dest_path){
Ok(_) => (),
Err(err) => {
error!("In FileStatus::copy_file({}, {}), std::fs::copy errored:\n{}", ori_path, dest_path, err);
return Err("Failed to copy_file!");
},
};
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_file_status() {
let filename="README.md";
let pathori=PathBuf::from(filename);
let path=if pathori.is_relative(){
std::env::current_dir().unwrap().join(filename)
} else {pathori};
let fs=FileStatus::get_status(&path).unwrap();
assert_eq!(fs.name,"README.md".to_string());
}
}