Skip to content

Commit 8ee23f4

Browse files
committed
Auto merge of #13453 - Veykril:disabled-commands, r=Veykril
internal: Properly handle commands in the VSCode client when the server is stopped
2 parents 69f01fd + 1cb4607 commit 8ee23f4

File tree

2 files changed

+136
-103
lines changed

2 files changed

+136
-103
lines changed

editors/code/src/ctx.ts

+61-19
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ export type Workspace =
1818
files: vscode.TextDocument[];
1919
};
2020

21+
export type CommandFactory = {
22+
enabled: (ctx: Ctx) => Cmd;
23+
disabled?: (ctx: Ctx) => Cmd;
24+
};
25+
2126
export class Ctx {
2227
readonly statusBar: vscode.StatusBarItem;
2328
readonly config: Config;
@@ -26,31 +31,40 @@ export class Ctx {
2631
private _serverPath: string | undefined;
2732
private traceOutputChannel: vscode.OutputChannel | undefined;
2833
private outputChannel: vscode.OutputChannel | undefined;
34+
private clientSubscriptions: Disposable[];
2935
private state: PersistentState;
36+
private commandFactories: Record<string, CommandFactory>;
37+
private commandDisposables: Disposable[];
3038

3139
workspace: Workspace;
3240

33-
constructor(readonly extCtx: vscode.ExtensionContext, workspace: Workspace) {
34-
this.statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
35-
extCtx.subscriptions.push(this.statusBar);
36-
extCtx.subscriptions.push({
37-
dispose() {
38-
this.dispose();
39-
},
40-
});
41+
constructor(
42+
readonly extCtx: vscode.ExtensionContext,
43+
workspace: Workspace,
44+
commandFactories: Record<string, CommandFactory>
45+
) {
4146
extCtx.subscriptions.push(this);
47+
this.statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
4248
this.statusBar.text = "rust-analyzer";
4349
this.statusBar.tooltip = "ready";
4450
this.statusBar.command = "rust-analyzer.analyzerStatus";
4551
this.statusBar.show();
4652
this.workspace = workspace;
53+
this.clientSubscriptions = [];
54+
this.commandDisposables = [];
55+
this.commandFactories = commandFactories;
4756

4857
this.state = new PersistentState(extCtx.globalState);
4958
this.config = new Config(extCtx);
59+
60+
this.updateCommands();
5061
}
5162

5263
dispose() {
5364
this.config.dispose();
65+
this.statusBar.dispose();
66+
void this.disposeClient();
67+
this.commandDisposables.forEach((disposable) => disposable.dispose());
5468
}
5569

5670
clientFetcher() {
@@ -63,7 +77,6 @@ export class Ctx {
6377
}
6478

6579
async getClient() {
66-
// if server path changes -> dispose
6780
if (!this.traceOutputChannel) {
6881
this.traceOutputChannel = vscode.window.createOutputChannel(
6982
"Rust Analyzer Language Server Trace"
@@ -118,7 +131,11 @@ export class Ctx {
118131
initializationOptions,
119132
serverOptions
120133
);
121-
this.client.onNotification(ra.serverStatus, (params) => this.setServerStatus(params));
134+
this.pushClientCleanup(
135+
this.client.onNotification(ra.serverStatus, (params) =>
136+
this.setServerStatus(params)
137+
)
138+
);
122139
}
123140
return this.client;
124141
}
@@ -127,16 +144,25 @@ export class Ctx {
127144
log.info("Activating language client");
128145
const client = await this.getClient();
129146
await client.start();
147+
this.updateCommands();
130148
return client;
131149
}
132150

133151
async deactivate() {
134152
log.info("Deactivating language client");
135153
await this.client?.stop();
154+
this.updateCommands();
136155
}
137156

138-
async disposeClient() {
139-
log.info("Deactivating language client");
157+
async stop() {
158+
log.info("Stopping language client");
159+
await this.disposeClient();
160+
this.updateCommands();
161+
}
162+
163+
private async disposeClient() {
164+
this.clientSubscriptions?.forEach((disposable) => disposable.dispose());
165+
this.clientSubscriptions = [];
140166
await this.client?.dispose();
141167
this._serverPath = undefined;
142168
this.client = undefined;
@@ -159,6 +185,25 @@ export class Ctx {
159185
return this._serverPath;
160186
}
161187

188+
private updateCommands() {
189+
this.commandDisposables.forEach((disposable) => disposable.dispose());
190+
this.commandDisposables = [];
191+
const fetchFactory = (factory: CommandFactory, fullName: string) => {
192+
return this.client && this.client.isRunning()
193+
? factory.enabled
194+
: factory.disabled ||
195+
((_) => () =>
196+
vscode.window.showErrorMessage(
197+
`command ${fullName} failed: rust-analyzer server is not running`
198+
));
199+
};
200+
for (const [name, factory] of Object.entries(this.commandFactories)) {
201+
const fullName = `rust-analyzer.${name}`;
202+
const callback = fetchFactory(factory, fullName)(this);
203+
this.commandDisposables.push(vscode.commands.registerCommand(fullName, callback));
204+
}
205+
}
206+
162207
setServerStatus(status: ServerStatusParams) {
163208
let icon = "";
164209
const statusBar = this.statusBar;
@@ -194,16 +239,13 @@ export class Ctx {
194239
statusBar.text = `${icon}rust-analyzer`;
195240
}
196241

197-
registerCommand(name: string, factory: (ctx: Ctx) => Cmd) {
198-
const fullName = `rust-analyzer.${name}`;
199-
const cmd = factory(this);
200-
const d = vscode.commands.registerCommand(fullName, cmd);
201-
this.pushExtCleanup(d);
202-
}
203-
204242
pushExtCleanup(d: Disposable) {
205243
this.extCtx.subscriptions.push(d);
206244
}
245+
246+
private pushClientCleanup(d: Disposable) {
247+
this.clientSubscriptions.push(d);
248+
}
207249
}
208250

209251
export interface Disposable {

editors/code/src/main.ts

+75-84
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as vscode from "vscode";
22
import * as lc from "vscode-languageclient/node";
33

44
import * as commands from "./commands";
5-
import { Ctx, Workspace } from "./ctx";
5+
import { CommandFactory, Ctx, Workspace } from "./ctx";
66
import { isRustDocument } from "./util";
77
import { activateTaskProvider } from "./tasks";
88
import { setContextValue } from "./util";
@@ -57,7 +57,7 @@ export async function activate(
5757
}
5858
: { kind: "Workspace Folder" };
5959

60-
const ctx = new Ctx(context, workspace);
60+
const ctx = new Ctx(context, workspace, createCommands());
6161
// VS Code doesn't show a notification when an extension fails to activate
6262
// so we do it ourselves.
6363
const api = await activateServer(ctx).catch((err) => {
@@ -75,8 +75,6 @@ async function activateServer(ctx: Ctx): Promise<RustAnalyzerExtensionApi> {
7575
ctx.pushExtCleanup(activateTaskProvider(ctx.config));
7676
}
7777

78-
await initCommonContext(ctx);
79-
8078
vscode.workspace.onDidChangeConfiguration(
8179
async (_) => {
8280
await ctx
@@ -91,85 +89,78 @@ async function activateServer(ctx: Ctx): Promise<RustAnalyzerExtensionApi> {
9189
return ctx.clientFetcher();
9290
}
9391

94-
async function initCommonContext(ctx: Ctx) {
95-
// Register a "dumb" onEnter command for the case where server fails to
96-
// start.
97-
//
98-
// FIXME: refactor command registration code such that commands are
99-
// **always** registered, even if the server does not start. Use API like
100-
// this perhaps?
101-
//
102-
// ```TypeScript
103-
// registerCommand(
104-
// factory: (Ctx) => ((Ctx) => any),
105-
// fallback: () => any = () => vscode.window.showErrorMessage(
106-
// "rust-analyzer is not available"
107-
// ),
108-
// )
109-
const defaultOnEnter = vscode.commands.registerCommand("rust-analyzer.onEnter", () =>
110-
vscode.commands.executeCommand("default:type", { text: "\n" })
111-
);
112-
ctx.pushExtCleanup(defaultOnEnter);
113-
114-
// Commands which invokes manually via command palette, shortcut, etc.
115-
ctx.registerCommand("reload", (_) => async () => {
116-
void vscode.window.showInformationMessage("Reloading rust-analyzer...");
117-
// FIXME: We should re-use the client, that is ctx.deactivate() if none of the configs have changed
118-
await ctx.disposeClient();
119-
await ctx.activate();
120-
});
121-
122-
ctx.registerCommand("startServer", (_) => async () => {
123-
await ctx.activate();
124-
});
125-
ctx.registerCommand("stopServer", (_) => async () => {
126-
// FIXME: We should re-use the client, that is ctx.deactivate() if none of the configs have changed
127-
await ctx.disposeClient();
128-
ctx.setServerStatus({
129-
health: "ok",
130-
quiescent: true,
131-
message: "server is not running",
132-
});
133-
});
134-
ctx.registerCommand("analyzerStatus", commands.analyzerStatus);
135-
ctx.registerCommand("memoryUsage", commands.memoryUsage);
136-
ctx.registerCommand("shuffleCrateGraph", commands.shuffleCrateGraph);
137-
ctx.registerCommand("reloadWorkspace", commands.reloadWorkspace);
138-
ctx.registerCommand("matchingBrace", commands.matchingBrace);
139-
ctx.registerCommand("joinLines", commands.joinLines);
140-
ctx.registerCommand("parentModule", commands.parentModule);
141-
ctx.registerCommand("syntaxTree", commands.syntaxTree);
142-
ctx.registerCommand("viewHir", commands.viewHir);
143-
ctx.registerCommand("viewFileText", commands.viewFileText);
144-
ctx.registerCommand("viewItemTree", commands.viewItemTree);
145-
ctx.registerCommand("viewCrateGraph", commands.viewCrateGraph);
146-
ctx.registerCommand("viewFullCrateGraph", commands.viewFullCrateGraph);
147-
ctx.registerCommand("expandMacro", commands.expandMacro);
148-
ctx.registerCommand("run", commands.run);
149-
ctx.registerCommand("copyRunCommandLine", commands.copyRunCommandLine);
150-
ctx.registerCommand("debug", commands.debug);
151-
ctx.registerCommand("newDebugConfig", commands.newDebugConfig);
152-
ctx.registerCommand("openDocs", commands.openDocs);
153-
ctx.registerCommand("openCargoToml", commands.openCargoToml);
154-
ctx.registerCommand("peekTests", commands.peekTests);
155-
ctx.registerCommand("moveItemUp", commands.moveItemUp);
156-
ctx.registerCommand("moveItemDown", commands.moveItemDown);
157-
ctx.registerCommand("cancelFlycheck", commands.cancelFlycheck);
158-
159-
ctx.registerCommand("ssr", commands.ssr);
160-
ctx.registerCommand("serverVersion", commands.serverVersion);
161-
162-
// Internal commands which are invoked by the server.
163-
ctx.registerCommand("runSingle", commands.runSingle);
164-
ctx.registerCommand("debugSingle", commands.debugSingle);
165-
ctx.registerCommand("showReferences", commands.showReferences);
166-
ctx.registerCommand("applySnippetWorkspaceEdit", commands.applySnippetWorkspaceEditCommand);
167-
ctx.registerCommand("resolveCodeAction", commands.resolveCodeAction);
168-
ctx.registerCommand("applyActionGroup", commands.applyActionGroup);
169-
ctx.registerCommand("gotoLocation", commands.gotoLocation);
170-
171-
ctx.registerCommand("linkToCommand", commands.linkToCommand);
92+
function createCommands(): Record<string, CommandFactory> {
93+
return {
94+
onEnter: {
95+
enabled: commands.onEnter,
96+
disabled: (_) => () => vscode.commands.executeCommand("default:type", { text: "\n" }),
97+
},
98+
reload: {
99+
enabled: (ctx) => async () => {
100+
void vscode.window.showInformationMessage("Reloading rust-analyzer...");
101+
// FIXME: We should re-use the client, that is ctx.deactivate() if none of the configs have changed
102+
await ctx.stop();
103+
await ctx.activate();
104+
},
105+
disabled: (ctx) => async () => {
106+
void vscode.window.showInformationMessage("Reloading rust-analyzer...");
107+
await ctx.activate();
108+
},
109+
},
110+
startServer: {
111+
enabled: (ctx) => async () => {
112+
await ctx.activate();
113+
},
114+
disabled: (ctx) => async () => {
115+
await ctx.activate();
116+
},
117+
},
118+
stopServer: {
119+
enabled: (ctx) => async () => {
120+
// FIXME: We should re-use the client, that is ctx.deactivate() if none of the configs have changed
121+
await ctx.stop();
122+
ctx.setServerStatus({
123+
health: "ok",
124+
quiescent: true,
125+
message: "server is not running",
126+
});
127+
},
128+
},
172129

173-
defaultOnEnter.dispose();
174-
ctx.registerCommand("onEnter", commands.onEnter);
130+
analyzerStatus: { enabled: commands.analyzerStatus },
131+
memoryUsage: { enabled: commands.memoryUsage },
132+
shuffleCrateGraph: { enabled: commands.shuffleCrateGraph },
133+
reloadWorkspace: { enabled: commands.reloadWorkspace },
134+
matchingBrace: { enabled: commands.matchingBrace },
135+
joinLines: { enabled: commands.joinLines },
136+
parentModule: { enabled: commands.parentModule },
137+
syntaxTree: { enabled: commands.syntaxTree },
138+
viewHir: { enabled: commands.viewHir },
139+
viewFileText: { enabled: commands.viewFileText },
140+
viewItemTree: { enabled: commands.viewItemTree },
141+
viewCrateGraph: { enabled: commands.viewCrateGraph },
142+
viewFullCrateGraph: { enabled: commands.viewFullCrateGraph },
143+
expandMacro: { enabled: commands.expandMacro },
144+
run: { enabled: commands.run },
145+
copyRunCommandLine: { enabled: commands.copyRunCommandLine },
146+
debug: { enabled: commands.debug },
147+
newDebugConfig: { enabled: commands.newDebugConfig },
148+
openDocs: { enabled: commands.openDocs },
149+
openCargoToml: { enabled: commands.openCargoToml },
150+
peekTests: { enabled: commands.peekTests },
151+
moveItemUp: { enabled: commands.moveItemUp },
152+
moveItemDown: { enabled: commands.moveItemDown },
153+
cancelFlycheck: { enabled: commands.cancelFlycheck },
154+
ssr: { enabled: commands.ssr },
155+
serverVersion: { enabled: commands.serverVersion },
156+
// Internal commands which are invoked by the server.
157+
applyActionGroup: { enabled: commands.applyActionGroup },
158+
applySnippetWorkspaceEdit: { enabled: commands.applySnippetWorkspaceEditCommand },
159+
debugSingle: { enabled: commands.debugSingle },
160+
gotoLocation: { enabled: commands.gotoLocation },
161+
linkToCommand: { enabled: commands.linkToCommand },
162+
resolveCodeAction: { enabled: commands.resolveCodeAction },
163+
runSingle: { enabled: commands.runSingle },
164+
showReferences: { enabled: commands.showReferences },
165+
};
175166
}

0 commit comments

Comments
 (0)