-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.ts
60 lines (55 loc) · 1.91 KB
/
index.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
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
import which from '@zkochan/which'
import execa from 'execa'
import PATH from 'path-name'
export type { execa }
const pathCache = new Map<string, string | undefined>()
export function sync (
file: string,
args?: readonly string[],
options?: execa.SyncOptions
): execa.ExecaSyncReturnValue {
try {
which.sync(file, { path: options?.cwd ?? process.cwd() })
} catch (err: any) {
// If the command is not found in the current directory, there is no need to resolve the command to full location
// as there is no danger of binary planting attack on Windows
if (err.code === 'ENOENT') {
return execa.sync(file, args, options)
}
}
const fileAbsolutePath = getCommandAbsolutePathSync(file, options)
return execa.sync(fileAbsolutePath, args, options)
}
function getCommandAbsolutePathSync (file: string, options?: {
readonly env?: NodeJS.ProcessEnv;
}) {
if (file.includes('\\') || file.includes('/')) return file
const path = options?.env?.[PATH] ?? process.env[PATH]
const key = JSON.stringify([path, file])
let fileAbsolutePath = pathCache.get(key)
if (fileAbsolutePath == null) {
fileAbsolutePath = which.sync(file, { path })
pathCache.set(key, fileAbsolutePath)
}
if (fileAbsolutePath == null) {
throw new Error(`Couldn't find ${file}`)
}
return fileAbsolutePath
}
export default function (
file: string,
args?: readonly string[],
options?: execa.Options
): execa.ExecaChildProcess<string> {
try {
which.sync(file, { path: options?.cwd ?? process.cwd() })
} catch (err: any) {
// If the command is not found in the current directory, there is no need to resolve the command to full location
// as there is no danger of binary planting attack on Windows
if (err.code === 'ENOENT') {
return execa(file, args, options)
}
}
const fileAbsolutePath = getCommandAbsolutePathSync(file, options)
return execa(fileAbsolutePath, args, options)
}