forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbaseLinter.ts
More file actions
210 lines (186 loc) · 7.68 KB
/
baseLinter.ts
File metadata and controls
210 lines (186 loc) · 7.68 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import * as path from 'path';
import * as vscode from 'vscode';
import { IWorkspaceService } from '../common/application/types';
import { isTestExecution } from '../common/constants';
import '../common/extensions';
import { traceError } from '../common/logger';
import { IPythonToolExecutionService } from '../common/process/types';
import { ExecutionInfo, IConfigurationService, IPythonSettings, Product } from '../common/types';
import { IServiceContainer } from '../ioc/types';
import { ErrorHandler } from './errorHandlers/errorHandler';
import { ILinter, ILinterInfo, ILinterManager, ILintMessage, LinterId, LintMessageSeverity } from './types';
const namedRegexp = require('named-js-regexp');
// Allow negative column numbers (https://github.com/PyCQA/pylint/issues/1822)
// Allow codes with more than one letter (i.e. ABC123)
const REGEX = '(?<line>\\d+),(?<column>-?\\d+),(?<type>\\w+),(?<code>\\w+\\d+):(?<message>.*)\\r?(\\n|$)';
interface IRegexGroup {
line: number;
column: number;
code: string;
message: string;
type: string;
}
function matchNamedRegEx(data: string, regex: string): IRegexGroup | undefined {
const compiledRegexp = namedRegexp(regex, 'g');
const rawMatch = compiledRegexp.exec(data);
if (rawMatch !== null) {
return <IRegexGroup>rawMatch.groups();
}
return undefined;
}
export function parseLine(
line: string,
regex: string,
linterID: LinterId,
colOffset: number = 0,
): ILintMessage | undefined {
const match = matchNamedRegEx(line, regex)!;
if (!match) {
return;
}
match.line = Number(<any>match.line);
match.column = Number(<any>match.column);
return {
code: match.code,
message: match.message,
column: isNaN(match.column) || match.column <= 0 ? 0 : match.column - colOffset,
line: match.line,
type: match.type,
provider: linterID,
};
}
export abstract class BaseLinter implements ILinter {
protected readonly configService: IConfigurationService;
private errorHandler: ErrorHandler;
private _pythonSettings!: IPythonSettings;
private _info: ILinterInfo;
private workspace: IWorkspaceService;
protected get pythonSettings(): IPythonSettings {
return this._pythonSettings;
}
constructor(
product: Product,
protected readonly outputChannel: vscode.OutputChannel,
protected readonly serviceContainer: IServiceContainer,
protected readonly columnOffset = 0,
) {
this._info = serviceContainer.get<ILinterManager>(ILinterManager).getLinterInfo(product);
this.errorHandler = new ErrorHandler(this.info.product, outputChannel, serviceContainer);
this.configService = serviceContainer.get<IConfigurationService>(IConfigurationService);
this.workspace = serviceContainer.get<IWorkspaceService>(IWorkspaceService);
}
public get info(): ILinterInfo {
return this._info;
}
public async lint(document: vscode.TextDocument, cancellation: vscode.CancellationToken): Promise<ILintMessage[]> {
this._pythonSettings = this.configService.getSettings(document.uri);
return this.runLinter(document, cancellation);
}
protected getWorkspaceRootPath(document: vscode.TextDocument): string {
const workspaceFolder = this.workspace.getWorkspaceFolder(document.uri);
const workspaceRootPath =
workspaceFolder && typeof workspaceFolder.uri.fsPath === 'string' ? workspaceFolder.uri.fsPath : undefined;
return typeof workspaceRootPath === 'string' ? workspaceRootPath : path.dirname(document.uri.fsPath);
}
protected getWorkingDirectoryPath(document: vscode.TextDocument): string {
return this._pythonSettings.linting.cwd || this.getWorkspaceRootPath(document);
}
protected abstract runLinter(
document: vscode.TextDocument,
cancellation: vscode.CancellationToken,
): Promise<ILintMessage[]>;
protected parseMessagesSeverity(error: string, categorySeverity: any): LintMessageSeverity {
if (categorySeverity[error]) {
const severityName = categorySeverity[error];
switch (severityName) {
case 'Error':
return LintMessageSeverity.Error;
case 'Hint':
return LintMessageSeverity.Hint;
case 'Information':
return LintMessageSeverity.Information;
case 'Warning':
return LintMessageSeverity.Warning;
default: {
if (LintMessageSeverity[severityName]) {
return <LintMessageSeverity>(<any>LintMessageSeverity[severityName]);
}
}
}
}
return LintMessageSeverity.Information;
}
protected async run(
args: string[],
document: vscode.TextDocument,
cancellation: vscode.CancellationToken,
regEx: string = REGEX,
): Promise<ILintMessage[]> {
if (!this.info.isEnabled(document.uri)) {
return [];
}
const executionInfo = this.info.getExecutionInfo(args, document.uri);
const cwd = this.getWorkingDirectoryPath(document);
const pythonToolsExecutionService = this.serviceContainer.get<IPythonToolExecutionService>(
IPythonToolExecutionService,
);
try {
const result = await pythonToolsExecutionService.exec(
executionInfo,
{ cwd, token: cancellation, mergeStdOutErr: false },
document.uri,
);
this.displayLinterResultHeader(result.stdout);
return await this.parseMessages(result.stdout, document, cancellation, regEx);
} catch (error) {
await this.handleError(error, document.uri, executionInfo);
return [];
}
}
protected async parseMessages(
output: string,
_document: vscode.TextDocument,
_token: vscode.CancellationToken,
regEx: string,
) {
const outputLines = output.splitLines({ removeEmptyEntries: false, trim: false });
return this.parseLines(outputLines, regEx);
}
protected async handleError(error: Error, resource: vscode.Uri, execInfo: ExecutionInfo) {
if (isTestExecution()) {
this.errorHandler.handleError(error, resource, execInfo).ignoreErrors();
} else {
this.errorHandler
.handleError(error, resource, execInfo)
.catch((ex) => traceError('Error in errorHandler.handleError', ex))
.ignoreErrors();
}
}
private parseLine(line: string, regEx: string): ILintMessage | undefined {
return parseLine(line, regEx, this.info.id, this.columnOffset);
}
private parseLines(outputLines: string[], regEx: string): ILintMessage[] {
const messages: ILintMessage[] = [];
for (const line of outputLines) {
try {
const msg = this.parseLine(line, regEx);
if (msg) {
messages.push(msg);
if (messages.length >= this.pythonSettings.linting.maxNumberOfProblems) {
break;
}
}
} catch (ex) {
traceError(`Linter '${this.info.id}' failed to parse the line '${line}.`, ex);
}
}
return messages;
}
private displayLinterResultHeader(data: string) {
this.outputChannel.append(`${'#'.repeat(10)}Linting Output - ${this.info.id}${'#'.repeat(10)}\n`);
this.outputChannel.append(data);
}
}