set-path.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. const { resolve, dirname, delimiter } = require('path')
  2. // the path here is relative, even though it does not need to be
  3. // in order to make the posix tests pass in windows
  4. const nodeGypPath = resolve(__dirname, '../lib/node-gyp-bin')
  5. // Windows typically calls its PATH environ 'Path', but this is not
  6. // guaranteed, nor is it guaranteed to be the only one. Merge them
  7. // all together in the order they appear in the object.
  8. const setPATH = (projectPath, binPaths, env) => {
  9. const PATH = Object.keys(env).filter(p => /^path$/i.test(p) && env[p])
  10. .map(p => env[p].split(delimiter))
  11. .reduce((set, p) => set.concat(p.filter(concatted => !set.includes(concatted))), [])
  12. .join(delimiter)
  13. const pathArr = []
  14. if (binPaths) {
  15. pathArr.push(...binPaths)
  16. }
  17. // unshift the ./node_modules/.bin from every folder
  18. // walk up until dirname() does nothing, at the root
  19. // XXX we should 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. }
  37. return env
  38. }
  39. module.exports = setPATH