forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
environment.ts
234 lines (211 loc) · 7.96 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { pathExistsSync, readFileSync } from '../platform/fs-paths';
import { inject, injectable } from 'inversify';
import * as path from 'path';
import { traceError } from '../../logging';
import { sendTelemetryEvent } from '../../telemetry';
import { EventName } from '../../telemetry/constants';
import { IFileSystem } from '../platform/types';
import { IPathUtils } from '../types';
import { EnvironmentVariables, IEnvironmentVariablesService } from './types';
import { normCase } from '../platform/fs-paths';
@injectable()
export class EnvironmentVariablesService implements IEnvironmentVariablesService {
private _pathVariable?: 'Path' | 'PATH';
constructor(
// We only use a small portion of either of these interfaces.
@inject(IPathUtils) private readonly pathUtils: IPathUtils,
@inject(IFileSystem) private readonly fs: IFileSystem,
) {}
public async parseFile(
filePath?: string,
baseVars?: EnvironmentVariables,
): Promise<EnvironmentVariables | undefined> {
if (!filePath || !(await this.fs.pathExists(filePath))) {
return;
}
const contents = await this.fs.readFile(filePath).catch((ex) => {
traceError('Custom .env is likely not pointing to a valid file', ex);
return undefined;
});
if (!contents) {
return;
}
return parseEnvFile(contents, baseVars);
}
public parseFileSync(filePath?: string, baseVars?: EnvironmentVariables): EnvironmentVariables | undefined {
if (!filePath || !pathExistsSync(filePath)) {
return;
}
let contents: string | undefined;
try {
contents = readFileSync(filePath, { encoding: 'utf8' });
} catch (ex) {
traceError('Custom .env is likely not pointing to a valid file', ex);
}
if (!contents) {
return;
}
return parseEnvFile(contents, baseVars);
}
public mergeVariables(
source: EnvironmentVariables,
target: EnvironmentVariables,
options?: { overwrite?: boolean; mergeAll?: boolean },
) {
if (!target) {
return;
}
const reference = target;
target = normCaseKeys(target);
source = normCaseKeys(source);
const settingsNotToMerge = ['PYTHONPATH', this.pathVariable];
Object.keys(source).forEach((setting) => {
if (!options?.mergeAll && settingsNotToMerge.indexOf(setting) >= 0) {
return;
}
if (target[setting] === undefined || options?.overwrite) {
target[setting] = source[setting];
}
});
restoreKeys(target);
matchTarget(reference, target);
}
public appendPythonPath(vars: EnvironmentVariables, ...pythonPaths: string[]) {
return this.appendPaths(vars, 'PYTHONPATH', ...pythonPaths);
}
public appendPath(vars: EnvironmentVariables, ...paths: string[]) {
return this.appendPaths(vars, this.pathVariable, ...paths);
}
private get pathVariable(): string {
if (!this._pathVariable) {
this._pathVariable = this.pathUtils.getPathVariableName();
}
return normCase(this._pathVariable)!;
}
private appendPaths(vars: EnvironmentVariables, variableName: string, ...pathsToAppend: string[]) {
const reference = vars;
vars = normCaseKeys(vars);
variableName = normCase(variableName);
vars = this._appendPaths(vars, variableName, ...pathsToAppend);
restoreKeys(vars);
matchTarget(reference, vars);
return vars;
}
private _appendPaths(vars: EnvironmentVariables, variableName: string, ...pathsToAppend: string[]) {
const valueToAppend = pathsToAppend
.filter((item) => typeof item === 'string' && item.trim().length > 0)
.map((item) => item.trim())
.join(path.delimiter);
if (valueToAppend.length === 0) {
return vars;
}
const variable = vars ? vars[variableName] : undefined;
if (variable && typeof variable === 'string' && variable.length > 0) {
vars[variableName] = variable + path.delimiter + valueToAppend;
} else {
vars[variableName] = valueToAppend;
}
return vars;
}
}
export function parseEnvFile(lines: string | Buffer, baseVars?: EnvironmentVariables): EnvironmentVariables {
const globalVars = baseVars ? baseVars : {};
const vars: EnvironmentVariables = {};
lines
.toString()
.split('\n')
.forEach((line, _idx) => {
const [name, value] = parseEnvLine(line);
if (name === '') {
return;
}
vars[name] = substituteEnvVars(value, vars, globalVars);
});
return vars;
}
function parseEnvLine(line: string): [string, string] {
// Most of the following is an adaptation of the dotenv code:
// https://github.com/motdotla/dotenv/blob/master/lib/main.js#L32
// We don't use dotenv here because it loses ordering, which is
// significant for substitution.
const match = line.match(/^\s*(_*[a-zA-Z]\w*)\s*=\s*(.*?)?\s*$/);
if (!match) {
return ['', ''];
}
const name = match[1];
let value = match[2];
if (value && value !== '') {
if (value[0] === "'" && value[value.length - 1] === "'") {
value = value.substring(1, value.length - 1);
value = value.replace(/\\n/gm, '\n');
} else if (value[0] === '"' && value[value.length - 1] === '"') {
value = value.substring(1, value.length - 1);
value = value.replace(/\\n/gm, '\n');
}
} else {
value = '';
}
return [name, value];
}
const SUBST_REGEX = /\${([a-zA-Z]\w*)?([^}\w].*)?}/g;
function substituteEnvVars(
value: string,
localVars: EnvironmentVariables,
globalVars: EnvironmentVariables,
missing = '',
): string {
// Substitution here is inspired a little by dotenv-expand:
// https://github.com/motdotla/dotenv-expand/blob/master/lib/main.js
let invalid = false;
let replacement = value;
replacement = replacement.replace(SUBST_REGEX, (match, substName, bogus, offset, orig) => {
if (offset > 0 && orig[offset - 1] === '\\') {
return match;
}
if ((bogus && bogus !== '') || !substName || substName === '') {
invalid = true;
return match;
}
return localVars[substName] || globalVars[substName] || missing;
});
if (!invalid && replacement !== value) {
value = replacement;
sendTelemetryEvent(EventName.ENVFILE_VARIABLE_SUBSTITUTION);
}
return value.replace(/\\\$/g, '$');
}
export function normCaseKeys(env: EnvironmentVariables): EnvironmentVariables {
const normalizedEnv: EnvironmentVariables = {};
Object.keys(env).forEach((key) => {
const normalizedKey = normCase(key);
normalizedEnv[normalizedKey] = env[key];
});
return normalizedEnv;
}
export function restoreKeys(env: EnvironmentVariables) {
const processEnvKeys = Object.keys(process.env);
processEnvKeys.forEach((processEnvKey) => {
const originalKey = normCase(processEnvKey);
if (originalKey !== processEnvKey && env[originalKey] !== undefined) {
env[processEnvKey] = env[originalKey];
delete env[originalKey];
}
});
}
export function matchTarget(reference: EnvironmentVariables, target: EnvironmentVariables): void {
Object.keys(reference).forEach((key) => {
if (target.hasOwnProperty(key)) {
reference[key] = target[key];
} else {
delete reference[key];
}
});
// Add any new keys from target to reference
Object.keys(target).forEach((key) => {
if (!reference.hasOwnProperty(key)) {
reference[key] = target[key];
}
});
}