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 37
/
index.js
344 lines (298 loc) · 10.7 KB
/
index.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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
'use babel';
/**
* Note that this can't be loaded lazily as `atom` doesn't export it correctly
* for that, however as this comes from app.asar it is pre-compiled and is
* essentially "free" as there is no expensive compilation step.
*/
// eslint-disable-next-line import/extensions, import/no-extraneous-dependencies
import { CompositeDisposable } from 'atom';
const lazyReq = require('lazy-req')(require);
const { dirname } = lazyReq('path')('dirname');
const stylelint = lazyReq('stylelint');
const { generateRange } = lazyReq('atom-linter')('generateRange');
const assignDeep = lazyReq('assign-deep');
const escapeHTML = lazyReq('escape-html');
// Settings
let useStandard;
let presetConfig;
let disableWhenNoConfig;
let showIgnored;
// Internal vars
let subscriptions;
const baseScopes = [
'source.css',
'source.scss',
'source.css.scss',
'source.less',
'source.css.less',
'source.css.postcss',
'source.css.postcss.sugarss'
];
function startMeasure(baseName) {
performance.mark(`${baseName}-start`);
}
function endMeasure(baseName) {
if (atom.inDevMode()) {
performance.mark(`${baseName}-end`);
performance.measure(baseName, `${baseName}-start`, `${baseName}-end`);
// eslint-disable-next-line no-console
console.log(`${baseName} took: `, performance.getEntriesByName(baseName)[0].duration);
performance.clearMarks(`${baseName}-end`);
performance.clearMeasures(baseName);
}
performance.clearMarks(`${baseName}-start`);
}
function createRange(editor, data) {
if (!Object.hasOwnProperty.call(data, 'line') && !Object.hasOwnProperty.call(data, 'column')) {
// data.line & data.column might be undefined for non-fatal invalid rules,
// e.g.: "block-no-empty": "foo"
// Return `false` so Linter will ignore the range
return false;
}
return generateRange(editor, data.line - 1, data.column - 1);
}
export function activate() {
startMeasure('linter-stylelint: Activation');
require('atom-package-deps').install('linter-stylelint');
subscriptions = new CompositeDisposable();
subscriptions.add(atom.config.observe('linter-stylelint.useStandard', (value) => {
useStandard = value;
}));
subscriptions.add(atom.config.observe('linter-stylelint.disableWhenNoConfig', (value) => {
disableWhenNoConfig = value;
}));
subscriptions.add(atom.config.observe('linter-stylelint.showIgnored', (value) => {
showIgnored = value;
}));
endMeasure('linter-stylelint: Activation');
}
export function deactivate() {
subscriptions.dispose();
}
function generateHTMLMessage(message) {
if (!message.rule || message.rule === 'CssSyntaxError') {
return escapeHTML()(message.text);
}
const ruleParts = message.rule.split('/');
let url;
if (ruleParts.length === 1) {
// Core rule
url = `http://stylelint.io/user-guide/rules/${ruleParts[0]}`;
} else {
// Plugin rule
const pluginName = ruleParts[0];
// const ruleName = ruleParts[1];
switch (pluginName) {
case 'plugin':
url = 'https://github.com/AtomLinter/linter-stylelint/tree/master/docs/noRuleNamespace.md';
break;
default:
url = 'https://github.com/AtomLinter/linter-stylelint/tree/master/docs/linkingNewRule.md';
}
}
// Escape any HTML in the message, and replace the rule ID with a link
return escapeHTML()(message.text).replace(
`(${message.rule})`, `(<a href="${url}">${message.rule}</a>)`
);
}
const parseResults = (editor, options, results, filePath) => {
startMeasure('linter-stylelint: Parsing results');
if (options.code !== editor.getText()) {
// The editor contents have changed since the lint was requested, tell
// Linter not to update the results
endMeasure('linter-stylelint: Parsing results');
endMeasure('linter-stylelint: Lint');
return null;
}
if (!results) {
endMeasure('linter-stylelint: Parsing results');
endMeasure('linter-stylelint: Lint');
return [];
}
const invalidOptions = results.invalidOptionWarnings.map(msg => ({
type: 'Error',
severity: 'error',
text: msg.text,
filePath
}));
const warnings = results.warnings.map((warning) => {
// Stylelint only allows 'error' and 'warning' as severity values
const severity = !warning.severity || warning.severity === 'error' ? 'Error' : 'Warning';
return {
type: severity,
severity: severity.toLowerCase(),
html: generateHTMLMessage(warning),
filePath,
range: createRange(editor, warning)
};
});
const deprecations = results.deprecations.map(deprecation => ({
type: 'Warning',
severity: 'warning',
html: `${escapeHTML()(deprecation.text)} (<a href="${deprecation.reference}">reference</a>)`,
filePath
}));
const ignored = [];
if (showIgnored && results.ignored) {
ignored.push({
type: 'Warning',
severity: 'warning',
text: 'This file is ignored',
filePath
});
}
const toReturn = []
.concat(invalidOptions)
.concat(warnings)
.concat(deprecations)
.concat(ignored);
endMeasure('linter-stylelint: Parsing results');
endMeasure('linter-stylelint: Lint');
return toReturn;
};
const runStylelint = async (editor, options, filePath) => {
startMeasure('linter-stylelint: Stylelint');
let data;
try {
data = await stylelint().lint(options);
} catch (error) {
endMeasure('linter-stylelint: Stylelint');
// Was it a code parsing error?
if (error.line) {
endMeasure('linter-stylelint: Lint');
return [{
type: 'Error',
severity: 'error',
text: error.reason || error.message,
filePath,
range: createRange(editor, error)
}];
}
// If we got here, stylelint found something really wrong with the
// configuration, such as extending an invalid configuration
atom.notifications.addError('Unable to run stylelint', {
detail: error.reason || error.message,
dismissable: true
});
endMeasure('linter-stylelint: Lint');
return [];
}
endMeasure('linter-stylelint: Stylelint');
const results = data.results.shift();
return parseResults(editor, options, results, filePath);
};
export function provideLinter() {
return {
name: 'stylelint',
grammarScopes: baseScopes,
scope: 'file',
lintOnFly: true,
lint: async (editor) => {
startMeasure('linter-stylelint: Lint');
const scopes = editor.getLastCursor().getScopeDescriptor().getScopesArray();
const filePath = editor.getPath();
const text = editor.getText();
if (!text) {
endMeasure('linter-stylelint: Lint');
return [];
}
// Require stylelint-config-standard if it hasn't already been loaded
if (!presetConfig && useStandard) {
presetConfig = require('stylelint-config-standard');
}
// Setup base config if useStandard() is true
const defaultConfig = {
rules: {}
};
// Base the config in the project directory
let [configBasedir] = atom.project.relativizePath(filePath);
if (configBasedir === null) {
// Falling back to the file directory if no project is found
configBasedir = dirname(filePath);
}
const rules = useStandard ? assignDeep()({}, presetConfig) : defaultConfig;
const options = {
code: text,
codeFilename: filePath,
config: rules,
configBasedir
};
if (scopes.includes('source.css.scss') || scopes.includes('source.scss')) {
options.syntax = 'scss';
}
if (scopes.includes('source.css.less') || scopes.includes('source.less')) {
options.syntax = 'less';
}
if (scopes.includes('source.css.postcss.sugarss')) {
options.syntax = 'sugarss';
// `stylelint-config-standard` isn't fully compatible with SugarSS
// See here for details:
// https://github.com/stylelint/stylelint-config-standard#using-the-config-with-sugarss-syntax
options.config.rules['block-closing-brace-empty-line-before'] = null;
options.config.rules['block-closing-brace-newline-after'] = null;
options.config.rules['block-closing-brace-newline-before'] = null;
options.config.rules['block-closing-brace-space-before'] = null;
options.config.rules['block-opening-brace-newline-after'] = null;
options.config.rules['block-opening-brace-space-after'] = null;
options.config.rules['block-opening-brace-space-before'] = null;
options.config.rules['declaration-block-semicolon-newline-after'] = null;
options.config.rules['declaration-block-semicolon-space-after'] = null;
options.config.rules['declaration-block-semicolon-space-before'] = null;
options.config.rules['declaration-block-trailing-semicolon'] = null;
options.config.rules['declaration-block-trailing-semicolon'] = null;
}
startMeasure('linter-stylelint: Create Linter');
const stylelintLinter = await stylelint().createLinter();
endMeasure('linter-stylelint: Create Linter');
startMeasure('linter-stylelint: Config');
let foundConfig;
try {
foundConfig = await stylelintLinter.getConfigForFile(filePath);
} catch (error) {
if (!/No configuration provided for .+/.test(error.message)) {
endMeasure('linter-stylelint: Config');
// If we got here, stylelint failed to parse the configuration
// there's no point of re-linting if useStandard is true, because the
// user does not have the complete set of desired rules parsed
atom.notifications.addError('Unable to parse stylelint configuration', {
detail: error.message,
dismissable: true
});
endMeasure('linter-stylelint: Lint');
return [];
}
}
endMeasure('linter-stylelint: Config');
if (foundConfig) {
options.config = assignDeep()(rules, foundConfig.config);
options.configBasedir = dirname(foundConfig.filepath);
}
if (!foundConfig && disableWhenNoConfig) {
endMeasure('linter-stylelint: Lint');
return [];
}
startMeasure('linter-stylelint: Check ignored');
let fileIsIgnored;
try {
fileIsIgnored = await stylelintLinter.isPathIgnored(filePath);
} catch (error) {
// Do nothing, configuration errors should have already been caught and thrown above
}
endMeasure('linter-stylelint: Check ignored');
if (fileIsIgnored) {
endMeasure('linter-stylelint: Lint');
if (showIgnored) {
return [{
type: 'Warning',
severity: 'warning',
text: 'This file is ignored',
filePath
}];
}
return [];
}
const results = await runStylelint(editor, options, filePath);
return results;
}
};
}