set-path.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. const {resolve, dirname} = require('path')
  2. const isWindows = require('./is-windows.js')
  3. // the path here is relative, even though it does not need to be
  4. // in order to make the posix tests pass in windows
  5. const nodeGypPath = resolve(__dirname, '../lib/node-gyp-bin')
  6. // Windows typically calls its PATH environ 'Path', but this is not
  7. // guaranteed, nor is it guaranteed to be the only one. Merge them
  8. // all together in the order they appear in the object.
  9. const setPATH = (projectPath, env) => {
  10. // not require('path').delimiter, because we fake this for testing
  11. const delimiter = isWindows ? ';' : ':'
  12. const PATH = Object.keys(env).filter(p => /^path$/i.test(p) && env[p])
  13. .map(p => env[p].split(delimiter))
  14. .reduce((set, p) => set.concat(p.filter(p => !set.includes(p))), [])
  15. .join(delimiter)
  16. const pathArr = []
  17. // unshift the ./node_modules/.bin from every folder
  18. // walk up until dirname() does nothing, at the root
  19. // XXX should we specify a cwd that we don't go above?
  20. let p = projectPath
  21. let pp
  22. do {
  23. pathArr.push(resolve(p, 'node_modules', '.bin'))
  24. pp = p
  25. p = dirname(p)
  26. } while (p !== pp)
  27. pathArr.push(nodeGypPath, PATH)
  28. const pathVal = pathArr.join(delimiter)
  29. // XXX include the node-gyp-bin path somehow? Probably better for
  30. // npm or arborist or whoever to just provide that by putting it in
  31. // the PATH environ, since that's preserved anyway.
  32. for (const key of Object.keys(env)) {
  33. if (/^path$/i.test(key))
  34. env[key] = pathVal
  35. }
  36. return env
  37. }
  38. module.exports = setPATH