-
-
Notifications
You must be signed in to change notification settings - Fork 269
/
clean-cwd.ts
32 lines (29 loc) · 946 Bytes
/
clean-cwd.ts
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
import { cwd } from '@tapjs/core'
import { pathToFileURL } from 'node:url'
// escape a string to json, then unwrap the "
// used for cwd detection
const esc = (s: string) => {
const j = JSON.stringify(s)
return j.substring(1, j.length - 1)
}
const cwdURL = String(pathToFileURL(cwd)).substring('file://'.length)
const cwdPosix = cwd.replace(/\\/g, '/')
const cwdLcase = cwd.toLowerCase()
const cwdPosixLcase = cwdPosix.toLowerCase()
const cwds = new Set([cwdURL, cwd, cwdPosix, cwdLcase, cwdPosixLcase])
for (const c of [...cwds]) {
cwds.add(esc(c))
cwds.add(esc(esc(c)))
cwds.add(esc(esc(esc(c))))
cwds.add(esc(esc(esc(esc(c)))))
}
const reSpecial = /[/\-\\^$*+?.()|[\]{}]/g
const escapeRegex = (s: string) => s.replace(reSpecial, '\\$&')
export const cleanCWD = (snap: string) => {
const tag = '{CWD}'
for (const c of cwds) {
const r = new RegExp(escapeRegex(c), 'gi')
snap = snap.replace(r, tag)
}
return snap
}