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
use regex::Regex;
pub fn filenamify<S: AsRef<str>>(input: S) -> String {
let replacemant = "_";
let reserved = Regex::new("[<>:\"/\\\\|?*\u{0000}-\u{001F}\u{007F}\u{0080}-\u{009F}]+").unwrap();
let windows_reserved = Regex::new("^(con|prn|aux|nul|com\\d|lpt\\d)$").unwrap();
let outer_periods = Regex::new("^\\.+|\\.+$").unwrap();
let input = reserved.replace_all(input.as_ref(), replacemant);
let input = outer_periods.replace_all(input.as_ref(), replacemant);
let mut result = input.into_owned();
if windows_reserved.is_match(result.as_str()) {
result.push_str(replacemant);
}
result
}
#[cfg(test)]
mod tests {
use super::filenamify;
#[test]
fn test_filenamify() {
assert_eq!(filenamify("foo/bar"), "foo_bar");
assert_eq!(filenamify("foo//bar"), "foo_bar");
assert_eq!(filenamify("//foo//bar//"), "_foo_bar_");
assert_eq!(filenamify("foo\\bar"), "foo_bar");
assert_eq!(filenamify("foo\\\\\\bar"), "foo_bar");
assert_eq!(filenamify(r"foo\\bar"), "foo_bar");
assert_eq!(filenamify(r"foo\\\\\\bar"), "foo_bar");
assert_eq!(filenamify("////foo////bar////"), "_foo_bar_");
assert_eq!(filenamify("foo\u{0000}bar"), "foo_bar");
assert_eq!(filenamify("\"foo<>bar*"), "_foo_bar_");
assert_eq!(filenamify("."), "_");
assert_eq!(filenamify(".."), "_");
assert_eq!(filenamify("./"), "__");
assert_eq!(filenamify("../"), "__");
assert_eq!(filenamify("../../foo/bar"), "__.._foo_bar");
assert_eq!(filenamify("foo.bar."), "foo.bar_");
assert_eq!(filenamify("foo.bar.."), "foo.bar_");
assert_eq!(filenamify("foo.bar..."), "foo.bar_");
assert_eq!(filenamify("con"), "con_");
assert_eq!(filenamify("com1"), "com1_");
assert_eq!(filenamify(":nul|"), "_nul_");
assert_eq!(filenamify("foo/bar/nul"), "foo_bar_nul");
assert_eq!(filenamify("file:///file.tar.gz"), "file_file.tar.gz");
assert_eq!(filenamify("http://www.google.com"), "http_www.google.com");
assert_eq!(filenamify("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), "https_www.youtube.com_watch_v=dQw4w9WgXcQ");
}
}