This repository has been archived by the owner on Aug 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
main.js
265 lines (231 loc) · 7.85 KB
/
main.js
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
'use babel';
// eslint-disable-next-line import/extensions, import/no-extraneous-dependencies
import { CompositeDisposable } from 'atom';
import path from 'path';
import fs from 'fs';
const TSLINT_MODULE_NAME = 'tslint';
const grammarScopes = ['source.ts', 'source.tsx'];
const editorClass = 'linter-tslint-compatible-editor';
const tslintCache = new Map();
let tslintDef;
let requireResolve;
const idleCallbacks = new Set();
/**
* Shim for TSLint v3 interoperability
* @param {Function} Linter TSLint v3 linter
* @return {Function} TSLint v4-compatible linter
*/
function shim(Linter) {
function LinterShim(options) {
this.options = options;
this.results = {};
}
// Assign class properties
Object.assign(LinterShim, Linter);
// Assign instance methods
LinterShim.prototype = Object.assign({}, Linter.prototype, {
lint(filePath, text, configuration) {
const options = Object.assign({}, this.options, { configuration });
const linter = new Linter(filePath, text, options);
this.results = linter.lint();
},
getResult() {
return this.results;
},
});
return LinterShim;
}
function loadDefaultTSLint() {
if (!tslintDef) {
tslintDef = require('loophole').allowUnsafeNewFunction(() =>
// eslint-disable-next-line import/no-dynamic-require
require(TSLINT_MODULE_NAME).Linter);
}
}
export default {
activate() {
let depsCallbackID;
const lintertslintDeps = () => {
idleCallbacks.delete(depsCallbackID);
// Install package dependencies
require('atom-package-deps').install('linter-tslint');
// Initialize the default TSLint instance
loadDefaultTSLint();
};
depsCallbackID = window.requestIdleCallback(lintertslintDeps);
idleCallbacks.add(depsCallbackID);
this.subscriptions = new CompositeDisposable();
// Config subscriptions
this.subscriptions.add(
atom.config.observe('linter-tslint.rulesDirectory', (dir) => {
if (dir && path.isAbsolute(dir)) {
fs.stat(dir, (err, stats) => {
if (stats && stats.isDirectory()) {
this.rulesDirectory = dir;
}
});
}
}),
atom.config.observe('linter-tslint.useLocalTslint', (use) => {
tslintCache.clear();
this.useLocalTslint = use;
}),
atom.config.observe('linter-tslint.ignoreTypings', (ignoreTypings) => {
this.ignoreTypings = ignoreTypings;
}),
);
// Marks each TypeScript editor with a CSS class so that
// we can enable commands only for TypeScript editors.
this.subscriptions.add(
atom.workspace.observeTextEditors((textEditor) => {
if (textEditor.getRootScopeDescriptor().getScopesArray()
.some(scope => grammarScopes.includes(scope))) {
atom.views.getView(textEditor).classList.add(editorClass);
}
}),
);
// Command subscriptions
this.subscriptions.add(
atom.commands.add(`atom-text-editor.${editorClass}`, {
'linter-tslint:fix-file': async () => {
const textEditor = atom.workspace.getActiveTextEditor();
if (!textEditor || textEditor.isModified()) {
// Abort for invalid or unsaved text editors
atom.notifications.addError('Linter-TSLint: Please save before fixing');
return;
}
// The fix replaces the file content and the cursor can jump automatically
// to the beginning of the file, so save current cursor position
const cursorPosition = textEditor.getCursorBufferPosition();
try {
const results = await this.lint(textEditor, {
fix: true,
});
const notificationText = results && results.length === 0 ?
'Linter-TSLint: Fix complete.' :
'Linter-TSLint: Fix attempt complete, but linting errors remain.';
atom.notifications.addSuccess(notificationText);
} catch (err) {
atom.notifications.addWarning(err.message);
} finally {
// Restore cursor to the position before fix job
textEditor.setCursorBufferPosition(cursorPosition);
}
},
}),
);
},
deactivate() {
idleCallbacks.forEach(callbackID => window.cancelIdleCallback(callbackID));
idleCallbacks.clear();
this.subscriptions.dispose();
},
async getLinter(filePath) {
const basedir = path.dirname(filePath);
if (tslintCache.has(basedir)) {
return tslintCache.get(basedir);
}
// Initialize the default instance if it hasn't already been initialized
loadDefaultTSLint();
if (this.useLocalTslint) {
return this.getLocalLinter(basedir);
}
tslintCache.set(basedir, tslintDef);
return tslintDef;
},
async getLocalLinter(basedir) {
return new Promise((resolve) => {
if (!requireResolve) {
requireResolve = require('resolve');
}
requireResolve(TSLINT_MODULE_NAME, { basedir },
(err, linterPath, pkg) => {
let linter;
if (!err && pkg && /^3|4|5\./.test(pkg.version)) {
if (pkg.version.startsWith('3')) {
// eslint-disable-next-line import/no-dynamic-require
linter = shim(require('loophole').allowUnsafeNewFunction(() => require(linterPath)));
} else {
// eslint-disable-next-line import/no-dynamic-require
linter = require('loophole').allowUnsafeNewFunction(() => require(linterPath).Linter);
}
} else {
linter = tslintDef;
}
tslintCache.set(basedir, linter);
return resolve(linter);
},
);
});
},
provideLinter() {
return {
name: 'TSLint',
grammarScopes,
scope: 'file',
lintOnFly: true,
lint: async (textEditor) => {
if (this.ignoreTypings && textEditor.getPath().toLowerCase().endsWith('.d.ts')) {
return [];
}
return this.lint(textEditor);
},
};
},
async lint(textEditor, options) {
const filePath = textEditor.getPath();
const text = textEditor.getText();
const Linter = await this.getLinter(filePath);
const configurationPath = Linter.findConfigurationPath(null, filePath);
const configuration = Linter.loadConfigurationFromPath(configurationPath);
let { rulesDirectory } = configuration;
if (rulesDirectory) {
const configurationDir = path.dirname(configurationPath);
if (!Array.isArray(rulesDirectory)) {
rulesDirectory = [rulesDirectory];
}
rulesDirectory = rulesDirectory.map((dir) => {
if (path.isAbsolute(dir)) {
return dir;
}
return path.join(configurationDir, dir);
});
if (this.rulesDirectory) {
rulesDirectory.push(this.rulesDirectory);
}
}
const linter = new Linter(Object.assign({
formatter: 'json',
rulesDirectory,
}, options));
linter.lint(filePath, text, configuration);
const lintResult = linter.getResult();
if (textEditor.getText() !== text) {
// Text has been modified since the lint was triggered, tell linter not to update
return null;
}
if (
// tslint@<5
!lintResult.failureCount &&
// tslint@>=5
!lintResult.errorCount &&
!lintResult.warningCount &&
!lintResult.infoCount
) {
return [];
}
return lintResult.failures.map((failure) => {
const startPosition = failure.getStartPosition().getLineAndCharacter();
const endPosition = failure.getEndPosition().getLineAndCharacter();
return {
type: failure.ruleSeverity || 'warning',
text: `${failure.getRuleName()} - ${failure.getFailure()}`,
filePath: path.normalize(failure.getFileName()),
range: [
[startPosition.line, startPosition.character],
[endPosition.line, endPosition.character],
],
};
});
},
};