forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmockDebugService.ts
More file actions
336 lines (310 loc) · 12.3 KB
/
mockDebugService.ts
File metadata and controls
336 lines (310 loc) · 12.3 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { inject, injectable } from 'inversify';
import * as net from 'net';
import * as path from 'path';
import * as uuid from 'uuid/v4';
import {
Breakpoint,
BreakpointsChangeEvent,
DebugAdapterTracker,
DebugAdapterTrackerFactory,
DebugConfiguration,
DebugConfigurationProvider,
DebugConsole,
DebugSession,
DebugSessionCustomEvent,
Disposable,
Event,
EventEmitter,
SourceBreakpoint,
WorkspaceFolder
} from 'vscode';
import { DebugProtocol } from 'vscode-debugprotocol';
import { IDebugService } from '../../client/common/application/types';
import { traceInfo } from '../../client/common/logger';
import { IDisposable } from '../../client/common/types';
import { createDeferred } from '../../client/common/utils/async';
import { noop } from '../../client/common/utils/misc';
import { EXTENSION_ROOT_DIR } from '../../client/constants';
import { IProtocolParser } from '../../client/debugger/debugAdapter/types';
import { DebugAdapterDescriptorFactory } from '../../client/debugger/extension/adapter/factory';
// tslint:disable:no-any
// For debugging set these environment variables
// PYDEV_DEBUG=True
// PTVSD_LOG_DIR=<dir that already exists>
// PYDEVD_DEBUG_FILE=<dir that exists, but new file allowed>
class MockDebugSession implements DebugSession {
private _name = 'MockDebugSession';
constructor(
private _id: string,
private _configuration: DebugConfiguration,
private customRequestHandler: (command: string, args?: any) => Thenable<any>
) {
noop();
}
public get id(): string {
return this._id;
}
public get type(): string {
return 'python';
}
public get name(): string {
return this._name;
}
public get workspaceFolder(): WorkspaceFolder | undefined {
return undefined;
}
public get configuration(): DebugConfiguration {
return this._configuration;
}
public customRequest(command: string, args?: any): Thenable<any> {
return this.customRequestHandler(command, args);
}
}
//tslint:disable:trailing-comma no-any no-multiline-string
@injectable()
export class MockDebuggerService implements IDebugService, IDisposable {
private socket: net.Socket | undefined;
private session: DebugSession | undefined;
private sequence: number = 1;
private breakpointEmitter: EventEmitter<void> = new EventEmitter<void>();
private debugAdapterTrackerFactory: DebugAdapterTrackerFactory | undefined;
private debugAdapterTracker: DebugAdapterTracker | undefined;
private sessionChangedEvent: EventEmitter<DebugSession> = new EventEmitter<DebugSession>();
private sessionStartedEvent: EventEmitter<DebugSession> = new EventEmitter<DebugSession>();
private sessionTerminatedEvent: EventEmitter<DebugSession> = new EventEmitter<DebugSession>();
private sessionCustomEvent: EventEmitter<DebugSessionCustomEvent> = new EventEmitter<DebugSessionCustomEvent>();
private breakpointsChangedEvent: EventEmitter<BreakpointsChangeEvent> = new EventEmitter<BreakpointsChangeEvent>();
private _breakpoints: Breakpoint[] = [];
private _stoppedThreadId: number | undefined;
constructor(@inject(IProtocolParser) private protocolParser: IProtocolParser) {
noop();
}
public dispose(): void {
if (this.socket) {
this.socket.end();
this.socket = undefined;
}
}
public get activeDebugSession(): DebugSession | undefined {
return this.session;
}
public get activeDebugConsole(): DebugConsole {
return {
append(_value: string): void {
noop();
},
appendLine(_value: string): void {
noop();
}
};
}
public get breakpoints(): Breakpoint[] {
return this._breakpoints;
}
public get onDidChangeActiveDebugSession(): Event<DebugSession | undefined> {
return this.sessionChangedEvent.event;
}
public get onDidStartDebugSession(): Event<DebugSession> {
return this.sessionStartedEvent.event;
}
public get onDidReceiveDebugSessionCustomEvent(): Event<DebugSessionCustomEvent> {
return this.sessionCustomEvent.event;
}
public get onDidTerminateDebugSession(): Event<DebugSession> {
return this.sessionTerminatedEvent.event;
}
public get onDidChangeBreakpoints(): Event<BreakpointsChangeEvent> {
return this.breakpointsChangedEvent.event;
}
public registerDebugConfigurationProvider(_debugType: string, _provider: DebugConfigurationProvider): Disposable {
throw new Error('Method not implemented.');
}
public registerDebugAdapterDescriptorFactory(
_debugType: string,
_factory: DebugAdapterDescriptorFactory
): Disposable {
throw new Error('Not implemented');
}
public registerDebugAdapterTrackerFactory(_debugType: string, _provider: DebugAdapterTrackerFactory): Disposable {
this.debugAdapterTrackerFactory = _provider;
return {
dispose: () => {
noop();
}
};
}
public startDebugging(
_folder: WorkspaceFolder | undefined,
nameOrConfiguration: string | DebugConfiguration,
_parentSession?: DebugSession | undefined
): Thenable<boolean> {
// Should have a port number. We'll assume during the test it's local
const config = nameOrConfiguration as DebugConfiguration;
if (config.port) {
this.session = new MockDebugSession(uuid(), config, this.sendCustomRequest.bind(this));
// Create our debug adapter tracker at session start
if (this.debugAdapterTrackerFactory) {
this.debugAdapterTracker = this.debugAdapterTrackerFactory.createDebugAdapterTracker(
this.session
) as DebugAdapterTracker;
}
this.socket = net.createConnection(config.port);
this.protocolParser.connect(this.socket);
this.protocolParser.on('event_stopped', this.onBreakpoint.bind(this));
this.protocolParser.on('event_output', this.onOutput.bind(this));
this.socket.on('error', this.onError.bind(this));
this.socket.on('close', this.onClose.bind(this));
return this.sendStartSequence(config.port, this.session.id);
}
return Promise.resolve(true);
}
public addBreakpoints(breakpoints: Breakpoint[]): void {
this._breakpoints = this._breakpoints.concat(breakpoints);
}
public removeBreakpoints(_breakpoints: Breakpoint[]): void {
noop();
}
public get onBreakpointHit(): Event<void> {
return this.breakpointEmitter.event;
}
public async continue(): Promise<void> {
await this.sendMessage('continue', { threadId: 0 });
if (this.debugAdapterTracker && this.debugAdapterTracker.onDidSendMessage) {
this.debugAdapterTracker.onDidSendMessage({ type: 'event', event: 'continue' });
}
}
public async getStackTrace(): Promise<DebugProtocol.StackTraceResponse | undefined> {
const deferred = createDeferred<DebugProtocol.StackTraceResponse>();
this.protocolParser.once('response_stackTrace', (args: any) => {
if (this.debugAdapterTracker && this.debugAdapterTracker.onDidSendMessage) {
this.debugAdapterTracker.onDidSendMessage(args as DebugProtocol.StackTraceResponse);
}
deferred.resolve(args as DebugProtocol.StackTraceResponse);
});
await this.emitMessage('stackTrace', {
threadId: this._stoppedThreadId ? this._stoppedThreadId : 1,
startFrame: 0,
levels: 1
});
return deferred.promise;
}
private sendCustomRequest(command: string, args?: any): Promise<void> {
return this.sendMessage(command, args);
}
private async sendStartSequence(port: number, sessionId: string): Promise<boolean> {
await this.sendInitialize();
await this.sendAttach(port, sessionId);
if (this._breakpoints.length > 0) {
await this.sendBreakpoints();
}
await this.sendConfigurationDone();
return true;
}
private sendBreakpoints(): Promise<void> {
// Only supporting a single file now
const sbs = this._breakpoints.map(b => b as SourceBreakpoint);
const file = sbs[0].location.uri.fsPath;
return this.sendMessage('setBreakpoints', {
source: {
name: path.basename(file),
path: file
},
lines: sbs.map(sb => sb.location.range.start.line),
breakpoints: sbs.map(sb => {
return { line: sb.location.range.start.line };
}),
sourceModified: true
});
}
private sendAttach(port: number, sessionId: string): Promise<void> {
// Send our attach request
return this.sendMessage('attach', {
name: 'IPython',
request: 'attach',
type: 'python',
port,
host: 'localhost',
justMyCode: true,
logToFile: true,
debugOptions: ['RedirectOutput', 'FixFilePathCase', 'WindowsClient', 'ShowReturnValue'],
showReturnValue: true,
workspaceFolder: EXTENSION_ROOT_DIR,
pathMappings: [{ localRoot: EXTENSION_ROOT_DIR, remoteRoot: EXTENSION_ROOT_DIR }],
__sessionId: sessionId
});
}
private sendConfigurationDone(): Promise<void> {
return this.sendMessage('configurationDone');
}
private async sendInitialize(): Promise<void> {
// Send our initialize request. (Got this by dumping debugAdapter output during real run. Set logToFile to true to generate)
await this.sendMessage('initialize', {
clientID: 'vscode',
clientName: 'Visual Studio Code',
adapterID: 'python',
pathFormat: 'path',
linesStartAt1: true,
columnsStartAt1: true,
supportsVariableType: true,
supportsVariablePaging: true,
supportsRunInTerminalRequest: true,
locale: 'en-us'
});
}
private async sendMessage(command: string, args?: any): Promise<void> {
const response = createDeferred();
this.protocolParser.once(`response_${command}`, () => response.resolve());
this.socket!.on('error', err => response.reject(err));
await this.emitMessage(command, args);
await response.promise;
}
private emitMessage(command: string, args?: any): Promise<void> {
return new Promise((resolve, reject) => {
try {
if (this.socket) {
const obj = {
command,
arguments: args,
type: 'request',
seq: this.sequence
};
this.sequence += 1;
const objString = JSON.stringify(obj);
const message = `Content-Length: ${objString.length}\r\n\r\n${objString}`;
this.socket.write(message, (_a: any) => {
if (this.debugAdapterTracker && this.debugAdapterTracker.onDidSendMessage) {
this.debugAdapterTracker.onDidSendMessage(obj);
}
resolve();
});
}
} catch (e) {
reject(e);
}
});
}
private onBreakpoint(args: DebugProtocol.StoppedEvent): void {
// Save the current thread id. We use this in our stack trace request
this._stoppedThreadId = args.body.threadId;
if (this.debugAdapterTracker && this.debugAdapterTracker.onDidSendMessage) {
this.debugAdapterTracker.onDidSendMessage(args);
}
// Indicate we stopped at a breakpoint
this.breakpointEmitter.fire();
}
private onOutput(args: any): void {
traceInfo(JSON.stringify(args));
}
private onError(args: any): void {
traceInfo(JSON.stringify(args));
}
private onClose(): void {
if (this.socket) {
this.socket.end();
this.socket = undefined;
}
}
}