3 const path = require('path');
4 const which = require('which');
5 const getPathKey = require('path-key');
7 function resolveCommandAttempt(parsed, withoutPathExt) {
8 const env = parsed.options.env || process.env;
9 const cwd = process.cwd();
10 const hasCustomCwd = parsed.options.cwd != null;
11 // Worker threads do not have process.chdir()
12 const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
14 // If a custom `cwd` was specified, we need to change the process cwd
15 // because `which` will do stat calls but does not support a custom cwd
16 if (shouldSwitchCwd) {
18 process.chdir(parsed.options.cwd);
27 resolved = which.sync(parsed.command, {
28 path: env[getPathKey({ env })],
29 pathExt: withoutPathExt ? path.delimiter : undefined,
34 if (shouldSwitchCwd) {
39 // If we successfully resolved, ensure that an absolute path is returned
40 // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
42 resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
48 function resolveCommand(parsed) {
49 return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
52 module.exports = resolveCommand;