resolveCommand.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const path = require('path');
  3. const which = require('which');
  4. const pathKey = require('path-key')();
  5. function resolveCommandAttempt(parsed, withoutPathExt) {
  6. const cwd = process.cwd();
  7. const hasCustomCwd = parsed.options.cwd != null;
  8. // Worker threads do not have process.chdir()
  9. const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined;
  10. // If a custom `cwd` was specified, we need to change the process cwd
  11. // because `which` will do stat calls but does not support a custom cwd
  12. if (shouldSwitchCwd) {
  13. try {
  14. process.chdir(parsed.options.cwd);
  15. } catch (err) {
  16. /* Empty */
  17. }
  18. }
  19. let resolved;
  20. try {
  21. resolved = which.sync(parsed.command, {
  22. path: (parsed.options.env || process.env)[pathKey],
  23. pathExt: withoutPathExt ? path.delimiter : undefined,
  24. });
  25. } catch (e) {
  26. /* Empty */
  27. } finally {
  28. if (shouldSwitchCwd) {
  29. process.chdir(cwd);
  30. }
  31. }
  32. // If we successfully resolved, ensure that an absolute path is returned
  33. // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
  34. if (resolved) {
  35. resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
  36. }
  37. return resolved;
  38. }
  39. function resolveCommand(parsed) {
  40. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  41. }
  42. module.exports = resolveCommand;