-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
extension.ts
347 lines (298 loc) · 10.6 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
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
/* -------------------------------------------------------------------------
* Original work Copyright (c) Microsoft Corporation. All rights reserved.
* Original work licensed under the MIT License.
* See ThirdPartyNotices.txt in the project root for license information.
* All modifications Copyright (c) Open Law Library. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http: // www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ----------------------------------------------------------------------- */
"use strict";
import * as net from "net";
import * as path from "path";
import * as vscode from "vscode";
import * as semver from "semver";
import { PythonExtension } from "@vscode/python-extension";
import { LanguageClient, LanguageClientOptions, ServerOptions, State } from "vscode-languageclient/node";
const MIN_PYTHON = semver.parse("3.7.9")
// Some other nice to haves.
// TODO: Check selected env satisfies pygls' requirements - if not offer to run the select env command.
// TODO: Start a debug session for the currently configured server.
// TODO: TCP Transport
// TODO: WS Transport
// TODO: Web Extension support (requires WASM-WASI!)
let client: LanguageClient;
let clientStarting = false
let python: PythonExtension;
let logger: vscode.LogOutputChannel
/**
* This is the main entry point.
* Called when vscode first activates the extension
*/
export async function activate(context: vscode.ExtensionContext) {
logger = vscode.window.createOutputChannel('pygls', { log: true })
logger.info("Extension activated.")
await getPythonExtension();
if (!python) {
return
}
// Restart language server command
context.subscriptions.push(
vscode.commands.registerCommand("pygls.server.restart", async () => {
logger.info('restarting server...')
await startLangServer()
})
)
// Execute command... command
context.subscriptions.push(
vscode.commands.registerCommand("pygls.server.executeCommand", async () => {
await executeServerCommand()
})
)
// Restart the language server if the user switches Python envs...
context.subscriptions.push(
python.environments.onDidChangeActiveEnvironmentPath(async () => {
logger.info('python env modified, restarting server...')
await startLangServer()
})
)
// ... or if they change a relevant config option
context.subscriptions.push(
vscode.workspace.onDidChangeConfiguration(async (event) => {
if (event.affectsConfiguration("pygls.server") || event.affectsConfiguration("pygls.client")) {
logger.info('config modified, restarting server...')
await startLangServer()
}
})
)
// Start the language server once the user opens the first text document...
context.subscriptions.push(
vscode.workspace.onDidOpenTextDocument(
async () => {
if (!client) {
await startLangServer()
}
}
)
)
// ...or notebook.
context.subscriptions.push(
vscode.workspace.onDidOpenNotebookDocument(
async () => {
if (!client) {
await startLangServer()
}
}
)
)
// Restart the server if the user modifies it.
context.subscriptions.push(
vscode.workspace.onDidSaveTextDocument(async (document: vscode.TextDocument) => {
const expectedUri = vscode.Uri.file(path.join(getCwd(), getServerPath()))
if (expectedUri.toString() === document.uri.toString()) {
logger.info('server modified, restarting...')
await startLangServer()
}
})
)
}
export function deactivate(): Thenable<void> {
return stopLangServer()
}
/**
* Start (or restart) the language server.
*
* @param command The executable to run
* @param args Arguments to pass to the executable
* @param cwd The working directory in which to run the executable
* @returns
*/
async function startLangServer() {
// Don't interfere if we are already in the process of launching the server.
if (clientStarting) {
return
}
clientStarting = true
if (client) {
await stopLangServer()
}
const cwd = getCwd()
const serverPath = getServerPath()
logger.info(`cwd: '${cwd}'`)
logger.info(`server: '${serverPath}'`)
const resource = vscode.Uri.joinPath(vscode.Uri.file(cwd), serverPath)
const pythonPath = await getPythonPath(resource)
if (!pythonPath) {
clientStarting = false
return
}
const serverOptions: ServerOptions = {
command: pythonPath,
args: [serverPath],
options: { cwd },
};
client = new LanguageClient('pygls', serverOptions, getClientOptions());
try {
await client.start()
clientStarting = false
} catch (err) {
clientStarting = false
logger.error(`Unable to start server: ${err}`)
}
}
async function stopLangServer(): Promise<void> {
if (!client) {
return
}
if (client.state === State.Running) {
await client.stop()
}
client.dispose()
client = undefined
}
function getClientOptions(): LanguageClientOptions {
const config = vscode.workspace.getConfiguration('pygls.client')
const options = {
documentSelector: config.get<any>('documentSelector'),
outputChannel: logger,
connectionOptions: {
maxRestartCount: 0 // don't restart on server failure.
},
};
logger.info(`client options: ${JSON.stringify(options, undefined, 2)}`)
return options
}
function startLangServerTCP(addr: number): LanguageClient {
const serverOptions: ServerOptions = () => {
return new Promise((resolve /*, reject */) => {
const clientSocket = new net.Socket();
clientSocket.connect(addr, "127.0.0.1", () => {
resolve({
reader: clientSocket,
writer: clientSocket,
});
});
});
};
return new LanguageClient(
`tcp lang server (port ${addr})`,
serverOptions,
getClientOptions()
);
}
/**
* Execute a command provided by the language server.
*/
async function executeServerCommand() {
if (!client || client.state !== State.Running) {
await vscode.window.showErrorMessage("There is no language server running.")
return
}
const knownCommands = client.initializeResult.capabilities.executeCommandProvider?.commands
if (!knownCommands || knownCommands.length === 0) {
const info = client.initializeResult.serverInfo
const name = info?.name || "Server"
const version = info?.version || ""
await vscode.window.showInformationMessage(`${name} ${version} does not implement any commands.`)
return
}
const commandName = await vscode.window.showQuickPick(knownCommands, { canPickMany: false })
if (!commandName) {
return
}
logger.info(`executing command: '${commandName}'`)
const result = await vscode.commands.executeCommand(commandName /* if your command accepts arguments you can pass them here */)
logger.info(`${commandName} result: ${JSON.stringify(result, undefined, 2)}`)
}
/**
* If the user has explicitly provided a src directory use that.
* Otherwise, fallback to the examples/servers directory.
*
* @returns The working directory from which to launch the server
*/
function getCwd(): string {
const config = vscode.workspace.getConfiguration("pygls.server")
const cwd = config.get<string>('cwd')
if (cwd) {
return cwd
}
const serverDir = path.resolve(
path.join(__dirname, "..", "..", "servers")
)
return serverDir
}
/**
*
* @returns The python script to launch the server with
*/
function getServerPath(): string {
const config = vscode.workspace.getConfiguration("pygls.server")
const server = config.get<string>('launchScript')
return server
}
/**
* This uses the official python extension to grab the user's currently
* configured environment.
*
* @returns The python interpreter to use to launch the server
*/
async function getPythonPath(resource?: vscode.Uri): Promise<string | undefined> {
const config = vscode.workspace.getConfiguration("pygls.server", resource)
const pythonPath = config.get<string>('pythonPath')
if (pythonPath) {
logger.info(`Using user configured python environment: '${pythonPath}'`)
return pythonPath
}
if (!python) {
return
}
if (resource) {
logger.info(`Looking for environment in which to execute: '${resource.toString()}'`)
}
// Use whichever python interpreter the user has configured.
const activeEnvPath = python.environments.getActiveEnvironmentPath(resource)
logger.info(`Found environment: ${activeEnvPath.id}: ${activeEnvPath.path}`)
const activeEnv = await python.environments.resolveEnvironment(activeEnvPath)
if (!activeEnv) {
logger.error(`Unable to resolve envrionment: ${activeEnvPath}`)
return
}
const v = activeEnv.version
const pythonVersion = semver.parse(`${v.major}.${v.minor}.${v.micro}`)
// Check to see if the environment satisfies the min Python version.
if (semver.lt(pythonVersion, MIN_PYTHON)) {
const message = [
`Your currently configured environment provides Python v${pythonVersion} `,
`but pygls requires v${MIN_PYTHON}.\n\nPlease choose another environment.`
].join('')
const response = await vscode.window.showErrorMessage(message, "Change Environment")
if (!response) {
return
} else {
await vscode.commands.executeCommand('python.setInterpreter')
return
}
}
const pythonUri = activeEnv.executable.uri
if (!pythonUri) {
logger.error(`URI of Python executable is undefined!`)
return
}
return pythonUri.fsPath
}
async function getPythonExtension() {
try {
python = await PythonExtension.api();
} catch (err) {
logger.error(`Unable to load python extension: ${err}`)
}
}