This repository was archived by the owner on Jul 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 287
/
Copy pathenvironment.ts
198 lines (168 loc) · 4.63 KB
/
environment.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import spawn from 'cross-spawn';
import fs from 'fs';
import path from 'path';
const SHIM_DIR = path.resolve(__dirname, 'shims');
function isWindows(): boolean {
return process.platform === 'win32';
}
function defaultShell(): string {
if (isWindows()) {
return process.env.COMSPEC || 'cmd.exe';
}
if (!process.env.SHELL) {
return process.platform === 'darwin' ? '/bin/bash' : '/bin/sh';
}
return process.env.SHELL;
}
function shimExtension(shell: string): string {
let extension = 'sh';
if (shell.indexOf('fish') >= 0) extension = 'fish';
else if (isWindows()) extension = 'cmd';
return extension;
}
function getTemplate(shell: string): string {
let template;
if (isWindows()) {
template = 'SET';
} else if (shell.indexOf('fish') >= 0) {
template = `#!${shell}
for name in (set -nx)
if string match --quiet '*PATH' $name
echo $name=(string join : -- $$name)
else
echo $name="$$name"
end
end`;
} else {
template = `#!${shell} -i\nexport`;
}
return template;
}
function mkShim(shell: string, shimPath: string): boolean {
const template = getTemplate(shell);
let result = false;
try {
fs.writeFileSync(shimPath, template);
fs.chmodSync(shimPath, 0o744);
result = true;
} catch (e) {
console.error(e);
}
return result;
}
function getShellName(shell: string): string {
const cleanShell = isWindows() ? path.basename(shell) : shell;
return cleanShell.replace(/[\/\\]/g, '.');
}
function getShim(shell: string, shimDir: string): string {
let shellName: string = getShellName(shell);
if (shellName[0] === '.') shellName = shellName.slice(1);
const shimPath = path.join(shimDir, `env.${shellName}.${shimExtension(shellName)}`);
if (!fs.existsSync(shimDir)) {
fs.mkdirSync(shimDir);
}
if (!fs.existsSync(shimPath)) {
mkShim(shell, shimPath);
}
return shimPath;
}
// Based on the dotenv parse function:
// https://github.com/motdotla/dotenv/blob/main/lib/main.js#L32
// modified to not have to deal with Buffers and to handle stuff
// like export and declare -x at the start of the line
function processExportLine(line: string): string[] {
const result = [];
// matching "KEY' and 'VAL' in 'KEY=VAL' with support for arbitrary prefixes
const keyValueArr = line.match(/^(?:[\w-]*\s+)*([\w.-]+)\s*=\s*(.*)?\s*$/);
if (keyValueArr != null) {
const key = keyValueArr[1];
// default undefined or missing values to empty string
let value = keyValueArr[2] || '';
// expand newlines in quoted values
const len = value ? value.length : 0;
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, '\n');
}
// remove any surrounding quotes and extra spaces
value = value.replace(/(^['"]|['"]$)/g, '').trim();
result.push(key, value);
}
return result;
}
function processEnvironment(output: string): IEnvironment {
const env: IEnvironment = {};
for (const line of output.split('\n')) {
const result: string[] = processExportLine(line);
const name = result[0];
if (RUBY_ENVIRONMENT_VARIABLES.indexOf(name) >= 0) {
env[name] = result[1];
}
}
return env;
}
// Whitelist environment variables to pass on
// Don't want to pull in potentially secret variables
// If updating this make sure the RubyEnvironment interface
// also gets updated.
//
// It'd be really nice if there was a way
// of generating the correct constant and/or TypeScript interface
// from a single declaration
const RUBY_ENVIRONMENT_VARIABLES = [
'PATH',
'Path', // Windows
'PATHEXT', // Windows
'RUBY_VERSION',
'RUBY_ROOT',
'RUBY_ENGINE',
'RUBYOPT',
'GEM_HOME',
'GEM_PATH',
'GEM_ROOT',
'HOME',
'RUBOCOP_OPTS',
'LANG',
'BUNDLE_PATH',
'RBENV_ROOT',
'ASDF_DATA_DIR',
'ASDF_CONFIG_FILE',
'ASDF_DEFAULT_TOOL_VERSIONS_FILENAME',
];
export interface IEnvironment {
[key: string]: string;
}
export interface RubyEnvironment extends IEnvironment {
PATH: string;
Path?: string; // Windows
PATHEXT?: string; // Windows
RUBY_VERSION: string;
RUBY_ROOT: string;
RUBY_ENGINE: string;
RUBYOPT: string;
GEM_HOME: string;
GEM_PATH: string;
GEM_ROOT: string;
HOME: string;
RUBOCOP_OPTS: string;
LANG: string;
BUNDLE_PATH?: string;
RBENV_ROOT?: string;
ASDF_DATA_DIR?: string;
ASDF_CONFIG_FILE?: string;
ASDF_DEFAULT_TOOL_VERSIONS_FILENAME?: string;
}
export interface LoadEnvOptions {
shell?: string;
shimDir?: string;
}
export function loadEnv(cwd: string, options = {} as LoadEnvOptions): IEnvironment {
const { shell = defaultShell(), shimDir = SHIM_DIR } = options;
const shim: string = getShim(shell, shimDir);
const { stdout, stderr, status } = spawn.sync(shim, [], {
cwd,
});
if (status !== 0) {
console.error(stderr.toString());
}
return processEnvironment(stdout.toString());
}