You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

resolveCommand.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. // If a custom `cwd` was specified, we need to change the process cwd
  9. // because `which` will do stat calls but does not support a custom cwd
  10. if (hasCustomCwd) {
  11. try {
  12. process.chdir(parsed.options.cwd);
  13. } catch (err) {
  14. /* Empty */
  15. }
  16. }
  17. let resolved;
  18. try {
  19. resolved = which.sync(parsed.command, {
  20. path: (parsed.options.env || process.env)[pathKey],
  21. pathExt: withoutPathExt ? path.delimiter : undefined,
  22. });
  23. } catch (e) {
  24. /* Empty */
  25. } finally {
  26. process.chdir(cwd);
  27. }
  28. // If we successfully resolved, ensure that an absolute path is returned
  29. // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
  30. if (resolved) {
  31. resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
  32. }
  33. return resolved;
  34. }
  35. function resolveCommand(parsed) {
  36. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  37. }
  38. module.exports = resolveCommand;