forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathindex.ts
229 lines (211 loc) · 9.02 KB
/
index.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as vscode from 'vscode';
import { Uri } from 'vscode';
import { cloneDeep } from 'lodash';
import { getGlobalStorage, IPersistentStorage } from '../common/persistentState';
import { getOSType, OSType } from '../common/utils/platform';
import { ActivationResult, ExtensionState } from '../components';
import { PythonEnvInfo } from './base/info';
import { BasicEnvInfo, IDiscoveryAPI, ILocator } from './base/locator';
import { PythonEnvsReducer } from './base/locators/composite/envsReducer';
import { PythonEnvsResolver } from './base/locators/composite/envsResolver';
import { WindowsPathEnvVarLocator } from './base/locators/lowLevel/windowsKnownPathsLocator';
import { WorkspaceVirtualEnvironmentLocator } from './base/locators/lowLevel/workspaceVirtualEnvLocator';
import {
initializeExternalDependencies as initializeLegacyExternalDependencies,
normCasePath,
} from './common/externalDependencies';
import { ExtensionLocators, WatchRootsArgs, WorkspaceLocators } from './base/locators/wrappers';
import { CustomVirtualEnvironmentLocator } from './base/locators/lowLevel/customVirtualEnvLocator';
import { CondaEnvironmentLocator } from './base/locators/lowLevel/condaLocator';
import { GlobalVirtualEnvironmentLocator } from './base/locators/lowLevel/globalVirtualEnvronmentLocator';
import { PosixKnownPathsLocator } from './base/locators/lowLevel/posixKnownPathsLocator';
import { PyenvLocator } from './base/locators/lowLevel/pyenvLocator';
import { WindowsRegistryLocator } from './base/locators/lowLevel/windowsRegistryLocator';
import { MicrosoftStoreLocator } from './base/locators/lowLevel/microsoftStoreLocator';
import { getEnvironmentInfoService } from './base/info/environmentInfoService';
import { registerNewDiscoveryForIOC } from './legacyIOC';
import { PoetryLocator } from './base/locators/lowLevel/poetryLocator';
import { createPythonEnvironments } from './api';
import {
createCollectionCache as createCache,
IEnvsCollectionCache,
} from './base/locators/composite/envsCollectionCache';
import { EnvsCollectionService } from './base/locators/composite/envsCollectionService';
import { IDisposable } from '../common/types';
import { traceError } from '../logging';
import { ActiveStateLocator } from './base/locators/lowLevel/activeStateLocator';
/**
* Set up the Python environments component (during extension activation).'
*/
export async function initialize(ext: ExtensionState): Promise<IDiscoveryAPI> {
// Set up the legacy IOC container before api is created.
initializeLegacyExternalDependencies(ext.legacyIOC.serviceContainer);
const api = await createPythonEnvironments(() => createLocator(ext));
registerNewDiscoveryForIOC(
// These are what get wrapped in the legacy adapter.
ext.legacyIOC.serviceManager,
api,
);
return api;
}
/**
* Make use of the component (e.g. register with VS Code).
*/
export async function activate(api: IDiscoveryAPI, ext: ExtensionState): Promise<ActivationResult> {
/**
* Force an initial background refresh of the environments.
*
* Note API is ready to be queried only after a refresh has been triggered, and extension activation is
* blocked on API being ready. So if discovery was never triggered for a scope, we need to block
* extension activation on the "refresh trigger".
*/
const folders = vscode.workspace.workspaceFolders;
// Trigger discovery if environment cache is empty.
const wasTriggered = getGlobalStorage<PythonEnvInfo[]>(ext.context, 'PYTHON_ENV_INFO_CACHE', []).get().length > 0;
if (!wasTriggered) {
api.triggerRefresh().ignoreErrors();
folders?.forEach(async (folder) => {
const wasTriggeredForFolder = getGlobalStorage<boolean>(
ext.context,
`PYTHON_WAS_DISCOVERY_TRIGGERED_${normCasePath(folder.uri.fsPath)}`,
false,
);
await wasTriggeredForFolder.set(true);
});
} else {
// Figure out which workspace folders need to be activated if any.
folders?.forEach(async (folder) => {
const wasTriggeredForFolder = getGlobalStorage<boolean>(
ext.context,
`PYTHON_WAS_DISCOVERY_TRIGGERED_${normCasePath(folder.uri.fsPath)}`,
false,
);
if (!wasTriggeredForFolder.get()) {
api.triggerRefresh({
searchLocations: { roots: [folder.uri], doNotIncludeNonRooted: true },
}).ignoreErrors();
await wasTriggeredForFolder.set(true);
}
});
}
return {
fullyReady: Promise.resolve(),
};
}
/**
* Get the locator to use in the component.
*/
async function createLocator(
ext: ExtensionState,
// This is shared.
): Promise<IDiscoveryAPI> {
// Create the low-level locators.
const locators: ILocator<BasicEnvInfo> = new ExtensionLocators<BasicEnvInfo>(
// Here we pull the locators together.
createNonWorkspaceLocators(ext),
createWorkspaceLocator(ext),
);
// Create the env info service used by ResolvingLocator and CachingLocator.
const envInfoService = getEnvironmentInfoService(ext.disposables);
// Build the stack of composite locators.
const reducer = new PythonEnvsReducer(locators);
const resolvingLocator = new PythonEnvsResolver(
reducer,
// These are shared.
envInfoService,
);
const caching = new EnvsCollectionService(
await createCollectionCache(ext),
// This is shared.
resolvingLocator,
);
return caching;
}
function createNonWorkspaceLocators(ext: ExtensionState): ILocator<BasicEnvInfo>[] {
const locators: (ILocator<BasicEnvInfo> & Partial<IDisposable>)[] = [];
locators.push(
// OS-independent locators go here.
new PyenvLocator(),
new CondaEnvironmentLocator(),
new ActiveStateLocator(),
new GlobalVirtualEnvironmentLocator(),
new CustomVirtualEnvironmentLocator(),
);
if (getOSType() === OSType.Windows) {
locators.push(
// Windows specific locators go here.
new WindowsRegistryLocator(),
new MicrosoftStoreLocator(),
new WindowsPathEnvVarLocator(),
);
} else {
locators.push(
// Linux/Mac locators go here.
new PosixKnownPathsLocator(),
);
}
const disposables = locators.filter((d) => d.dispose !== undefined) as IDisposable[];
ext.disposables.push(...disposables);
return locators;
}
function watchRoots(args: WatchRootsArgs): IDisposable {
const { initRoot, addRoot, removeRoot } = args;
const folders = vscode.workspace.workspaceFolders;
if (folders) {
folders.map((f) => f.uri).forEach(initRoot);
}
return vscode.workspace.onDidChangeWorkspaceFolders((event) => {
for (const root of event.removed) {
removeRoot(root.uri);
}
for (const root of event.added) {
addRoot(root.uri);
}
});
}
function createWorkspaceLocator(ext: ExtensionState): WorkspaceLocators {
const locators = new WorkspaceLocators(watchRoots, [
(root: vscode.Uri) => [new WorkspaceVirtualEnvironmentLocator(root.fsPath), new PoetryLocator(root.fsPath)],
// Add an ILocator factory func here for each kind of workspace-rooted locator.
]);
ext.disposables.push(locators);
return locators;
}
function getFromStorage(storage: IPersistentStorage<PythonEnvInfo[]>): PythonEnvInfo[] {
return storage.get().map((e) => {
if (e.searchLocation) {
if (typeof e.searchLocation === 'string') {
e.searchLocation = Uri.parse(e.searchLocation);
} else if ('scheme' in e.searchLocation && 'path' in e.searchLocation) {
e.searchLocation = Uri.parse(`${e.searchLocation.scheme}://${e.searchLocation.path}`);
} else {
traceError('Unexpected search location', JSON.stringify(e.searchLocation));
}
}
return e;
});
}
function putIntoStorage(storage: IPersistentStorage<PythonEnvInfo[]>, envs: PythonEnvInfo[]): Promise<void> {
storage.set(
// We have to `cloneDeep()` here so that we don't overwrite the original `PythonEnvInfo` objects.
cloneDeep(envs).map((e) => {
if (e.searchLocation) {
// Make TS believe it is string. This is temporary. We need to serialize this in
// a custom way.
e.searchLocation = (e.searchLocation.toString() as unknown) as Uri;
}
return e;
}),
);
return Promise.resolve();
}
async function createCollectionCache(ext: ExtensionState): Promise<IEnvsCollectionCache> {
const storage = getGlobalStorage<PythonEnvInfo[]>(ext.context, 'PYTHON_ENV_INFO_CACHE', []);
const cache = await createCache({
get: () => getFromStorage(storage),
store: async (e) => putIntoStorage(storage, e),
});
return cache;
}