-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathclient.ts
347 lines (285 loc) · 8.58 KB
/
client.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
import * as vscode from 'vscode';
import { join } from "path";
import {
ConfigurationParams,
CancellationToken,
LanguageClient,
LanguageClientOptions,
ServerOptions,
ExecutableOptions,
ResponseError,
State
} from "vscode-languageclient/node";
import { InitOptions } from "../common/config";
import { OutputChannelLogger } from "../common/log";
import { PythonManager } from "./python";
import { Commands, Events, Notifications } from '../common/constants';
export interface SphinxInfo {
/**
* A unique id used to refer to this Sphinx application instance.
*/
id: string
/**
* Sphinx's version number
*/
version: string
/**
* The Sphinx application object's confdir
*/
conf_dir: string
/**
* The Sphinx application object's outdir
*/
build_dir: string
/**
* The current builder's name
*/
builder_name: string
/**
* The Sphinx application object's srcdir
*/
src_dir: string
}
export class EsbonioClient {
private client?: LanguageClient
private devtools?: vscode.TaskExecution
private handlers: Map<string, any[]>
constructor(
private logger: OutputChannelLogger,
private python: PythonManager,
private context: vscode.ExtensionContext,
private channel: vscode.OutputChannel,
) {
this.handlers = new Map()
// Restart server implementation
context.subscriptions.push(
vscode.commands.registerCommand(Commands.RESTART_SERVER, async () => await this.restartServer())
)
// Unset devtools task when it finishes.
context.subscriptions.push(
vscode.tasks.onDidEndTask((event) => {
if (event.execution === this.devtools) {
this.devtools = undefined
}
})
)
}
public addHandler(event: string, handler: any) {
if (this.handlers.has(event)) {
this.handlers.get(event)?.push(handler)
} else {
this.handlers.set(event, [handler])
}
}
/**
* Start the language server.
*/
async start(): Promise<void> {
try {
this.client = await this.getStdioClient()
} catch (err) {
this.logger.error(`${err}`)
return
}
if (!this.client) {
return
}
try {
this.logger.info("Starting Language Server")
await this.client.start()
this.callHandlers(Events.SERVER_START, undefined)
} catch (err) {
this.logger.error(`${err}`)
}
}
/**
* Restart the language server
*/
async restartServer() {
let config = vscode.workspace.getConfiguration("esbonio.server")
if (config.get("enabled")) {
this.logger.info("Restarting server...")
await this.stop()
await this.start()
}
}
/**
* Stop the language server.
*/
async stop() {
if (this.client && this.client.state === State.Running) {
this.callHandlers(Events.SERVER_STOP, undefined)
await this.client.stop()
}
return
}
/**
* Return a LanguageClient configured to communicate with the server over stdio.
*/
private async getStdioClient(): Promise<LanguageClient | undefined> {
let command = await this.python.getCmd()
if (!command) {
return
}
// Isolate the Python interpreter from the user's environment - we brought our own.
command.push("-S")
let config = vscode.workspace.getConfiguration("esbonio")
let serverDevtools = config.get<boolean>('server.enableDevTools')
let sphinxDevtools = config.get<boolean>('sphinx.enableDevTools')
if (serverDevtools || sphinxDevtools) {
await this.startDevtools(command[0], ...command.slice(1), "-m", "lsp_devtools", "tui")
}
if (serverDevtools) {
command.push("-m", "lsp_devtools", "agent", "--", ...command)
}
let startupModule = config.get<string>("server.startupModule") || "esbonio.server"
let includedModules = config.get<string[]>('server.includedModules') || []
let excludedModules = config.get<string[]>('server.excludedModules') || []
// Entry point can either be a script, or it can be a python module.
if (startupModule.endsWith(".py") || startupModule.includes("/") || startupModule.includes("\\")) {
command.push(startupModule)
} else {
command.push("-m", startupModule)
}
includedModules.forEach(mod => {
command?.push('--include', mod)
})
excludedModules.forEach(mod => {
command?.push('--exclude', mod)
})
this.logger.debug(`Server start command: ${command.join(" ")}`)
let serverEnv: ExecutableOptions = {
env: {
PYTHONPATH: join(this.context.extensionPath, "bundled", "libs")
}
}
let server: ServerOptions = {
command: command[0], args: command.slice(1), options: serverEnv
}
let client = new LanguageClient(
'esbonio',
'Esbonio Language Server',
server,
this.getLanguageClientOptions(config)
)
this.registerHandlers(client)
return client
}
public scrollView(line: number) {
this.client?.sendNotification(Notifications.VIEW_SCROLL, { line: line })
}
/**
* Register any additional method handlers on the language client.
*/
private registerHandlers(client: LanguageClient) {
let methods = [
Notifications.SCROLL_EDITOR,
Notifications.SPHINX_APP_CREATED,
]
for (let method of methods) {
client.onNotification(method, (params) => {
this.callHandlers(method, params)
})
}
}
/**
* Returns the LanguageClient options that are common to both modes of
* transport.
*/
private getLanguageClientOptions(config: vscode.WorkspaceConfiguration): LanguageClientOptions {
let initOptions: InitOptions = {
server: {
logLevel: config.get<string>('server.logLevel'),
logFilter: config.get<string[]>('server.logFilter'),
showDeprecationWarnings: config.get<boolean>('server.showDeprecationWarnings'),
completion: {
preferredInsertBehavior: config.get<string>('server.completion.preferredInsertBehavior')
}
}
}
let documentSelector = [
{ scheme: 'file', language: 'restructuredtext' },
]
if (config.get<boolean>('server.enabledInPyFiles')) {
documentSelector.push(
{ scheme: 'file', language: 'python' }
)
}
let clientOptions: LanguageClientOptions = {
documentSelector: documentSelector,
initializationOptions: initOptions,
outputChannel: this.channel,
connectionOptions: {
maxRestartCount: 0
},
middleware: {
workspace: {
configuration: async (params: ConfigurationParams, token: CancellationToken, next) => {
// this.logger.debug(`workspace/configuration: ${JSON.stringify(params, undefined, 2)}`)
let index = -1
params.items.forEach((item, i) => {
if (item.section === "esbonio.sphinx") {
index = i
}
})
let result = await next(params, token);
if (result instanceof ResponseError) {
return result
}
if (index < 0) {
return result
}
let item = result[index]
if (item.pythonCommand.length > 0) {
return result
}
// User has not explictly configured a Python command, try and inject the
// Python interpreter they have configured for this resource.
let scopeUri: vscode.Uri | undefined = undefined
let scope = params.items[index].scopeUri
if (scope) {
scopeUri = vscode.Uri.parse(scope)
}
let python = await this.python.getCmd(scopeUri)
if (python) {
item.pythonCommand = python
}
return result
}
}
},
}
this.logger.debug(`LanguageClientOptions: ${JSON.stringify(clientOptions, null, 2)}`)
return clientOptions
}
private callHandlers(method: string, params: any) {
this.handlers.get(method)?.forEach(handler => {
try {
handler(params)
} catch (err) {
this.logger.error(`Error in '${method}' notification handler: ${err}`)
}
})
}
private async startDevtools(command: string, ...args: string[]) {
if (this.devtools) {
return
}
const task = new vscode.Task(
{ type: 'esbonio-devtools' },
vscode.TaskScope.Workspace,
"lsp-devtools",
"esbonio",
new vscode.ProcessExecution(
command,
args,
{
env: {
PYTHONPATH: join(this.context.extensionPath, "bundled", "libs")
}
}
),
)
this.devtools = await vscode.tasks.executeTask(task)
}
}