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
pub mod permissions;
use std::{
fs::{self, File},
io::{Error, ErrorKind},
path::{Path, PathBuf},
};
use crate::{Args, Result};
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum PathKind {
Directory,
File,
}
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum TakeOption {
MustExist,
DenyExisting,
Take {
make: bool,
},
}
pub fn get_path(args: &Args, keys: &[&str], kind: PathKind, option: TakeOption) -> Result<Option<PathBuf>> {
match args.get::<PathBuf>(keys)? {
Some(path) => handle_path(path, kind, option).map(|p| Some(p)),
None => Ok(None),
}
}
pub fn take_path(args: &mut Args, keys: &[&str], kind: PathKind, option: TakeOption) -> Result<Option<PathBuf>> {
match args.take::<PathBuf>(keys)? {
Some(path) => handle_path(path, kind, option).map(|p| Some(p)),
None => Ok(None),
}
}
pub fn handle_path<P>(path: P, kind: PathKind, option: TakeOption) -> Result<P> where P: AsRef<Path> {
{
let path = path.as_ref();
if match option {
TakeOption::MustExist => true,
TakeOption::Take { .. } if path.exists() => true,
_ => false,
} {
match kind {
PathKind::Directory => if path.is_dir() == false {
return Err(Error::new(ErrorKind::InvalidInput, format!("Not a directory: {:?}", path)));
},
PathKind::File => if path.is_file() == false {
return Err(Error::new(ErrorKind::InvalidInput, format!("Not a file: {:?}", path)));
},
};
}
match option {
TakeOption::MustExist => if path.exists() == false {
return Err(Error::new(ErrorKind::NotFound, format!("Not found: {:?}", path)));
},
TakeOption::DenyExisting => if path.exists() {
return Err(Error::new(ErrorKind::AlreadyExists, format!("Already exists: {:?}", path)));
},
TakeOption::Take { make } => if make && path.exists() == false {
match kind {
PathKind::Directory => fs::create_dir_all(&path)?,
PathKind::File => drop(File::create(&path)?),
};
},
};
}
Ok(path)
}
#[test]
fn test_take_path() {
const KEYS: &[&str] = &["--path"];
let mut args = crate::parse_strings([&KEYS[0], file!()].iter()).unwrap();
assert!(take_path(&mut args, KEYS, PathKind::File, TakeOption::MustExist).unwrap().is_some());
assert!(args.is_empty());
let mut args = crate::parse_strings([&KEYS[0], file!()].iter()).unwrap();
assert_eq!(get_path(&mut args, KEYS, PathKind::File, TakeOption::DenyExisting).unwrap_err().kind(), ErrorKind::AlreadyExists);
assert!(args.is_empty() == false);
let mut args = crate::parse_strings([&KEYS[0], file!()].iter()).unwrap();
assert_eq!(take_path(&mut args, KEYS, PathKind::Directory, TakeOption::Take { make: false }).unwrap_err().kind(), ErrorKind::InvalidInput);
assert!(args.is_empty());
}
#[cfg(unix)]
const INVALID_FILE_NAME_CHARS: &[char] = &[];
#[cfg(not(unix))]
const INVALID_FILE_NAME_CHARS: &[char] = &['^', '?', '%', '*', ':', '|', '"', '<', '>'];
pub fn verify_ne_file_name<S>(name: S, max_len: Option<usize>) -> Result<()> where S: AsRef<str> {
let name = name.as_ref();
if name.len() > max_len.unwrap_or(1024) {
return Err(Error::new(ErrorKind::InvalidInput, "File name is too long"));
}
if name.is_empty() {
return Err(Error::new(ErrorKind::InvalidInput, "File name is empty"));
}
if name.trim().len() != name.len() {
return Err(Error::new(ErrorKind::InvalidInput, "File name contains leading or trailing white space(s)"));
}
if name.chars().any(|c| match c.is_ascii() {
true => match c as u8 {
0..=31 | 127 | b'\\' | b'/' => true,
_ => INVALID_FILE_NAME_CHARS.contains(&c),
},
false => false,
}) {
return Err(Error::new(ErrorKind::InvalidInput, "File name contains invalid character(s)"));
}
Ok(())
}