forked from tinylibs/tinyexec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.ts
61 lines (48 loc) · 1.33 KB
/
env.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import {
delimiter as pathDelimiter,
resolve as resolvePath,
dirname
} from 'node:path';
export type EnvLike = (typeof process)['env'];
export interface EnvPathInfo {
key: string;
value: string;
}
const isPathLikePattern = /^path$/i;
const defaultEnvPathInfo = {key: 'PATH', value: ''};
function getPathFromEnv(env: EnvLike): EnvPathInfo {
for (const key in env) {
if (
!Object.prototype.hasOwnProperty.call(env, key) ||
!isPathLikePattern.test(key)
) {
continue;
}
const value = env[key];
if (!value) {
return defaultEnvPathInfo;
}
return {key, value};
}
return defaultEnvPathInfo;
}
function addNodeBinToPath(cwd: string, path: EnvPathInfo): EnvPathInfo {
const parts = path.value.split(pathDelimiter);
let currentPath = cwd;
let lastPath: string;
do {
parts.push(resolvePath(currentPath, 'node_modules', '.bin'));
lastPath = currentPath;
currentPath = dirname(currentPath);
} while (currentPath !== lastPath);
return {key: path.key, value: parts.join(pathDelimiter)};
}
export function computeEnv(cwd: string, env?: EnvLike): EnvLike {
const envWithDefault = {
...process.env,
...env
};
const envPathInfo = addNodeBinToPath(cwd, getPathFromEnv(envWithDefault));
envWithDefault[envPathInfo.key] = envPathInfo.value;
return envWithDefault;
}