forked from microsoft/vscode
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvalidationProvider.ts
389 lines (348 loc) · 12.8 KB
/
validationProvider.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
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as cp from 'child_process';
import { NodeStringDecoder, StringDecoder } from 'string_decoder';
import * as vscode from 'vscode';
import { ThrottledDelayer } from './utils/async';
import * as nls from 'vscode-nls';
let localize = nls.loadMessageBundle();
export class LineDecoder {
private stringDecoder: NodeStringDecoder;
private remaining: string;
constructor(encoding: string = 'utf8') {
this.stringDecoder = new StringDecoder(encoding);
this.remaining = null;
}
public write(buffer: NodeBuffer): string[] {
var result: string[] = [];
var value = this.remaining
? this.remaining + this.stringDecoder.write(buffer)
: this.stringDecoder.write(buffer);
if (value.length < 1) {
return result;
}
var start = 0;
var ch: number;
while (start < value.length && ((ch = value.charCodeAt(start)) === 13 || ch === 10)) {
start++;
}
var idx = start;
while (idx < value.length) {
ch = value.charCodeAt(idx);
if (ch === 13 || ch === 10) {
result.push(value.substring(start, idx));
idx++;
while (idx < value.length && ((ch = value.charCodeAt(idx)) === 13 || ch === 10)) {
idx++;
}
start = idx;
} else {
idx++;
}
}
this.remaining = start < value.length ? value.substr(start) : null;
return result;
}
public end(): string {
return this.remaining;
}
}
enum RunTrigger {
onSave,
onType
}
namespace RunTrigger {
export let strings = {
onSave: 'onSave',
onType: 'onType'
};
export let from = function (value: string): RunTrigger {
if (value === 'onType') {
return RunTrigger.onType;
} else {
return RunTrigger.onSave;
}
};
}
const CheckedExecutablePath = 'php.validate.checkedExecutablePath';
export default class PHPValidationProvider {
private static MatchExpression: RegExp = /(?:(?:Parse|Fatal) error): (.*)(?: in )(.*?)(?: on line )(\d+)/;
private static BufferArgs: string[] = ['-l', '-n', '-d', 'display_errors=On', '-d', 'log_errors=Off'];
private static FileArgs: string[] = ['-l', '-n', '-d', 'display_errors=On', '-d', 'log_errors=Off', '-f'];
private validationEnabled: boolean;
private executableIsUserDefined: boolean;
private executable: string;
private trigger: RunTrigger;
private pauseValidation: boolean;
private documentListener: vscode.Disposable;
private diagnosticCollection: vscode.DiagnosticCollection;
private delayers: { [key: string]: ThrottledDelayer<void> };
private platform: string;
private runInShell: boolean = false;
private shellExecutable: string;
private shellArgs: string[] = [];
private isMsys: boolean = false;
constructor(private workspaceStore: vscode.Memento) {
this.executable = null;
this.validationEnabled = true;
this.trigger = RunTrigger.onSave;
this.pauseValidation = false;
this.platform = process.platform;
}
public activate(subscriptions: vscode.Disposable[]) {
this.diagnosticCollection = vscode.languages.createDiagnosticCollection();
subscriptions.push(this);
vscode.workspace.onDidChangeConfiguration(this.loadConfiguration, this, subscriptions);
this.loadConfiguration();
vscode.workspace.onDidOpenTextDocument(this.triggerValidate, this, subscriptions);
vscode.workspace.onDidCloseTextDocument((textDocument) => {
this.diagnosticCollection.delete(textDocument.uri);
delete this.delayers[textDocument.uri.toString()];
}, null, subscriptions);
subscriptions.push(vscode.commands.registerCommand('php.untrustValidationExecutable', this.untrustValidationExecutable, this));
}
public dispose(): void {
this.diagnosticCollection.clear();
this.diagnosticCollection.dispose();
}
private loadConfiguration(): void {
let section = vscode.workspace.getConfiguration('php');
let oldExecutable = this.executable;
if (section) {
this.validationEnabled = section.get<boolean>('validate.enable', true);
let inspect = section.inspect<string>('validate.executablePath');
if (inspect && inspect.workspaceValue) {
this.executable = inspect.workspaceValue;
this.executableIsUserDefined = false;
} else if (inspect && inspect.globalValue) {
this.executable = inspect.globalValue;
this.executableIsUserDefined = true;
} else {
this.executable = undefined;
this.executableIsUserDefined = undefined;
}
let shellSettings = section.get<any>('validate.runInShell');
if (typeof(shellSettings) === 'boolean') {
this.runInShell = shellSettings;
if (this.platform.toLowerCase() === 'win32') {
this.shellExecutable = 'C:\\WINDOWS\\system32\\cmd.exe';
this.shellArgs = ['/C'];
if (process.env.ComSpec) {
this.shellExecutable = process.env.ComSpec;
if (process.env.ComSpec.toLowerCase().indexof('powershell.exe') !== -1) {
this.shellArgs = ['/Command'];
} else if (process.env.ComSpec.toLowerCase().indexof('bash.exe') !== -1) {
this.shellArgs = ['-c'];
}
}
} else {
this.shellExecutable = process.env.SHELL || '/bin/bash';
this.shellArgs = ['-c'];
}
} else if (typeof(shellSettings) === 'object') {
this.runInShell = true;
if (shellSettings.shellExecutable && typeof(shellSettings.shellExecutable) === 'string') {
this.shellExecutable = shellSettings.shellExecutable;
}
if (shellSettings.shellArgs) {
if (typeof(shellSettings.shellArgs) === 'string') {
this.shellArgs = [shellSettings.shellArgs];
}
if (shellSettings.shellArgs instanceof Array) {
this.shellArgs = shellSettings.shellArgs.splice(0);
}
}
console.log('Run in shell?', this.runInShell);
console.log('Shell exec', this.shellExecutable);
console.log('Shell args', this.shellArgs);
}
// Is this native bash.exe?
// We inspect output from `bash.exe` and look for "msys" string.
// This tells us how we need to transform our file paths.
if (this.shellExecutable.toLowerCase().indexOf('bash.exe') !== -1) {
let inspectString = this.shellExecutable + ' --version';
let that = this;
cp.exec(inspectString, function (error, stdout, stderr) {
console.log('Inspecting bash.exe shell executable version', inspectString, stdout);
if (stdout.toLowerCase().indexOf('msys') !== -1) {
that.isMsys = true;
}
});
}
this.trigger = RunTrigger.from(section.get<string>('validate.run', RunTrigger.strings.onSave));
}
if (this.executableIsUserDefined !== true && this.workspaceStore.get<string>(CheckedExecutablePath, undefined) !== void 0) {
vscode.commands.executeCommand('setContext', 'php.untrustValidationExecutableContext', true);
}
this.delayers = Object.create(null);
if (this.pauseValidation) {
this.pauseValidation = oldExecutable === this.executable;
}
if (this.documentListener) {
this.documentListener.dispose();
}
this.diagnosticCollection.clear();
if (this.validationEnabled) {
if (this.trigger === RunTrigger.onType) {
this.documentListener = vscode.workspace.onDidChangeTextDocument((e) => {
this.triggerValidate(e.document);
});
} else {
this.documentListener = vscode.workspace.onDidSaveTextDocument(this.triggerValidate, this);
}
// Configuration has changed. Reevaluate all documents.
vscode.workspace.textDocuments.forEach(this.triggerValidate, this);
}
}
private untrustValidationExecutable() {
this.workspaceStore.update(CheckedExecutablePath, undefined);
vscode.commands.executeCommand('setContext', 'php.untrustValidationExecutableContext', false);
}
private triggerValidate(textDocument: vscode.TextDocument): void {
if (textDocument.languageId !== 'php' || this.pauseValidation || !this.validationEnabled) {
return;
}
interface MessageItem extends vscode.MessageItem {
id: string;
}
let trigger = () => {
let key = textDocument.uri.toString();
let delayer = this.delayers[key];
if (!delayer) {
delayer = new ThrottledDelayer<void>(this.trigger === RunTrigger.onType ? 250 : 0);
this.delayers[key] = delayer;
}
delayer.trigger(() => this.doValidate(textDocument));
};
if (this.executableIsUserDefined !== void 0 && !this.executableIsUserDefined) {
let checkedExecutablePath = this.workspaceStore.get<string>(CheckedExecutablePath, undefined);
if (!checkedExecutablePath || checkedExecutablePath !== this.executable) {
vscode.window.showInformationMessage<MessageItem>(
localize('php.useExecutablePath', 'Do you allow {0} (defined as a workspace setting) to be executed to lint PHP files?', this.executable),
{
title: localize('php.yes', 'Allow'),
id: 'yes'
},
{
title: localize('php.no', 'Disallow'),
isCloseAffordance: true,
id: 'no'
}
).then(selected => {
if (!selected || selected.id === 'no') {
this.pauseValidation = true;
} else if (selected.id === 'yes') {
this.workspaceStore.update(CheckedExecutablePath, this.executable);
vscode.commands.executeCommand('setContext', 'php.untrustValidationExecutableContext', true);
trigger();
}
});
return;
}
}
trigger();
}
private doValidate(textDocument: vscode.TextDocument): Promise<void> {
return new Promise<void>((resolve, reject) => {
let executable = this.executable || 'php';
let decoder = new LineDecoder();
let diagnostics: vscode.Diagnostic[] = [];
let processLine = (line: string) => {
let matches = line.match(PHPValidationProvider.MatchExpression);
if (matches) {
let message = matches[1];
let line = parseInt(matches[3]) - 1;
let diagnostic: vscode.Diagnostic = new vscode.Diagnostic(
new vscode.Range(line, 0, line, Number.MAX_VALUE),
message
);
diagnostics.push(diagnostic);
}
};
let options = vscode.workspace.rootPath ? { cwd: vscode.workspace.rootPath } : {};
let args: string[];
if (this.trigger === RunTrigger.onSave) {
args = PHPValidationProvider.FileArgs.slice(0);
args.push(textDocument.fileName);
} else {
args = PHPValidationProvider.BufferArgs;
}
// Are we validating with WSL?
if (this.runInShell) {
// Reset executable
let executableInShell = executable;
executable = this.shellExecutable;
console.log('Orig args', args);
// Shell args
let executableArgs = args.slice(0);
// If win32 and bash.exe, transform Windows file path to Linux file path
if (this.platform === 'win32' && executable.indexOf('bash.exe') !== -1) {
let windowsPath = executableArgs.pop();
let linuxPath = '';
if (this.isMsys) {
// Git Bash (msys) uses "/c/Users/..." filesystem mount
linuxPath = windowsPath.trim().replace(/^([a-zA-Z]):\\/, '/$1/').replace(/\\/g, '/');
} else {
// WSL Bash uses "/mnt/c/Users/..." filesystem mount
linuxPath = windowsPath.trim().replace(/^([a-zA-Z]):\\/, '/mnt/$1/').replace(/\\/g, '/');
}
executableArgs.push(linuxPath);
}
// Finalize executable args
args = this.shellArgs.concat(['"', executableInShell, executableArgs.join(' '), '"']);
console.log('Final args', args);
// Node spawn with shell
options['shell'] = true;
}
try {
let childProcess = cp.spawn(executable, args, options);
childProcess.on('error', (error: Error) => {
if (this.pauseValidation) {
resolve();
return;
}
this.showError(error, executable);
this.pauseValidation = true;
resolve();
});
if (childProcess.pid) {
if (this.trigger === RunTrigger.onType) {
childProcess.stdin.write(textDocument.getText());
childProcess.stdin.end();
}
childProcess.stdout.on('data', (data: Buffer) => {
decoder.write(data).forEach(processLine);
});
childProcess.stdout.on('end', () => {
let line = decoder.end();
if (line) {
processLine(line);
}
this.diagnosticCollection.set(textDocument.uri, diagnostics);
resolve();
});
} else {
resolve();
}
} catch (error) {
this.showError(error, executable);
}
});
}
private showError(error: any, executable: string): void {
let message: string = null;
if (error.code === 'ENOENT') {
if (this.executable) {
message = localize('wrongExecutable', 'Cannot validate since {0} is not a valid php executable. Use the setting \'php.validate.executablePath\' to configure the PHP executable.', executable);
} else {
message = localize('noExecutable', 'Cannot validate since no PHP executable is set. Use the setting \'php.validate.executablePath\' to configure the PHP executable.');
}
} else {
message = error.message ? error.message : localize('unknownReason', 'Failed to run php using path: {0}. Reason is unknown.', executable);
}
vscode.window.showInformationMessage(message);
}
}