-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsanitize.js
44 lines (36 loc) · 1.01 KB
/
sanitize.js
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
const FORBIDDEN_SEPARATOR_CHARS = [' ', '..', '~', '^', ':', '?', '*', '[', '@']
function sanitize (input, separator = '_') {
FORBIDDEN_SEPARATOR_CHARS.forEach((forbiddenChar) => {
if (separator.indexOf(forbiddenChar) !== -1) {
throw new Error(`Invalid separator char: ${forbiddenChar}`)
}
})
let output = input
output = output.replace(/\/\s+/g, '/')
const toRemove = [
/~/g,
/\^/g,
/:/g,
/\\/g,
/\.\.$/,
/(@\{)+/g,
/\?/g,
/\*/g,
/\[/g
]
output = toRemove.reduce((output, regexp) => {
return output.replace(regexp, '')
}, output)
const toSeparate = [
/(\.\.)+/g,
/\s+/g
]
output = toSeparate.reduce((output, regexp) => {
return output.replace(regexp, separator)
}, output)
output = output.replace(/\/\./g, '/')
.replace(/(\/[^/]+)\.lock/g, `$1${separator}lock`)
.replace(/\/+/g, '/')
return output
}
module.exports = sanitize