/
path.go
50 lines (40 loc) Β· 1.07 KB
/
path.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
package clean
import (
"path"
"strings"
"unicode"
)
// Path removes invalid character from a path string.
func Path(s string) string {
if s == "" || reject(s, 512) || strings.Contains(s, "..") || strings.Contains(s, "//") {
return ""
}
// Trim whitespace.
s = strings.TrimSpace(s)
// Remove non-printable and other potentially problematic characters.
// The following characters must never be used in a filepath: \ > < | : &
s = strings.Map(func(r rune) rune {
if !unicode.IsPrint(r) {
return -1
}
switch r {
case '\\', '|', '"', '?', '*', '%', '<', '>', '{', '}':
return -1
default:
return r
}
}, s)
return s
}
// UserPath sanitizes and normalizes a user provided path, so it can be used.
func UserPath(dir string) string {
if dir == "" {
return dir
}
// The following characters must never be used in a filepath: \ > < | : &
dir = strings.Trim(path.Clean(Path(strings.ReplaceAll(dir, "\\", "/"))), " ~./\\|?*%<>")
if strings.Contains(dir, "/.") || strings.Contains(dir, "..") || strings.Contains(dir, "//") {
return ""
}
return dir
}