codekingpro/portable-devtools
115k
1const { log } = require('proc-log')
2const { resolve, dirname, delimiter } = require('path')
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
5const nodeGypPath = resolve(__dirname, '../lib/node-gyp-bin')
6
7// Windows typically calls its PATH environ 'Path', but this is not
8// guaranteed, nor is it guaranteed to be the only one. Merge them
9// all together in the order they appear in the object.
10const setPATH = (projectPath, binPaths, env) => {
11 const PATH = Object.keys(env).filter(p => /^path$/i.test(p) && env[p])
12 .map(p => env[p].split(delimiter))
13 .reduce((set, p) => set.concat(p.filter(concatted => !set.includes(concatted))), [])
14 .join(delimiter)
15
16 const pathArr = []
17 if (binPaths) {
18 for (const bin of binPaths) {
19 if (bin.includes(delimiter)) {
20 const event = env.npm_lifecycle_event
21 const context = event ? `"${event}" script` : 'script execution'
22 log.warn('run-script', `Path contains delimiter ("${delimiter}"), ${context} may not behave as expected.`)
23 }
24 }
25 pathArr.push(...binPaths)
26 }
27 // unshift the ./node_modules/.bin from every folder
28 // walk up until dirname() does nothing, at the root
29 // XXX we should specify a cwd that we don't go above
30 let p = projectPath
31 let pp
32 do {
33 pathArr.push(resolve(p, 'node_modules', '.bin'))
34 pp = p
35 p = dirname(p)
36 } while (p !== pp)
37 pathArr.push(nodeGypPath, PATH)
38
39 const pathVal = pathArr.join(delimiter)
40
41 // XXX include the node-gyp-bin path somehow? Probably better for
42 // npm or arborist or whoever to just provide that by putting it in
43 // the PATH environ, since that's preserved anyway.
44 for (const key of Object.keys(env)) {
45 if (/^path$/i.test(key)) {
46 env[key] = pathVal
47 }
48 }
49
50 return env
51}
52
53module.exports = setPATH
54 