forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathextension.ts
201 lines (168 loc) · 7.9 KB
/
extension.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
'use strict';
// This line should always be right on top.
if ((Reflect as any).metadata === undefined) {
require('reflect-metadata');
}
// Initialize source maps (this must never be moved up nor further down).
import { initialize } from './sourceMapSupport';
initialize(require('vscode'));
//===============================================
// We start tracking the extension's startup time at this point. The
// locations at which we record various Intervals are marked below in
// the same way as this.
const durations = {} as IStartupDurations;
import { StopWatch } from './common/utils/stopWatch';
// Do not move this line of code (used to measure extension load times).
const stopWatch = new StopWatch();
// Initialize file logging here. This should not depend on too many things.
import { initializeFileLogging, traceError } from './logging';
const logDispose: { dispose: () => void }[] = [];
initializeFileLogging(logDispose);
//===============================================
// loading starts here
import { ProgressLocation, ProgressOptions, window } from 'vscode';
import { buildApi } from './api';
import { IApplicationShell, IWorkspaceService } from './common/application/types';
import { IDisposableRegistry, IExperimentService, IExtensionContext } from './common/types';
import { createDeferred } from './common/utils/async';
import { Common } from './common/utils/localize';
import { activateComponents, activateFeatures } from './extensionActivation';
import { initializeStandard, initializeComponents, initializeGlobals } from './extensionInit';
import { IServiceContainer } from './ioc/types';
import { sendErrorTelemetry, sendStartupTelemetry } from './startupTelemetry';
import { IStartupDurations } from './types';
import { runAfterActivation } from './common/utils/runAfterActivation';
import { IInterpreterService } from './interpreter/contracts';
import { PythonExtension } from './api/types';
import { WorkspaceService } from './common/application/workspace';
import { disposeAll } from './common/utils/resourceLifecycle';
import { ProposedExtensionAPI } from './proposedApiTypes';
import { buildProposedApi } from './proposedApi';
durations.codeLoadingTime = stopWatch.elapsedTime;
//===============================================
// loading ends here
// These persist between activations:
let activatedServiceContainer: IServiceContainer | undefined;
/////////////////////////////
// public functions
export async function activate(context: IExtensionContext): Promise<PythonExtension> {
let api: PythonExtension;
let ready: Promise<void>;
let serviceContainer: IServiceContainer;
try {
const workspaceService = new WorkspaceService();
context.subscriptions.push(
workspaceService.onDidGrantWorkspaceTrust(async () => {
await deactivate();
await activate(context);
}),
);
[api, ready, serviceContainer] = await activateUnsafe(context, stopWatch, durations);
} catch (ex) {
// We want to completely handle the error
// before notifying VS Code.
await handleError(ex as Error, durations);
throw ex; // re-raise
}
// Send the "success" telemetry only if activation did not fail.
// Otherwise Telemetry is send via the error handler.
sendStartupTelemetry(ready, durations, stopWatch, serviceContainer)
// Run in the background.
.ignoreErrors();
return api;
}
export async function deactivate(): Promise<void> {
// Make sure to shutdown anybody who needs it.
if (activatedServiceContainer) {
const disposables = activatedServiceContainer.get<IDisposableRegistry>(IDisposableRegistry);
await disposeAll(disposables);
// Remove everything that is already disposed.
while (disposables.pop());
}
}
/////////////////////////////
// activation helpers
async function activateUnsafe(
context: IExtensionContext,
startupStopWatch: StopWatch,
startupDurations: IStartupDurations,
): Promise<[PythonExtension & ProposedExtensionAPI, Promise<void>, IServiceContainer]> {
// Add anything that we got from initializing logs to dispose.
context.subscriptions.push(...logDispose);
const activationDeferred = createDeferred<void>();
displayProgress(activationDeferred.promise);
startupDurations.startActivateTime = startupStopWatch.elapsedTime;
const activationStopWatch = new StopWatch();
//===============================================
// activation starts here
// First we initialize.
const ext = initializeGlobals(context);
activatedServiceContainer = ext.legacyIOC.serviceContainer;
// Note standard utils especially experiment and platform code are fundamental to the extension
// and should be available before we activate anything else.Hence register them first.
initializeStandard(ext);
// We need to activate experiments before initializing components as objects are created or not created based on experiments.
const experimentService = activatedServiceContainer.get<IExperimentService>(IExperimentService);
// This guarantees that all experiment information has loaded & all telemetry will contain experiment info.
await experimentService.activate();
const components = await initializeComponents(ext);
// Then we finish activating.
const componentsActivated = await activateComponents(ext, components, activationStopWatch);
activateFeatures(ext, components);
const nonBlocking = componentsActivated.map((r) => r.fullyReady);
const activationPromise = (async () => {
await Promise.all(nonBlocking);
})();
//===============================================
// activation ends here
startupDurations.totalActivateTime = startupStopWatch.elapsedTime - startupDurations.startActivateTime;
activationDeferred.resolve();
setTimeout(async () => {
if (activatedServiceContainer) {
const workspaceService = activatedServiceContainer.get<IWorkspaceService>(IWorkspaceService);
if (workspaceService.isTrusted) {
const interpreterManager = activatedServiceContainer.get<IInterpreterService>(IInterpreterService);
const workspaces = workspaceService.workspaceFolders ?? [];
await interpreterManager
.refresh(workspaces.length > 0 ? workspaces[0].uri : undefined)
.catch((ex) => traceError('Python Extension: interpreterManager.refresh', ex));
}
}
runAfterActivation();
});
const api = buildApi(
activationPromise,
ext.legacyIOC.serviceManager,
ext.legacyIOC.serviceContainer,
components.pythonEnvs,
);
const proposedApi = buildProposedApi(components.pythonEnvs, ext.legacyIOC.serviceContainer);
return [{ ...api, ...proposedApi }, activationPromise, ext.legacyIOC.serviceContainer];
}
function displayProgress(promise: Promise<any>) {
const progressOptions: ProgressOptions = { location: ProgressLocation.Window, title: Common.loadingExtension };
window.withProgress(progressOptions, () => promise);
}
/////////////////////////////
// error handling
async function handleError(ex: Error, startupDurations: IStartupDurations) {
notifyUser(
"Extension activation failed, run the 'Developer: Toggle Developer Tools' command for more information.",
);
traceError('extension activation failed', ex);
await sendErrorTelemetry(ex, startupDurations, activatedServiceContainer);
}
interface IAppShell {
showErrorMessage(string: string): Promise<void>;
}
function notifyUser(msg: string) {
try {
let appShell: IAppShell = (window as any) as IAppShell;
if (activatedServiceContainer) {
appShell = (activatedServiceContainer.get<IApplicationShell>(IApplicationShell) as any) as IAppShell;
}
appShell.showErrorMessage(msg).ignoreErrors();
} catch (ex) {
traceError('Failed to Notify User', ex);
}
}