-
Notifications
You must be signed in to change notification settings - Fork 3
/
filenamify.go
159 lines (130 loc) · 3.73 KB
/
filenamify.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
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
package filenamify
import (
"errors"
"math"
"path/filepath"
"regexp"
"sync"
)
type Options struct {
// String for substitution
Replacement string
// maxlength
MaxLength int
}
const MAX_FILENAME_LENGTH = 100
var (
reControlCharsRegex = regexp.MustCompile("[\u0000-\u001f\u0080-\u009f]")
reRelativePathRegex = regexp.MustCompile(`^\.+`)
// https://github.com/sindresorhus/filename-reserved-regex/blob/master/index.js
filenameReservedRegex = regexp.MustCompile(`[<>:"/\\|?*\x00-\x1F]`)
filenameReservedWindowsNamesRegex = regexp.MustCompile(`(?i)^(con|prn|aux|nul|com[0-9]|lpt[0-9])$`)
)
func FilenamifyV2(str string, optFuns ...func(options *Options)) (string, error) {
options := Options{
Replacement: "!", // default remains the same
MaxLength: MAX_FILENAME_LENGTH,
}
for _, fn := range optFuns {
fn(&options)
}
var replacement = options.Replacement
if filenameReservedRegex.MatchString(replacement) && reControlCharsRegex.MatchString(replacement) {
return "", errors.New("replacement string cannot contain reserved filename characters")
}
// reserved word
str = filenameReservedRegex.ReplaceAllString(str, replacement)
// continue
str = reControlCharsRegex.ReplaceAllString(str, replacement)
str = reRelativePathRegex.ReplaceAllString(str, replacement)
// for repeat
if len(replacement) > 0 {
str = trimRepeated(str, replacement)
if len(str) > 1 {
str = stripOuter(str, replacement)
}
}
// for windows names
if filenameReservedWindowsNamesRegex.MatchString(str) {
str = str + replacement
}
// limit length
var limitLength int
if options.MaxLength > 0 {
limitLength = options.MaxLength
} else {
limitLength = MAX_FILENAME_LENGTH
}
strBuf := []rune(str)
strBuf = strBuf[0:int(math.Min(float64(limitLength), float64(len(strBuf))))]
return string(strBuf), nil
}
func Filenamify(str string, options Options) (string, error) {
return FilenamifyV2(str, genFuncFromOptions(options))
}
func PathV2(filePath string, optFuns ...func(options *Options)) (string, error) {
p, err := filepath.Abs(filePath)
if err != nil {
return "", err
}
p, err = FilenamifyV2(filepath.Base(p), optFuns...)
if err != nil {
return "", err
}
return filepath.Join(filepath.Dir(p), p), nil
}
func Path(filePath string, options Options) (string, error) {
return PathV2(filePath, genFuncFromOptions(options))
}
// https://github.com/sindresorhus/escape-string-regexp/blob/master/index.js
var reg = regexp.MustCompile(`[|\\{}()[\]^$+*?.-]`)
func escapeStringRegexp(str string) string {
str = reg.ReplaceAllStringFunc(str, func(s string) string {
return `\` + s
})
return str
}
type expressionCache struct {
sync.RWMutex
exp map[string]*regexp.Regexp
}
func (e *expressionCache) Get(exp string) *regexp.Regexp {
e.RLock()
v, ok := e.exp[exp]
e.RUnlock()
if ok {
return v
}
e.Lock()
defer e.Unlock()
v = regexp.MustCompile(exp)
e.exp[exp] = v
return v
}
var cache = expressionCache{exp: make(map[string]*regexp.Regexp)}
func trimRepeated(str string, replacement string) string {
exp := `(?:` + escapeStringRegexp(replacement) + `){2,}`
reg := cache.Get(exp)
return reg.ReplaceAllString(str, replacement)
}
func stripOuter(input string, substring string) string {
// https://github.com/sindresorhus/strip-outer/blob/master/index.js
substring = escapeStringRegexp(substring)
exp := `^` + substring + `|` + substring + `$`
reg := cache.Get(exp)
return reg.ReplaceAllString(input, "")
}
func genFuncFromOptions(options Options) func(*Options) {
var optFun = func(opt *Options) {
if options.Replacement != "" {
opt.Replacement = options.Replacement
}
if options.MaxLength > 0 {
opt.MaxLength = options.MaxLength
} else {
opt.MaxLength = MAX_FILENAME_LENGTH
}
opt = &options
}
return optFun
}