blob: 4ac050fc3846e06a7583d7e9ea35fed5a4b437a5 (
plain)
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
|
const fs = require('fs')
const {promisify} = require('util')
const {readFileSync} = fs
const readFile = promisify(fs.readFile)
const extractPath = (path, cmdshimContents) => {
if (/[.]cmd$/.test(path)) {
return extractPathFromCmd(cmdshimContents)
} else if (/[.]ps1$/.test(path)) {
return extractPathFromPowershell(cmdshimContents)
} else {
return extractPathFromCygwin(cmdshimContents)
}
}
const extractPathFromPowershell = cmdshimContents => {
const matches = cmdshimContents.match(/"[$]basedir[/]([^"]+?)"\s+[$]args/)
return matches && matches[1]
}
const extractPathFromCmd = cmdshimContents => {
const matches = cmdshimContents.match(/"%(?:~dp0|dp0%)\\([^"]+?)"\s+%[*]/)
return matches && matches[1]
}
const extractPathFromCygwin = cmdshimContents => {
const matches = cmdshimContents.match(/"[$]basedir[/]([^"]+?)"\s+"[$]@"/)
return matches && matches[1]
}
const wrapError = (thrown, newError) => {
newError.message = thrown.message
newError.code = thrown.code
newError.path = thrown.path
return newError
}
const notaShim = (path, er) => {
if (!er) {
er = new Error()
Error.captureStackTrace(er, notaShim)
}
er.code = 'ENOTASHIM'
er.message = `Can't read shim path from '${path}', ` +
`it doesn't appear to be a cmd-shim`
return er
}
const readCmdShim = path => {
// create a new error to capture the stack trace from this point,
// instead of getting some opaque stack into node's internals
const er = new Error()
Error.captureStackTrace(er, readCmdShim)
return readFile(path).then(contents => {
const destination = extractPath(path, contents.toString())
if (destination) return destination
return Promise.reject(notaShim(path, er))
}, readFileEr => Promise.reject(wrapError(readFileEr, er)))
}
const readCmdShimSync = path => {
const contents = readFileSync(path)
const destination = extractPath(path, contents.toString())
if (!destination) throw notaShim(path)
return destination
}
readCmdShim.sync = readCmdShimSync
module.exports = readCmdShim
|