This repository has been archived by the owner on May 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
/
debugger.ts
263 lines (233 loc) · 8.58 KB
/
debugger.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
import path from "path";
import fs from "fs";
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import * as vscode from "vscode";
import { Ruby } from "./ruby";
import { LOG_CHANNEL } from "./common";
export class Debugger
implements
vscode.DebugAdapterDescriptorFactory,
vscode.DebugConfigurationProvider
{
private readonly workingFolder: string;
private readonly ruby: Ruby;
private debugProcess?: ChildProcessWithoutNullStreams;
private readonly console = vscode.debug.activeDebugConsole;
private readonly subscriptions: vscode.Disposable[];
constructor(
context: vscode.ExtensionContext,
ruby: Ruby,
workingFolder = vscode.workspace.workspaceFolders![0].uri.fsPath,
) {
this.ruby = ruby;
this.subscriptions = [
vscode.debug.registerDebugConfigurationProvider("ruby_lsp", this),
vscode.debug.registerDebugAdapterDescriptorFactory("ruby_lsp", this),
];
this.workingFolder = workingFolder;
context.subscriptions.push(...this.subscriptions);
}
// This is where we start the debuggee process. We currently support launching with the debugger or attaching to a
// process that was already booted with the debugger
async createDebugAdapterDescriptor(
session: vscode.DebugSession,
_executable: vscode.DebugAdapterExecutable,
): Promise<vscode.DebugAdapterDescriptor | undefined> {
if (session.configuration.request === "launch") {
return this.spawnDebuggeeForLaunch(session);
} else if (session.configuration.request === "attach") {
return this.attachDebuggee();
} else {
return new Promise((_resolve, reject) =>
reject(
new Error(
`Unknown request type: ${session.configuration.request}. Please review your launch configurations`,
),
),
);
}
}
provideDebugConfigurations?(
_folder: vscode.WorkspaceFolder | undefined,
_token?: vscode.CancellationToken,
): vscode.ProviderResult<vscode.DebugConfiguration[]> {
return [
{
type: "ruby_lsp",
name: "Debug script",
request: "launch",
// eslint-disable-next-line no-template-curly-in-string
program: "ruby ${file}",
},
{
type: "ruby_lsp",
name: "Debug test",
request: "launch",
// eslint-disable-next-line no-template-curly-in-string
program: "ruby -Itest ${relativeFile}",
},
{
type: "ruby_lsp",
name: "Attach debugger",
request: "attach",
},
];
}
// Resolve the user's debugger configuration. Here we receive what is configured in launch.json and can modify and
// insert defaults for the user. The most important thing is making sure the Ruby environment is a part of it so that
// we launch using the right bundle and Ruby version
resolveDebugConfiguration?(
_folder: vscode.WorkspaceFolder | undefined,
debugConfiguration: vscode.DebugConfiguration,
_token?: vscode.CancellationToken,
): vscode.ProviderResult<vscode.DebugConfiguration> {
if (debugConfiguration.env) {
// If the user has their own debug launch configurations, we still need to inject the Ruby environment
debugConfiguration.env = Object.assign(
debugConfiguration.env,
this.ruby.env,
);
} else {
debugConfiguration.env = this.ruby.env;
}
let customGemfilePath = path.join(
this.workingFolder,
".ruby-lsp",
"Gemfile",
);
if (fs.existsSync(customGemfilePath)) {
debugConfiguration.env.BUNDLE_GEMFILE = customGemfilePath;
}
customGemfilePath = path.join(this.workingFolder, ".ruby-lsp", "gems.rb");
if (fs.existsSync(customGemfilePath)) {
debugConfiguration.env.BUNDLE_GEMFILE = customGemfilePath;
}
return debugConfiguration;
}
dispose() {
if (this.debugProcess) {
this.debugProcess.kill("SIGTERM");
}
this.subscriptions.forEach((subscription) => subscription.dispose());
}
private attachDebuggee(): Promise<vscode.DebugAdapterDescriptor | undefined> {
// When using attach, a process will be launched using Ruby debug and it will create a socket automatically. We have
// to find the available sockets and ask the user which one they want to attach to
const socketsDir = path.join("/", "tmp", "ruby-lsp-debug-sockets");
const sockets = fs
.readdirSync(socketsDir)
.map((file) => file)
.filter((file) => file.endsWith(".sock"));
// eslint-disable-next-line @typescript-eslint/no-misused-promises
return new Promise((resolve, reject) => {
if (sockets.length === 0) {
reject(
new Error(
`No debuggee processes found. Was a socket created in ${socketsDir}?`,
),
);
}
return vscode.window
.showQuickPick(sockets, {
placeHolder: "Select a debuggee",
ignoreFocusOut: true,
})
.then((selectedSocket) => {
if (selectedSocket === undefined) {
reject(new Error("No debuggee selected"));
} else {
resolve(
new vscode.DebugAdapterNamedPipeServer(
path.join(socketsDir, selectedSocket),
),
);
}
});
});
}
private spawnDebuggeeForLaunch(
session: vscode.DebugSession,
): Promise<vscode.DebugAdapterDescriptor | undefined> {
let initialMessage = "";
let initialized = false;
const sockPath = this.socketPath();
const configuration = session.configuration;
return new Promise((resolve, reject) => {
const args = [
"exec",
"rdbg",
"--open",
"--command",
`--sock-path=${sockPath}`,
"--",
configuration.program,
];
LOG_CHANNEL.info(`Spawning debugger in directory ${this.workingFolder}`);
LOG_CHANNEL.info(` Command bundle ${args.join(" ")}`);
LOG_CHANNEL.info(` Environment ${JSON.stringify(configuration.env)}`);
this.debugProcess = spawn("bundle", args, {
shell: true,
env: configuration.env,
cwd: this.workingFolder,
});
this.debugProcess.stderr.on("data", (data) => {
const message = data.toString();
// Print whatever data we get in stderr in the debug console since it might be relevant for the user
this.console.append(message);
if (!initialized) {
initialMessage += message;
}
// When stderr includes a complete wait for debugger connection message, then we're done initializing and can
// resolve the promise. If we try to resolve earlier, VS Code will simply fail to connect
if (
initialMessage.includes("DEBUGGER: wait for debugger connection...")
) {
initialized = true;
resolve(new vscode.DebugAdapterNamedPipeServer(sockPath));
}
});
// Anything printed by debug to stdout we want to show in the debug console
this.debugProcess.stdout.on("data", (data) => {
this.console.append(data.toString());
});
// If any errors occur in the server, we have to show that in the debug console and reject the promise
this.debugProcess.on("error", (error) => {
this.console.append(error.message);
reject(error);
});
// If the Ruby debug exits with an exit code > 1, then an error might've occurred. The reason we don't use only
// code zero here is because debug actually exits with 1 if the user cancels the debug session, which is not
// actually an error
this.debugProcess.on("exit", (code) => {
if (code) {
const message = `Debugger exited with status ${code}. Check the output channel for more information.`;
this.console.append(message);
LOG_CHANNEL.show();
reject(new Error(message));
}
});
});
}
// Generate a socket path so that Ruby debug doesn't have to create one for us. This makes coordination easier since
// we always know the path to the socket
private socketPath() {
const socketsDir = path.join("/", "tmp", "ruby-lsp-debug-sockets");
if (!fs.existsSync(socketsDir)) {
fs.mkdirSync(socketsDir);
}
let socketIndex = 0;
const prefix = `ruby-debug-${path.basename(this.workingFolder)}`;
const existingSockets = fs
.readdirSync(socketsDir)
.map((file) => file)
.filter((file) => file.startsWith(prefix))
.sort();
if (existingSockets.length > 0) {
socketIndex =
Number(
/-(\d+).sock$/.exec(existingSockets[existingSockets.length - 1])![1],
) + 1;
}
return `${socketsDir}/${prefix}-${socketIndex}.sock`;
}
}