-
Notifications
You must be signed in to change notification settings - Fork 1
/
sanitize_filenames.go
67 lines (61 loc) · 1.29 KB
/
sanitize_filenames.go
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
package main
import (
"strconv"
"strings"
)
var windowsSubst = map[rune]string{
'<': "<",
'>': ">",
':': "-",
'"': """,
'/': "",
'\\': "",
'|': "",
'?': "",
'*': "",
}
var minimalSubst = map[rune]string{
'/': "",
'\\': "",
}
var winBan = map[string]bool{
"CON": true, "PRN": true, "AUX": true, "NUL": true,
"COM1": true, "COM2": true, "COM3": true, "COM4": true,
"COM5": true, "COM6": true, "COM7": true, "COM8": true, "COM9": true,
"LPT1": true, "LPT2": true, "LPT3": true, "LPT4": true,
"LPT5": true, "LPT6": true, "LPT7": true, "LPT8": true, "LPT9": true,
}
func sanitizeWindowsFilename(name string) string {
name = strings.Trim(name, " .")
sansExt := strings.SplitN(name, ".", 2)[0]
if winBan[sansExt] {
return "__" + name
}
if name == "" {
return "__Blank__"
}
return name
}
func sanitizeFileName(filename string, allowSpecialChars bool) string {
var b strings.Builder
var banned map[rune]string
if allowSpecialChars {
banned = minimalSubst
} else {
banned = windowsSubst
}
for _, r := range filename {
repl, spec := banned[r]
if spec {
b.WriteString(repl)
} else if !strconv.IsPrint(r) {
b.WriteRune('-')
} else {
b.WriteRune(r)
}
}
if allowSpecialChars {
return b.String()
}
return sanitizeWindowsFilename(b.String())
}