-
Notifications
You must be signed in to change notification settings - Fork 17
/
extension.ts
287 lines (236 loc) · 10.8 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
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
'use strict';
import { realpathSync } from 'fs';
import * as vscode from 'vscode';
import * as which from 'which';
import { LanguageClientOptions, ErrorAction, CloseAction, RevealOutputChannelOn } from 'vscode-languageclient';
import { LanguageClient, ServerOptions } from 'vscode-languageclient/lib/node/main';
import { Trace } from 'vscode-jsonrpc/lib/node/main';
import * as dotnet from './dotnet';
import { handleBusyNotifications } from './notifications';
import { registerCommands } from './commands';
import { registerInternalCommands } from './internal-commands';
import { Settings, upgradeConfigurationSchema, readVSCodeSettings } from './settings';
let configuration: Settings;
let languageClient: LanguageClient;
let statusBarItem: vscode.StatusBarItem;
let outputChannel: vscode.OutputChannel;
const featureFlags = new Set<string>();
const languageServerEnvironment = Object.assign({}, process.env);
const projectDocumentSelector: vscode.DocumentSelector = [
{ language: 'xml', pattern: '**/*.*proj' },
{ language: 'xml', pattern: '**/*.props' },
{ language: 'xml', pattern: '**/*.targets' },
{ language: 'xml', pattern: '**/*.tasks' },
{ language: 'msbuild', pattern: '**/*.*' }
];
/**
* Called when the extension is activated.
*
* @param context The extension context.
*/
export async function activate(context: vscode.ExtensionContext): Promise<void> {
outputChannel = vscode.window.createOutputChannel('MSBuild Project Tools');
const progressOptions: vscode.ProgressOptions = {
location: vscode.ProgressLocation.Window
};
await vscode.window.withProgress(progressOptions, async progress => {
progress.report({
message: 'Initialising MSBuild project tools...'
});
await loadConfiguration();
const hostRuntimeDiscoveryResult = await dotnet.discoverUserRuntime();
if (!hostRuntimeDiscoveryResult.success) {
const failureResult = hostRuntimeDiscoveryResult as { failure: dotnet.RuntimeDiscoveryFailure };
switch (failureResult.failure) {
case dotnet.RuntimeDiscoveryFailure.DotnetNotFoundInPath:
outputChannel.appendLine('"dotnet" command was not found in the PATH. Please make sure "dotnet" is available from the PATH and reload extension since it is required for it to work');
vscode.window.showErrorMessage('"dotnet" was not found in the PATH (see the output window for details).');
break;
case dotnet.RuntimeDiscoveryFailure.ErrorWhileGettingRuntimesList:
outputChannel.appendLine('Error occured while trying to execute "dotnet --list-runtimes" command');
vscode.window.showErrorMessage('Error occured while trying to invoke "dotnet" command (see the output window for details).');
break;
}
return;
}
await createLanguageClient(context, hostRuntimeDiscoveryResult);
context.subscriptions.push(
handleExpressionAutoClose()
);
registerCommands(context, statusBarItem);
registerInternalCommands(context);
});
context.subscriptions.push(
vscode.workspace.onDidChangeConfiguration(async args => {
await loadConfiguration();
if (languageClient) {
const trace = configuration.logging.trace ? Trace.Verbose : Trace.Off;
await languageClient.setTrace(trace);
}
})
);
}
/**
* Called when the extension is deactivated.
*/
export async function deactivate(): Promise<void> {
await languageClient.stop();
}
/**
* Load extension configuration from the workspace.
*/
async function loadConfiguration(): Promise<void> {
const workspaceConfiguration = vscode.workspace.getConfiguration();
configuration = workspaceConfiguration.get('msbuildProjectTools');
await upgradeConfigurationSchema(configuration);
configuration = readVSCodeSettings(configuration);
featureFlags.clear();
if (configuration.experimentalFeatures) {
configuration.experimentalFeatures.forEach(
featureFlag => featureFlags.add(featureFlag)
);
}
}
/**
* Create the MSBuild language client.
*
* @param context The current extension context.
* @returns A promise that resolves to the language client.
*/
async function createLanguageClient(context: vscode.ExtensionContext, dotnetOnHost: { dotnetExecutablePath: string, canBeUsedForRunningLanguageServer: boolean }): Promise<void> {
statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 50);
context.subscriptions.push(statusBarItem);
statusBarItem.text = '$(check) MSBuild Project';
statusBarItem.tooltip = 'MSBuild Project Tools';
statusBarItem.hide();
outputChannel.appendLine('Starting MSBuild language service...');
const clientOptions: LanguageClientOptions = {
synchronize: {
configurationSection: 'msbuildProjectTools'
},
diagnosticCollectionName: 'MSBuild Project',
errorHandler: {
error: (error, message, count) => {
if (count > 2) // Don't be annoying
return { action: ErrorAction.Shutdown };
console.log(message);
console.log(error);
if (message)
outputChannel.appendLine(`The MSBuild language server encountered an unexpected error: ${message}\n\n${error}`);
else
outputChannel.appendLine(`The MSBuild language server encountered an unexpected error.\n\n${error}`);
return { action: ErrorAction.Continue };
},
closed: () => { return { action: CloseAction.DoNotRestart } }
},
initializationFailedHandler(error: Error) : boolean {
console.log(error);
outputChannel.appendLine(`Failed to initialise the MSBuild language server.\n\n${error}`);
vscode.window.showErrorMessage(`Failed to initialise MSBuild language server.\n\n${error}`);
return false; // Don't attempt to restart the language server.
},
revealOutputChannelOn: RevealOutputChannelOn.Never
};
const seqLoggingSettings = configuration.logging.seq;
if (seqLoggingSettings && seqLoggingSettings.url) {
languageServerEnvironment['MSBUILD_PROJECT_TOOLS_SEQ_URL'] = seqLoggingSettings.url;
languageServerEnvironment['MSBUILD_PROJECT_TOOLS_SEQ_API_KEY'] = seqLoggingSettings.apiKey;
}
if (configuration.logging.file) {
languageServerEnvironment['MSBUILD_PROJECT_TOOLS_LOG_FILE'] = configuration.logging.file;
}
if (configuration.logging.level === 'Verbose') {
languageServerEnvironment['MSBUILD_PROJECT_TOOLS_VERBOSE_LOGGING'] = '1';
}
const serverAssembly = context.asAbsolutePath('language-server/MSBuildProjectTools.LanguageServer.Host.dll');
let dotnetForLanguageServer = dotnetOnHost.dotnetExecutablePath;
if (!dotnetOnHost.canBeUsedForRunningLanguageServer) {
const isolatedDotnet = await dotnet.acquireIsolatedRuntime(context.extension.id);
if (isolatedDotnet === null) {
const baseErrorMessage = 'Cannot enable the MSBuild language service: unable to acquire isolated .NET runtime';
outputChannel.appendLine(baseErrorMessage + ". See '.NET Runtime' channel for more info");
await vscode.window.showErrorMessage(baseErrorMessage);
return;
}
await dotnet.acquireDependencies(isolatedDotnet, serverAssembly);
dotnetForLanguageServer = isolatedDotnet;
outputChannel.appendLine("Using isolated .NET runtime");
} else {
outputChannel.appendLine("Using .NET runtime from the host");
}
languageServerEnvironment['DOTNET_HOST_PATH'] = realpathSync(dotnetOnHost.dotnetExecutablePath);
const serverOptions: ServerOptions = {
command: dotnetForLanguageServer,
args: [serverAssembly],
options: {
env: languageServerEnvironment
}
};
languageClient = new LanguageClient('MSBuild Language Service', serverOptions, clientOptions);
const trace = configuration.logging.trace ? Trace.Verbose : Trace.Off;
await languageClient.setTrace(trace);
try {
await languageClient.start();
handleBusyNotifications(languageClient, statusBarItem);
outputChannel.appendLine('MSBuild language service is running.');
}
catch (startFailed) {
outputChannel.appendLine(`Failed to start MSBuild language service.\n\n${startFailed}`);
return;
}
}
/**
* Handle document-change events to automatically insert a closing parenthesis for common MSBuild expressions.
*/
function handleExpressionAutoClose(): vscode.Disposable {
return vscode.workspace.onDidChangeTextDocument(async args => {
if (!vscode.languages.match(projectDocumentSelector, args.document))
return;
if (!featureFlags.has('expressions'))
return;
if (args.contentChanges.length !== 1)
return; // Completion doesn't make sense with multiple cursors.
const contentChange = args.contentChanges[0];
if (isOriginPosition(contentChange.range.start))
return; // We're at the start of the document; no previous character to check.
if (contentChange.text === '(') {
// Select the previous character and the one they just typed.
const range = contentChange.range.with(
contentChange.range.start.translate(0, -1),
contentChange.range.end.translate(0, 1)
);
const openExpression = args.document.getText(range);
switch (openExpression) {
case '$(': // Eval open
case '@(': // Item group open
case '%(': // Item metadata open
{
break;
}
default:
{
return;
}
}
// Replace open expression with a closed one.
const closedExpression = openExpression + ')';
await vscode.window.activeTextEditor.edit(
edit => edit.replace(range, closedExpression)
);
// Move between the parentheses and trigger completion.
await vscode.commands.executeCommand('msbuildProjectTools.internal.moveAndSuggest',
'left', // moveTo
'character', // moveBy
1 // moveCount
);
}
});
}
/**
* Determine whether the specified {@link vscode.Position} represents the origin position.
*
* @param position The {@link vscode.Position} to examine.
*/
function isOriginPosition(position: vscode.Position): boolean {
return position.line === 0 && position.character === 0;
}