forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
baseLinter.ts
173 lines (153 loc) · 7.29 KB
/
baseLinter.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
import * as path from 'path';
import * as vscode from 'vscode';
import { IWorkspaceService } from '../common/application/types';
import '../common/extensions';
import { IPythonToolExecutionService } from '../common/process/types';
import { ExecutionInfo, IConfigurationService, ILogger, IPythonSettings, Product } from '../common/types';
import { IServiceContainer } from '../ioc/types';
import { ErrorHandler } from './errorHandlers/errorHandler';
import { ILinter, ILinterInfo, ILinterManager, ILintMessage, LintMessageSeverity } from './types';
// tslint:disable-next-line:no-require-imports no-var-requires
const namedRegexp = require('named-js-regexp');
// Allow negative column numbers (https://github.com/PyCQA/pylint/issues/1822)
const REGEX = '(?<line>\\d+),(?<column>-?\\d+),(?<type>\\w+),(?<code>\\w\\d+):(?<message>.*)\\r?(\\n|$)';
export interface IRegexGroup {
line: number;
column: number;
code: string;
message: string;
type: string;
}
export function matchNamedRegEx(data, regex): IRegexGroup | undefined {
const compiledRegexp = namedRegexp(regex, 'g');
const rawMatch = compiledRegexp.exec(data);
if (rawMatch !== null) {
return <IRegexGroup>rawMatch.groups();
}
return undefined;
}
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 isLinterExecutableSpecified(resource: vscode.Uri) {
const executablePath = this.info.pathName(resource);
return path.basename(executablePath).length > 0 && path.basename(executablePath) !== executablePath;
}
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 get logger(): ILogger {
return this.serviceContainer.get<ILogger>(ILogger);
}
protected abstract runLinter(document: vscode.TextDocument, cancellation: vscode.CancellationToken): Promise<ILintMessage[]>;
// tslint:disable-next-line:no-any
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]) {
// tslint:disable-next-line:no-any
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.getWorkspaceRootPath(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) {
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 handleError(error: Error, resource: vscode.Uri, execInfo: ExecutionInfo) {
this.errorHandler.handleError(error, resource, execInfo)
.catch(this.logger.logError.bind(this, 'Error in errorHandler.handleError'));
}
private parseLine(line: string, regEx: string): ILintMessage | undefined {
const match = matchNamedRegEx(line, regEx)!;
if (!match) {
return;
}
// tslint:disable-next-line:no-any
match.line = Number(<any>match.line);
// tslint:disable-next-line:no-any
match.column = Number(<any>match.column);
return {
code: match.code,
message: match.message,
column: isNaN(match.column) || match.column <= 0 ? 0 : match.column - this.columnOffset,
line: match.line,
type: match.type,
provider: this.info.id
};
}
private parseLines(outputLines: string[], regEx: string): ILintMessage[] {
return outputLines
.filter((value, index) => index <= this.pythonSettings.linting.maxNumberOfProblems)
.map(line => {
try {
const msg = this.parseLine(line, regEx);
if (msg) {
return msg;
}
} catch (ex) {
this.logger.logError(`Linter '${this.info.id}' failed to parse the line '${line}.`, ex);
}
return;
})
.filter(item => item !== undefined)
.map(item => item!);
}
private displayLinterResultHeader(data: string) {
this.outputChannel.append(`${'#'.repeat(10)}Linting Output - ${this.info.id}${'#'.repeat(10)}\n`);
this.outputChannel.append(data);
}
}