forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbaseLinter.ts
More file actions
192 lines (170 loc) · 7.59 KB
/
baseLinter.ts
File metadata and controls
192 lines (170 loc) · 7.59 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
// 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 { 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,
LinterId, LintMessageSeverity
} from './types';
// tslint:disable-next-line:no-require-imports no-var-requires no-any
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: 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;
}
// 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 - 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 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) {
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(this.logger.logError.bind(this, 'Error in errorHandler.handleError'))
.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) {
this.logger.logError(`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);
}
}