-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathresolve-command.ts
63 lines (56 loc) · 1.71 KB
/
resolve-command.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
61
62
63
import * as path from 'node:path';
import {chdir} from 'node:process';
import which from 'which';
import {getPathFromEnv} from './env.js';
import {type ParsedShellOptions} from './shared-types.js';
function resolveCommandAttempt(
parsed: ParsedShellOptions,
withoutPathExt: boolean
): string | undefined {
const env = parsed.options.env || process.env;
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
// Worker threads do not have process.chdir()
const shouldSwitchCwd =
hasCustomCwd &&
chdir !== undefined &&
!(chdir as typeof chdir & {disabled?: boolean}).disabled;
// If a custom `cwd` was specified, we need to change the process cwd
// because `which` will do stat calls but does not support a custom cwd
if (shouldSwitchCwd && typeof parsed.options.cwd === 'string') {
try {
chdir(parsed.options.cwd);
} catch (err) {
/* Empty */
}
}
let resolved;
try {
resolved = which.sync(parsed.command, {
path: getPathFromEnv(env).value,
pathExt: withoutPathExt ? path.delimiter : undefined
});
} catch (e) {
/* Empty */
} finally {
if (shouldSwitchCwd) {
chdir(cwd);
}
}
// If we successfully resolved, ensure that an absolute path is returned
// Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
if (resolved) {
resolved = path.resolve(
hasCustomCwd && typeof parsed.options.cwd === 'string'
? parsed.options.cwd
: '',
resolved
);
}
return resolved;
}
export function resolveCommand(parsed: ParsedShellOptions): string | undefined {
return (
resolveCommandAttempt(parsed, false) || resolveCommandAttempt(parsed, true)
);
}