index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use strict"
  2. var which = require('which')
  3. var npmPath = require('npm-path')
  4. module.exports = function(cwd) {
  5. function npmWhich(cmd, options, fn) {
  6. // options is optional
  7. if (options instanceof Function) fn = options, options = null
  8. options = options || {}
  9. options.cwd = options.cwd || cwd
  10. options.env = options.env || process.env
  11. function curryWhich(opts, fn) {
  12. if (opts instanceof Function) fn = opts, opts = null
  13. opts = opts || {}
  14. return npmWhich(cmd, mixin(opts, options), fn)
  15. }
  16. curryWhich.sync = function(opts) {
  17. opts = opts || {}
  18. return npmWhich.sync(cmd, mixin(opts, options))
  19. }
  20. if (!(typeof fn === 'function')) return curryWhich
  21. if (!options.cwd) return fn(new Error('You must specify a cwd.'))
  22. npmPath.get(options, function(err, newPath) {
  23. if (err) return fn(err)
  24. var oldPath = process.env[npmPath.PATH]
  25. process.env[npmPath.PATH] = newPath
  26. which(cmd, function(err, result) {
  27. process.env[npmPath.PATH] = oldPath
  28. fn(err, result)
  29. })
  30. })
  31. }
  32. npmWhich.sync = function(cmd, options) {
  33. options = options || {}
  34. options.cwd = options.cwd || cwd
  35. options.env = options.env || process.env
  36. if (!options.cwd) throw new Error('You must specify a cwd.')
  37. var err = null
  38. try {
  39. var oldPath = process.env[npmPath.PATH]
  40. var newPath = npmPath.getSync(options)
  41. process.env[npmPath.PATH] = newPath
  42. var result = which.sync(cmd)
  43. return result
  44. } catch(e) {
  45. err = e
  46. } finally {
  47. process.env[npmPath.PATH] = oldPath
  48. if (err) throw err
  49. }
  50. return result
  51. }
  52. if (arguments.length <= 1) return npmWhich
  53. return module.exports().apply(this, arguments)
  54. }
  55. module.exports.sync = function(cmd, options) {
  56. options = options || {}
  57. return module.exports(options.cwd).sync(cmd, options)
  58. }
  59. function mixin(a, b) {
  60. for (var key in b) {
  61. a[key] = b[key]
  62. }
  63. return a
  64. }