forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.ts
More file actions
439 lines (393 loc) · 13.8 KB
/
env.ts
File metadata and controls
439 lines (393 loc) · 13.8 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { cloneDeep } from 'lodash';
import * as path from 'path';
import { normalizeFilename } from '../../../common/utils/filesystem';
import { Architecture } from '../../../common/utils/platform';
import { arePathsSame } from '../../common/externalDependencies';
import { parseVersionFromExecutable } from './executable';
import {
areEqualVersions,
areEquivalentVersions,
isVersionEmpty,
} from './pythonVersion';
import {
FileInfo,
PythonDistroInfo,
PythonEnvInfo,
PythonEnvKind,
PythonReleaseLevel,
PythonVersion,
} from '.';
/**
* Create a new info object with all values empty.
*
* @param init - if provided, these values are applied to the new object
*/
export function buildEnvInfo(init?: {
kind?: PythonEnvKind;
executable?: string;
location?: string;
version?: PythonVersion;
org?: string;
arch?: Architecture;
fileInfo?: {ctime:number, mtime:number}
}): PythonEnvInfo {
const env = {
name: '',
location: '',
kind: PythonEnvKind.Unknown,
executable: {
filename: '',
sysPrefix: '',
ctime: init?.fileInfo?.ctime ?? -1,
mtime: init?.fileInfo?.mtime ?? -1,
},
searchLocation: undefined,
defaultDisplayName: undefined,
version: {
major: -1,
minor: -1,
micro: -1,
release: {
level: PythonReleaseLevel.Final,
serial: 0,
},
},
arch: init?.arch ?? Architecture.Unknown,
distro: {
org: init?.org ?? '',
},
};
if (init !== undefined) {
updateEnv(env, init);
}
return env;
}
/**
* Return a deep copy of the given env info.
*
* @param updates - if provided, these values are applied to the copy
*/
export function copyEnvInfo(
env: PythonEnvInfo,
updates?: {
kind?: PythonEnvKind,
},
): PythonEnvInfo {
// We don't care whether or not extra/hidden properties
// get preserved, so we do the easy thing here.
const copied = cloneDeep(env);
if (updates !== undefined) {
updateEnv(copied, updates);
}
return copied;
}
function updateEnv(env: PythonEnvInfo, updates: {
kind?: PythonEnvKind;
executable?: string;
location?: string;
version?: PythonVersion;
}): void {
if (updates.kind !== undefined) {
env.kind = updates.kind;
}
if (updates.executable !== undefined) {
env.executable.filename = updates.executable;
}
if (updates.location !== undefined) {
env.location = updates.location;
}
if (updates.version !== undefined) {
env.version = updates.version;
}
}
/**
* Determine the corresponding Python executable filename, if any.
*/
export function getEnvExecutable(env: string | Partial<PythonEnvInfo>): string {
const executable = typeof env === 'string'
? env
: env.executable?.filename || '';
if (executable === '') {
return '';
}
return normalizeFilename(executable);
}
/**
* For the given data, build a normalized partial info object.
*
* If insufficient data is provided to generate a minimal object, such
* that it is not identifiable, then `undefined` is returned.
*/
export function getMinimalPartialInfo(env: string | Partial<PythonEnvInfo>): Partial<PythonEnvInfo> | undefined {
if (typeof env === 'string') {
if (env === '') {
return undefined;
}
return {
executable: {
filename: env,
sysPrefix: '',
ctime: -1,
mtime: -1,
},
};
}
if (env.executable === undefined) {
return undefined;
}
if (env.executable.filename === '') {
return undefined;
}
return env;
}
/**
* Build an object with at least the minimal info about a Python env.
*
* This is meant to be as fast an operation as possible.
*
* Note that passing `PythonEnvKind.Unknown` for `kind` is okay,
* though not ideal.
*/
export function getFastEnvInfo(kind: PythonEnvKind, executable: string): PythonEnvInfo {
const env = buildEnvInfo({ kind, executable });
try {
env.version = parseVersionFromExecutable(env.executable.filename);
} catch {
// It didn't have version info in it.
// We could probably walk up the directory tree trying dirnames
// too, but we'll skip that for now. Windows gives us a few
// other options which we will also skip for now.
}
return env;
}
/**
* Build a new object with at much info as possible about a Python env.
*
* This does as much as possible without distro-specific or other
* special knowledge.
*
* @param minimal - the minimal info (e.g. from `getFastEnvInfo()`)
* on which to base the "full" object; this may include
* extra info beyond the "minimal", but at the very
* least it will include the minimum info necessary
* to be useful
*/
export async function getMaxDerivedEnvInfo(minimal: PythonEnvInfo): Promise<PythonEnvInfo> {
const env = cloneDeep(minimal);
// For now we do not worry about adding anything more to env.executable.
// `ctime` and `mtime` would require a stat call, `sysPrefix` would
// require guessing.
// For now we do not fill anything in for `name` or `location`. If
// we had `env.executable.sysPrefix` we could set a meaningful
// `location`, but we don't.
if (isVersionEmpty(env.version)) {
try {
env.version = parseVersionFromExecutable(env.executable.filename);
} catch {
// It didn't have version info in it.
// We could probably walk up the directory tree trying dirnames
// too, but we'll skip that for now. Windows gives us a few
// other options which we will also skip for now.
}
}
// Note that we do not set `env.arch` to the host's native
// architecture. Nearly all Python builds will match the host
// architecture, with the notable exception being older PSF builds
// for Windows, There is enough uncertainty that we play it safe
// by not setting `env.arch` here.
// We could probably make a decent guess at the distro, but that
// is best left to distro-specific locators.
return env;
}
/**
* Create a function that decides if the given "query" matches some env info.
*
* The returned function is compatible with `Array.filter()`.
*/
export function getEnvMatcher(
query: string | Partial<PythonEnvInfo>,
): (env: PythonEnvInfo) => boolean {
const executable = getEnvExecutable(query);
if (executable === '') {
// We could throw an exception error, but skipping it is fine.
return () => false;
}
function matchEnv(candidate: PythonEnvInfo): boolean {
return arePathsSame(executable, candidate.executable.filename);
}
return matchEnv;
}
/**
* Decide if the two sets of executables for the given envs are the same.
*/
export function haveSameExecutables(
envs1: PythonEnvInfo[],
envs2: PythonEnvInfo[],
): boolean {
if (envs1.length !== envs2.length) {
return false;
}
const executables1 = envs1.map(getEnvExecutable);
const executables2 = envs2.map(getEnvExecutable);
if (!executables2.every((e) => executables1.includes(e))) {
return false;
}
return true;
}
/**
* Checks if two environments are same.
* @param {string | PythonEnvInfo} left: environment to compare.
* @param {string | PythonEnvInfo} right: environment to compare.
* @param {boolean} allowPartialMatch: allow partial matches of properties when comparing.
*
* Remarks: The current comparison assumes that if the path to the executables are the same
* then it is the same environment. Additionally, if the paths are not same but executables
* are in the same directory and the version of python is the same than we can assume it
* to be same environment. This later case is needed for comparing windows store python,
* where multiple versions of python executables are all put in the same directory.
*/
export function areSameEnv(
left: string | Partial<PythonEnvInfo>,
right: string | Partial<PythonEnvInfo>,
allowPartialMatch = true,
): boolean | undefined {
const leftInfo = getMinimalPartialInfo(left);
const rightInfo = getMinimalPartialInfo(right);
if (leftInfo === undefined || rightInfo === undefined) {
return undefined;
}
const leftFilename = leftInfo.executable!.filename;
const rightFilename = rightInfo.executable!.filename;
// For now we assume that matching executable means they are the same.
if (arePathsSame(leftFilename, rightFilename)) {
return true;
}
if (arePathsSame(path.dirname(leftFilename), path.dirname(rightFilename))) {
const leftVersion = typeof left === 'string' ? undefined : left.version;
const rightVersion = typeof right === 'string' ? undefined : right.version;
if (leftVersion && rightVersion) {
if (
areEqualVersions(leftVersion, rightVersion)
|| (allowPartialMatch && areEquivalentVersions(leftVersion, rightVersion))
) {
return true;
}
}
}
return false;
}
/**
* Returns a heuristic value on how much information is available in the given version object.
* @param {PythonVersion} version version object to generate heuristic from.
* @returns A heuristic value indicating the amount of info available in the object
* weighted by most important to least important fields.
* Wn > Wn-1 + Wn-2 + ... W0
*/
function getPythonVersionSpecificity(version: PythonVersion): number {
let infoLevel = 0;
if (version.major > 0) {
infoLevel += 20; // W4
}
if (version.minor >= 0) {
infoLevel += 10; // W3
}
if (version.micro >= 0) {
infoLevel += 5; // W2
}
if (version.release?.level) {
infoLevel += 3; // W1
}
if (version.release?.serial || version.sysVersion) {
infoLevel += 1; // W0
}
return infoLevel;
}
/**
* Compares two python versions, based on the amount of data each object has. If versionA has
* less information then the returned value is negative. If it is same then 0. If versionA has
* more information then positive.
*/
export function comparePythonVersionSpecificity(versionA: PythonVersion, versionB: PythonVersion): number {
return Math.sign(getPythonVersionSpecificity(versionA) - getPythonVersionSpecificity(versionB));
}
/**
* Returns a heuristic value on how much information is available in the given executable object.
* @param {FileInfo} executable executable object to generate heuristic from.
* @returns A heuristic value indicating the amount of info available in the object
* weighted by most important to least important fields.
* Wn > Wn-1 + Wn-2 + ... W0
*/
function getFileInfoHeuristic(file: FileInfo): number {
let infoLevel = 0;
if (file.filename.length > 0) {
infoLevel += 5; // W2
}
if (file.mtime) {
infoLevel += 2; // W1
}
if (file.ctime) {
infoLevel += 1; // W0
}
return infoLevel;
}
/**
* Returns a heuristic value on how much information is available in the given distro object.
* @param {PythonDistroInfo} distro distro object to generate heuristic from.
* @returns A heuristic value indicating the amount of info available in the object
* weighted by most important to least important fields.
* Wn > Wn-1 + Wn-2 + ... W0
*/
function getDistroInfoHeuristic(distro: PythonDistroInfo): number {
let infoLevel = 0;
if (distro.org.length > 0) {
infoLevel += 20; // W3
}
if (distro.defaultDisplayName) {
infoLevel += 10; // W2
}
if (distro.binDir) {
infoLevel += 5; // W1
}
if (distro.version) {
infoLevel += 2;
}
return infoLevel;
}
/**
* Merges properties of the `target` environment and `other` environment and returns the merged environment.
* if the value in the `target` environment is not defined or has less information. This does not mutate
* the `target` instead it returns a new object that contains the merged results.
* @param {PythonEnvInfo} target : Properties of this object are favored.
* @param {PythonEnvInfo} other : Properties of this object are used to fill the gaps in the merged result.
*/
export function mergeEnvironments(target: PythonEnvInfo, other: PythonEnvInfo): PythonEnvInfo {
const merged = cloneDeep(target);
const version = cloneDeep(
getPythonVersionSpecificity(target.version) > getPythonVersionSpecificity(other.version)
? target.version
: other.version,
);
const executable = cloneDeep(
getFileInfoHeuristic(target.executable) > getFileInfoHeuristic(other.executable)
? target.executable
: other.executable,
);
executable.sysPrefix = target.executable.sysPrefix ?? other.executable.sysPrefix;
const distro = cloneDeep(
getDistroInfoHeuristic(target.distro) > getDistroInfoHeuristic(other.distro) ? target.distro : other.distro,
);
merged.arch = merged.arch === Architecture.Unknown ? other.arch : target.arch;
merged.defaultDisplayName = merged.defaultDisplayName ?? other.defaultDisplayName;
merged.distro = distro;
merged.executable = executable;
// No need to check this just use preferred kind. Since the first thing we do is figure out the
// preferred env based on kind.
merged.kind = target.kind;
merged.location = merged.location.length ? merged.location : other.location;
merged.name = merged.name.length ? merged.name : other.name;
merged.searchLocation = merged.searchLocation ?? other.searchLocation;
merged.version = version;
return merged;
}