This repository has been archived by the owner on Mar 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
tidy.ts
311 lines (263 loc) · 9.62 KB
/
tidy.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
import { ChildProcess, execFile, execFileSync } from "child_process";
import * as vscode from "vscode";
import * as jsYaml from "js-yaml";
function clangTidyArgs(files: string[], fixErrors: boolean) {
let args: string[] = [...files, "--export-fixes=-"];
const checks = vscode.workspace
.getConfiguration("clang-tidy")
.get("checks") as Array<string>;
if (checks.length > 0) {
args.push(`--checks=${checks.join(",")}`);
}
const compilerArgs = vscode.workspace
.getConfiguration("clang-tidy")
.get("compilerArgs") as Array<string>;
compilerArgs.forEach((arg) => {
args.push(`--extra-arg=${arg}`);
});
const compilerArgsBefore = vscode.workspace
.getConfiguration("clang-tidy")
.get("compilerArgsBefore") as Array<string>;
compilerArgsBefore.forEach((arg) => {
args.push(`--extra-arg-before=${arg}`);
});
const buildPath = vscode.workspace
.getConfiguration("clang-tidy")
.get("buildPath") as string;
if (buildPath.length > 0) {
args.push(`-p=${buildPath}`);
}
if (fixErrors) {
args.push("--fix");
}
return args;
}
function clangTidyExecutable() {
return vscode.workspace
.getConfiguration("clang-tidy")
.get("executable") as string;
}
class ChildProcessWithExitFlag {
constructor(process: ChildProcess) {
this.process = process;
this.exited = false;
process.on("exit", () => (this.exited = true));
}
process: ChildProcess;
exited: boolean;
}
let clangTidyProcess: ChildProcessWithExitFlag | undefined = undefined;
export function killClangTidy() {
if (
clangTidyProcess === undefined ||
clangTidyProcess.exited ||
clangTidyProcess.process.killed
) {
return;
}
// process.kill() does not work on Windows for some reason.
// We can use the taskkill command instead.
if (process.platform === "win32") {
const pid = clangTidyProcess.process.pid.toString();
execFileSync("taskkill", ["/pid", pid, "/f", "/t"]);
clangTidyProcess.process.killed = true;
} else {
clangTidyProcess.process.kill();
}
}
export function runClangTidy(
files: string[],
workingDirectory: string,
loggingChannel: vscode.OutputChannel,
fixErrors: boolean
): Promise<string> {
killClangTidy();
const progressMessage = fixErrors
? "Linting and fixing current file (do not modify it in the meanwhile)..."
: "Linting current file...";
return new Promise((resolve) => {
const clangTidy = clangTidyExecutable();
const args = clangTidyArgs(files, fixErrors);
loggingChannel.appendLine(`> ${clangTidy} ${args.join(" ")}`);
loggingChannel.appendLine(`Working Directory: ${workingDirectory}`);
vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification },
async (progress) => {
progress.report({ message: progressMessage });
await new Promise((res, rej) => {
clangTidyProcess = new ChildProcessWithExitFlag(
execFile(
clangTidy,
args,
{ cwd: workingDirectory },
(error, stdout, stderr) => {
loggingChannel.appendLine(stdout);
loggingChannel.appendLine(stderr);
resolve(stdout);
res();
}
)
);
});
}
);
});
}
interface ClangTidyResults {
MainSourceFile: string;
Diagnostics: ClangTidyDiagnostic[];
}
interface ClangTidyDiagnostic {
DiagnosticName: string;
DiagnosticMessage: {
Message: string;
FilePath: string;
FileOffset: number;
Replacements: ClangTidyReplacements[];
Severity: vscode.DiagnosticSeverity | vscode.DiagnosticSeverity.Warning;
};
}
interface ClangTidyReplacements {
FilePath: string;
Offset: number;
Length: number;
ReplacementText: string;
}
interface ClangTidyYaml {
MainSourceFile: string;
Diagnostics: [
{
DiagnosticName: string;
// Old style diagnostic info. For older versions of clang-tidy
Message?: string;
FilePath?: string;
FileOffset?: number;
Replacements?: ClangTidyReplacements[];
// Newer style diagnostic info. For newer versions of clang-tidy
DiagnosticMessage?: {
Message: string;
FilePath: string;
FileOffset: number;
Replacements: ClangTidyReplacements[];
};
}
];
}
function tidyOutputAsObject(clangTidyOutput: string) {
const yamlIndex = clangTidyOutput.search(/^---$/m);
if (yamlIndex < 0) {
return { MainSourceFile: "", Diagnostics: [] };
}
const rawYaml = clangTidyOutput.substr(yamlIndex);
const tidyResults = jsYaml.safeLoad(rawYaml) as ClangTidyYaml;
let structuredResults: ClangTidyResults = {
MainSourceFile: tidyResults.MainSourceFile,
Diagnostics: [],
};
tidyResults.Diagnostics.forEach((diag) => {
if (diag.DiagnosticMessage) {
structuredResults.Diagnostics.push({
DiagnosticName: diag.DiagnosticName,
DiagnosticMessage: {
Message: diag.DiagnosticMessage.Message,
FilePath: diag.DiagnosticMessage.FilePath,
FileOffset: diag.DiagnosticMessage.FileOffset,
Replacements: diag.DiagnosticMessage.Replacements,
Severity: vscode.DiagnosticSeverity.Warning,
},
});
} else if (diag.Message && diag.FilePath && diag.FileOffset) {
structuredResults.Diagnostics.push({
DiagnosticName: diag.DiagnosticName,
DiagnosticMessage: {
Message: diag.Message,
FilePath: diag.FilePath,
FileOffset: diag.FileOffset,
Replacements: diag.Replacements ? diag.Replacements : [],
Severity: vscode.DiagnosticSeverity.Warning,
},
});
}
});
let diagnostics = structuredResults.Diagnostics;
const severities = collectDiagnosticSeverities(clangTidyOutput);
for (let i = 0; i < diagnostics.length || i < severities.length; i++) {
diagnostics[i].DiagnosticMessage.Severity = severities[i];
}
return structuredResults;
}
export function collectDiagnostics(
clangTidyOutput: string,
document: vscode.TextDocument
) {
let results: vscode.Diagnostic[] = [];
const tidyResults = tidyOutputAsObject(clangTidyOutput);
tidyResults.Diagnostics.forEach((diag) => {
const diagnosticMessage = diag.DiagnosticMessage;
// We make these paths relative before comparing them because
// on Windows, the drive letter is lowercase for the document filename,
// but uppercase for the diagnostic message file path. This caused the
// comparison to fail when it shouldn't.
if (
vscode.workspace.asRelativePath(document.fileName) !==
vscode.workspace.asRelativePath(diagnosticMessage.FilePath)
) {
return; // The message isn't related to current file
}
if (diagnosticMessage.Replacements.length > 0) {
diagnosticMessage.Replacements.forEach((replacement) => {
const beginPos = document.positionAt(replacement.Offset);
const endPos = document.positionAt(
replacement.Offset + replacement.Length
);
const diagnostic = {
range: new vscode.Range(beginPos, endPos),
severity: diagnosticMessage.Severity,
message: diagnosticMessage.Message,
code: diag.DiagnosticName,
source: "clang-tidy",
};
results.push(diagnostic);
});
} else {
const line = document.positionAt(diagnosticMessage.FileOffset).line;
results.push({
range: new vscode.Range(line, 0, line, Number.MAX_VALUE),
severity: diagnosticMessage.Severity,
message: diagnosticMessage.Message,
code: diag.DiagnosticName,
source: "clang-tidy",
});
}
});
return results;
}
function collectDiagnosticSeverities(clangTidyOutput: string) {
const data = clangTidyOutput.split("\n");
const regex: RegExp = /^.*:\d+:\d+:\s+(warning|error|info|hint):\s+.*$/;
let severities: vscode.DiagnosticSeverity[] = [];
data.forEach((line) => {
const matches = regex.exec(line);
if (matches === null) {
return;
}
switch (matches[1]) {
case "error":
severities.push(vscode.DiagnosticSeverity.Error);
break;
case "warning":
severities.push(vscode.DiagnosticSeverity.Warning);
break;
case "info":
severities.push(vscode.DiagnosticSeverity.Information);
break;
case "hint":
severities.push(vscode.DiagnosticSeverity.Hint);
break;
default:
severities.push(vscode.DiagnosticSeverity.Warning);
break;
}
});
return severities;
}