-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathextension.ts
More file actions
451 lines (405 loc) · 14.8 KB
/
extension.ts
File metadata and controls
451 lines (405 loc) · 14.8 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as process from 'process';
import * as fs from 'fs';
import * as path from 'path';
import { Uri } from 'vscode';
import { getProgFlowVizCallback } from './programflow-visualization/main';
import { initTraceCache } from './programflow-visualization/trace_cache';
const extensionId = 'write-your-python-program';
const python3ConfigKey = 'python3Cmd';
const verboseConfigKey = 'verbose';
const debugConfigKey = 'debug';
const disableTypecheckingConfigKey = 'disableTypechecking';
const isWindows = process.platform === "win32";
const exeExt = isWindows ? ".exe" : "";
const disposables: vscode.Disposable[] = [];
const buttons: vscode.StatusBarItem[] = [];
function installButton(title: string, cmd: string | undefined) {
const runButton = vscode.window.createStatusBarItem(1, 0);
runButton.text = title;
if (cmd) {
runButton.command = cmd;
}
buttons.push(runButton);
disposables.push(runButton);
}
function hideButtons() {
buttons.forEach(b => {
b.hide();
});
}
function showButtons() {
buttons.forEach(b => {
b.show();
});
}
async function startTerminal(
existing: vscode.Terminal | undefined, name: string, cmd: string
): Promise<vscode.Terminal> {
if (existing) {
existing.dispose();
}
const terminalOptions: vscode.TerminalOptions = {name: name};
if (isWindows) {
// We don't know which shell will be used by default.
// If PowerShell is the default, we need to prefix the command with "& ".
// Otherwise, the prefix is not allowed and results in a syntax error.
// -> Just force cmd.exe.
terminalOptions.shellPath = "cmd.exe";
}
const terminal = vscode.window.createTerminal(terminalOptions);
// Sometimes the terminal takes some time to start up before it can start accepting input.
await new Promise((resolve) => setTimeout(resolve, 100));
terminal.show(false); // focus the terminal
terminal.sendText(cmd);
return terminal;
}
/**
* Appropriately formats a string so it can be used as an argument for a command in a shell.
* E.g. if an argument contains a space, then it will be enclosed within double quotes.
* @param {String} value.
*/
function toCommandArgument(s: string): string {
if (!s) {
return s;
}
return s.indexOf(' ') >= 0 && !s.startsWith('"') && !s.endsWith('"') ? `"${s}"` : s.toString();
};
/**
* Appropriately formats a a file path so it can be used as an argument for a command in a shell.
* E.g. if an argument contains a space, then it will be enclosed within double quotes.
*/
function fileToCommandArgument(s: string): string {
if (!s) {
return s;
}
return toCommandArgument(s).replace(/\\/g, '/');
}
function commandListToArgument(arr: string[]): string {
if (arr.length === 1) {
return fileToCommandArgument(arr[0]);
} else {
var result = "";
for (let i = 0; i < arr.length; i++) {
if (i === 0) {
result = fileToCommandArgument(arr[i]);
} else {
result = result + " " + toCommandArgument(arr[i]);
}
}
return result;
}
}
function showHideButtons(textEditor: vscode.TextEditor | undefined) {
if (!textEditor) {
hideButtons();
return;
}
const fileName = textEditor.document.fileName;
if (fileName.endsWith('.py')) {
showButtons();
} else {
hideButtons();
}
}
function installCmd(
context: vscode.ExtensionContext,
cmdId: string,
buttonTitle: string,
callback: (cmdId: string) => void
) {
cmdId = extensionId + "." + cmdId;
let disposable = vscode.commands.registerCommand(cmdId, () => callback(cmdId));
disposables.push(disposable);
context.subscriptions.push(disposable);
installButton(buttonTitle, cmdId);
}
function initProgramFlowVisualization(context: vscode.ExtensionContext, outChannel: vscode.OutputChannel) {
initTraceCache(context);
const cmdId = extensionId + ".programflow-visualization";
let disposable = vscode.commands.registerCommand(cmdId, getProgFlowVizCallback(context, outChannel));
disposables.push(disposable);
context.subscriptions.push(disposable);
installButton("$(debug-alt-small) Visualize", cmdId);
}
type PythonCmdResult = {
kind: "success", cmd: string[]
} | {
kind: "error", msg: string
} | {
kind: "warning", msg: string, cmd: string[]
};
export function getPythonCmd(ext: PythonExtension): PythonCmdResult {
const config = vscode.workspace.getConfiguration(extensionId);
const hasConfig = config && config[python3ConfigKey];
if (hasConfig) {
// explicitly configured for wypp (should we deprecate this?)
let configCmd: string= config[python3ConfigKey];
configCmd = configCmd.trim();
if (isWindows && !configCmd.endsWith(exeExt)) {
configCmd = configCmd + exeExt;
}
console.log("Found python command in wypp settings: " + configCmd);
if (path.isAbsolute(configCmd)) {
if (fs.existsSync(configCmd)) {
return {
kind: "success",
cmd: [configCmd]
};
} else {
return {
kind: "error",
msg: "Path " + configCmd + " does not exist."
};
}
} else {
return { kind: 'success', cmd: [configCmd] };
}
} else {
const cmd = ext.getPythonCommand();
if (cmd) {
console.log("Using the configured python command " + cmd);
return {
kind: 'success',
cmd
};
}
// The pythonPath configuration has been deprecated, see
// https://devblogs.microsoft.com/python/python-in-visual-studio-code-july-2021-release/
const pyConfig = vscode.workspace.getConfiguration("python");
const pyExtPyPath: string | undefined = pyConfig.get("pythonPath");
if (pyExtPyPath) {
console.log("Using python command from pythonPath setting (deprecated): " + pyExtPyPath);
return {
kind: 'success',
cmd: [pyExtPyPath]
};
} else {
const pythonCmd = isWindows ? ('python' + exeExt) : 'python3';
console.log("Using the default python command: " + pythonCmd);
return {
kind: 'success',
cmd: [pythonCmd]
};
}
}
}
function beVerbose(context: vscode.ExtensionContext): boolean {
const config = vscode.workspace.getConfiguration(extensionId);
return !!config[verboseConfigKey];
}
function isDebug(context: vscode.ExtensionContext): boolean {
const config = vscode.workspace.getConfiguration(extensionId);
return !!config[debugConfigKey];
}
function disableTypechecking(context: vscode.ExtensionContext): boolean {
const config = vscode.workspace.getConfiguration(extensionId);
return !!config[disableTypecheckingConfigKey];
}
async function fixPylanceConfig(
context: vscode.ExtensionContext,
folder?: vscode.WorkspaceFolder
) {
// disable warnings about wildcard imports, set pylance's extraPaths to wypp
// turn typechecking off
// This is a quite distructive change, so we do it on first hit of the run button
// not on-load of the plugin
const libDir = context.asAbsolutePath('python/code/');
const cfg = vscode.workspace.getConfiguration('python', folder?.uri);
const target = folder ? vscode.ConfigurationTarget.WorkspaceFolder
: vscode.ConfigurationTarget.Workspace;
// wildcard warnings
const keyOverride = 'analysis.diagnosticSeverityOverrides';
const overrides = cfg.get<Record<string, string>>(keyOverride) ?? {};
if (overrides.reportWildcardImportFromLibrary !== 'none') {
const updated = {
...overrides,
reportWildcardImportFromLibrary: 'none',
};
await cfg.update(
'analysis.diagnosticSeverityOverrides',
updated,
target
);
}
// extraPaths
const keyExtraPaths = 'analysis.extraPaths';
const extra = cfg.get<string[]>(keyExtraPaths) ?? [];
if (extra.length !== 1 || extra[0] !== libDir) {
await cfg.update(
keyExtraPaths,
[libDir],
target
);
}
// typechecking off
const keyMode = 'analysis.typeCheckingMode';
const mode = cfg.get<string>(keyMode) ?? '';
if (mode !== 'off') {
await cfg.update(
'analysis.typeCheckingMode',
'off',
target
);
}
}
class Location implements vscode.TerminalLink {
constructor(
public startIndex: number,
public length: number,
public tooltip: string | undefined,
public filePath: string,
public line: number
) { }
}
const linkPrefixes = ['declared at: ', 'caused by: '];
function findLink(dir: string, ctxLine: string): Location | undefined {
for (const pref of linkPrefixes) {
if (ctxLine.startsWith(pref)) {
const link = ctxLine.substr(pref.length).trim();
const i = link.indexOf(':');
if (i < 0 || i >= link.length - 1) {
return undefined;
}
const file = link.substr(0, i);
const line = parseInt(link.substr(i + 1));
if (file && file.length > 1 && !isNaN(line)) {
const p = path.join(dir, file);
const loc = new Location(pref.length, link.length, undefined, p, line);
// console.debug("Find link " + p + ":" + line);
return loc;
} else {
return undefined;
}
}
}
return undefined;
}
interface TerminalContext {
directory: string,
terminal: vscode.Terminal
}
type TerminalMap = { [name: string]: TerminalContext };
class TerminalLinkProvider implements vscode.TerminalLinkProvider {
constructor(private terminals: TerminalMap) {}
provideTerminalLinks(context: vscode.TerminalLinkContext, token: vscode.CancellationToken): vscode.ProviderResult<Location[]> {
let directory: string | undefined;
for (const [_key, term] of Object.entries(this.terminals)) {
if (context.terminal === term.terminal) {
directory = term.directory;
break;
}
}
if (directory === undefined) {
return [];
}
const loc = findLink(directory, context.line);
if (loc) {
return [loc];
} else {
return [];
}
}
handleTerminalLink(loc: Location): vscode.ProviderResult<void> {
console.log("Opening " + loc.filePath);
vscode.commands.executeCommand('vscode.open', Uri.file(loc.filePath)).then(() => {
const editor = vscode.window.activeTextEditor;
if (!editor) { return; }
let line = loc.line - 1;
if (line < 0) {
line = 0;
}
const col = 0;
editor.selection = new vscode.Selection(line, col, line, col);
editor.revealRange(new vscode.Range(line, 0, line, 10000));
});
}
}
export class PythonExtension {
private pyApi: any;
constructor() {
const pyExt = vscode.extensions.getExtension('ms-python.python');
this.pyApi = pyExt?.exports;
}
getPythonCommand(): string[] | undefined {
return this.pyApi?.settings?.getExecutionDetails()?.execCommand;
}
}
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export async function activate(context: vscode.ExtensionContext) {
disposables.forEach(d => d.dispose());
console.log('Activating extension ' + extensionId);
const outChannel = vscode.window.createOutputChannel("Write Your Python Program");
disposables.push(outChannel);
const terminals: { [name: string]: TerminalContext } = {};
installButton("Write Your Python Program", undefined);
const linkProvider = new TerminalLinkProvider(terminals);
const pyExt = new PythonExtension();
const runProg = context.asAbsolutePath('python/code/wypp/runYourProgram.py');
installCmd(
context,
"run",
"▶ RUN",
async (cmdId) => {
await fixPylanceConfig(context);
const file =
(vscode.window.activeTextEditor) ?
vscode.window.activeTextEditor.document.fileName :
undefined;
if (!file) {
vscode.window.showWarningMessage('No file is open');
return;
}
if (!file.endsWith('.py')) {
vscode.window.showWarningMessage('Not a python file');
return;
}
await vscode.window.activeTextEditor?.document.save();
const pyCmd = getPythonCmd(pyExt);
let verboseOpt = "";
if (isDebug(context)) {
verboseOpt = "--debug";
} else if (beVerbose(context)) {
verboseOpt = "--verbose";
}
if (verboseOpt !== "") {
verboseOpt = " " + verboseOpt + " --no-clear";
}
const disableOpt = disableTypechecking(context) ? " --no-typechecking" : "";
if (pyCmd.kind !== "error") {
const pythonCmd = commandListToArgument(pyCmd.cmd);
const cmdTerm = await startTerminal(
terminals[cmdId]?.terminal,
"WYPP - RUN",
pythonCmd + " " + fileToCommandArgument(runProg) + verboseOpt +
disableOpt +
" --interactive " +
" --change-directory " +
fileToCommandArgument(file)
);
terminals[cmdId] = {terminal: cmdTerm, directory: path.dirname(file)};
if (pyCmd.kind === "warning") {
vscode.window.showInformationMessage(pyCmd.msg);
}
} else {
vscode.window.showWarningMessage(pyCmd.msg);
}
}
);
initProgramFlowVisualization(context, outChannel);
vscode.window.onDidChangeActiveTextEditor(showHideButtons);
showHideButtons(vscode.window.activeTextEditor);
const linkDisposable = vscode.window.registerTerminalLinkProvider(linkProvider);
disposables.push(linkDisposable);
context.subscriptions.push(linkDisposable);
}
// this method is called when your extension is deactivated
export function deactivate() {
console.log('Deactivating extension write-your-program');
disposables.forEach(d => d.dispose());
buttons.splice(0, buttons.length);
disposables.splice(0, disposables.length);
}