-
Notifications
You must be signed in to change notification settings - Fork 7
/
validator.ts
256 lines (217 loc) · 7.46 KB
/
validator.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
import {
CancellationTokenSource,
ConfigurationChangeEvent,
Diagnostic,
DiagnosticCollection,
DiagnosticSeverity,
Disposable,
languages,
Range,
TextDocument,
TextDocumentChangeEvent,
Uri,
window,
workspace,
} from 'vscode';
import { exec, ChildProcess, spawn } from 'child_process';
import { PHPCSReport, PHPCSMessageType } from './phpcs-report';
import { debounce } from 'lodash';
const enum runConfig {
save = 'onSave',
type = 'onType',
}
/**
* Kills PHP CLIs.
*
* This is needed for Windows since ChildProcess.kill() only kills the spawner
* cmd.exe, even with `taskkill /T /F /pid ${pid}` where /T is supposed to kill
* trees from the spawner but it seems the php process is launched in a
* disconnected way.
*
* @param command
* The process to kill.
*/
function phpCliKill(command: ChildProcess, processName: string) {
if (process.platform === 'win32' && workspace.getConfiguration('phpSniffer').get('windowsHardkill')) {
// Whole code block below could be more succinctly done with:
// `taskkill /v /fi "cputime gt 00:00:02" /fi "cputime lt 00:00:10" /fi "sessionname eq Console" /im ${processName}`
// but `cputime gt` filter does not seem to work in this case.
exec(
`tasklist /v /fi "cputime ge 00:00:02" /fi "cputime lt 00:00:10" /fi "imagename eq ${processName}" /fi "sessionname eq Console" /fo csv`,
(err, stdout) => {
if (err) window.showErrorMessage('PHPCS: Error trying to kill PHP CLI, you may need to kill the process yourself.');
if (stdout.includes('","')) {
const pids = stdout.split('\n').slice(1).map(row => {
const [, pid] = row.substr(1, row.length - 2).split('","');
return pid;
});
exec(`taskkill /F ${pids.map(pid => `/pid ${pid}`).join(' ')}`);
}
},
);
}
command.kill();
}
export class Validator {
private diagnosticCollection: DiagnosticCollection = languages.createDiagnosticCollection('php');
/**
* The active validator listener.
*/
private validatorListener?: Disposable;
/**
* Token to cancel a current validation runs.
*/
private runnerCancellations: Map<Uri, CancellationTokenSource> = new Map();
constructor(subscriptions: Disposable[]) {
workspace.onDidChangeConfiguration(this.onConfigChange, this, subscriptions);
workspace.onDidOpenTextDocument(this.validate, this, subscriptions);
workspace.onDidCloseTextDocument(this.clearDocumentDiagnostics, this, subscriptions);
workspace.onDidChangeWorkspaceFolders(this.refresh, this, subscriptions);
this.refresh();
this.setValidatorListener();
}
/**
* Dispose this object.
*/
public dispose(): void {
this.diagnosticCollection.clear();
this.diagnosticCollection.dispose();
}
/**
* Reacts on configuration change.
*
* @param event - The configuration change event.
*/
protected onConfigChange(event: ConfigurationChangeEvent): void {
if (!event.affectsConfiguration('phpSniffer')) {
return;
}
if (event.affectsConfiguration('phpSniffer.run') || event.affectsConfiguration('phpSniffer.onTypeDelay')) {
this.setValidatorListener();
}
this.refresh();
}
/**
* Sets the validation event listening.
*/
protected setValidatorListener(): void {
if (this.validatorListener) {
this.validatorListener.dispose();
}
const config = workspace.getConfiguration('phpSniffer');
const run: runConfig = config.get('run', runConfig.save);
const delay: number = config.get('onTypeDelay', 250);
if (run === runConfig.type as string) {
const validator = debounce(
({ document }: TextDocumentChangeEvent): void => { this.validate(document); },
delay,
);
this.validatorListener = workspace.onDidChangeTextDocument(validator);
}
else {
this.validatorListener = workspace.onDidSaveTextDocument(this.validate, this);
}
}
/**
* Refreshes validation on any open documents.
*/
protected refresh(): void {
this.diagnosticCollection!.clear();
workspace.textDocuments.forEach(this.validate, this);
}
/**
* Lints a document.
*
* @param document - The document to lint.
*/
protected validate(document: TextDocument): void {
if (document.languageId !== 'php') {
return;
}
const oldRunner = this.runnerCancellations.get(document.uri);
if (oldRunner) {
oldRunner.cancel();
oldRunner.dispose();
}
const runner = new CancellationTokenSource();
this.runnerCancellations.set(document.uri, runner);
const { token } = runner;
const config = workspace.getConfiguration('phpSniffer', document.uri);
const execFolder: string = config.get('executablesFolder', '');
const standard: string = config.get('standard', '');
const windowsKillTarget: string = config.get('windowsPhpCli', 'php.exe');
const args = [
'--report=json',
`--standard="${standard}"`,
'-q',
];
if (document.uri.scheme === 'file') {
args.push(`--stdin-path="${document.uri.fsPath}"`);
}
args.push('-');
const spawnOptions = {
cwd: workspace.workspaceFolders && workspace.workspaceFolders[0].uri.scheme === 'file'
? workspace.workspaceFolders[0].uri.fsPath
: undefined,
shell: process.platform === 'win32',
};
const command = spawn(`${execFolder} phpcs`, args, spawnOptions);
token.onCancellationRequested(() => !command.killed && phpCliKill(command, windowsKillTarget));
let stdout = '';
let stderr = '';
command.stdin.write(document.getText());
command.stdin.end();
command.stdout.setEncoding('utf8');
command.stdout.on('data', data => stdout += data);
command.stderr.on('data', data => stderr += data);
const done = new Promise((resolve, reject) => {
command.on('close', () => {
if (token.isCancellationRequested || !stdout) {
resolve();
}
else {
const diagnostics: Diagnostic[] = [];
try {
const { files }: PHPCSReport = JSON.parse(stdout);
for (const file in files) {
files[file].messages.forEach(({ message, line, column, type, source }) => {
const zeroLine = line - 1;
const ZeroColumn = column - 1;
diagnostics.push(
new Diagnostic(
new Range(zeroLine, ZeroColumn, zeroLine, ZeroColumn),
`[${source}]\n${message}`,
type === PHPCSMessageType.ERROR ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning,
),
);
});
}
resolve();
} catch (error) {
let message = '';
if (stdout) message += `${stdout}\n`;
if (stderr) message += `${stderr}\n`;
message += error.toString();
console.error(`PHPCS: ${message}`);
reject(message);
}
this.diagnosticCollection.set(document.uri, diagnostics);
}
runner.dispose();
this.runnerCancellations.delete(document.uri);
});
});
setTimeout(() => {
!command.killed && phpCliKill(command, windowsKillTarget);
}, 3000);
window.setStatusBarMessage('PHP Sniffer: validating…', done);
}
/**
* Clears diagnostics from a document.
*
* @param document - The document to clear diagnostics of.
*/
protected clearDocumentDiagnostics({ uri }: TextDocument): void {
this.diagnosticCollection.delete(uri);
}
}