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 141
/
main.js
332 lines (291 loc) · 9.9 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
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
'use babel'
// eslint-disable-next-line import/no-extraneous-dependencies, import/extensions
import { CompositeDisposable } from 'atom'
import { hasValidScope } from './validate/editor'
// Internal variables
const idleCallbacks = new Set()
// Dependencies
// NOTE: We are not directly requiring these in order to reduce the time it
// takes to require this file as that causes delays in Atom loading this package
let path
let helpers
let workerHelpers
let isConfigAtHomeRoot
let migrateConfigOptions
const loadDeps = () => {
if (!path) {
path = require('path')
}
if (!helpers) {
helpers = require('./helpers')
}
if (!workerHelpers) {
workerHelpers = require('./worker-helpers')
}
if (!isConfigAtHomeRoot) {
isConfigAtHomeRoot = require('./is-config-at-home-root')
}
}
const makeIdleCallback = (work) => {
let callbackId
const callBack = () => {
idleCallbacks.delete(callbackId)
work()
}
callbackId = window.requestIdleCallback(callBack)
idleCallbacks.add(callbackId)
}
const scheduleIdleTasks = () => {
const linterEslintInstallPeerPackages = () => {
require('atom-package-deps').install('linter-eslint')
}
const linterEslintLoadDependencies = loadDeps
const linterEslintStartWorker = () => {
loadDeps()
helpers.startWorker()
}
if (!atom.inSpecMode()) {
makeIdleCallback(linterEslintInstallPeerPackages)
makeIdleCallback(linterEslintLoadDependencies)
makeIdleCallback(linterEslintStartWorker)
}
}
// Configuration
const scopes = []
let showRule
let lintHtmlFiles
let ignoredRulesWhenModified
let ignoredRulesWhenFixing
let disableWhenNoEslintConfig
let ignoreFixableRulesWhileTyping
// Internal functions
/**
* Given an Array or iterable containing a list of Rule IDs, return an Object
* to be sent to ESLint's configuration that disables those rules.
* @param {[iterable]} ruleIds Iterable containing ruleIds to ignore
* @return {Object} Object containing properties for each rule to ignore
*/
const idsToIgnoredRules = ruleIds => (
Array.from(ruleIds).reduce(
// 0 is the severity to turn off a rule
(ids, id) => Object.assign(ids, { [id]: 0 }),
{}
))
module.exports = {
activate() {
this.subscriptions = new CompositeDisposable()
if (!migrateConfigOptions) {
migrateConfigOptions = require('./migrate-config-options')
}
migrateConfigOptions()
const embeddedScope = 'source.js.embedded.html'
this.subscriptions.add(atom.config.observe(
'linter-eslint.lintHtmlFiles',
(value) => {
lintHtmlFiles = value
if (lintHtmlFiles) {
scopes.push(embeddedScope)
} else if (scopes.indexOf(embeddedScope) !== -1) {
scopes.splice(scopes.indexOf(embeddedScope), 1)
}
}
))
this.subscriptions.add(atom.config.observe(
'linter-eslint.scopes',
(value) => {
// Remove any old scopes
scopes.splice(0, scopes.length)
// Add the current scopes
Array.prototype.push.apply(scopes, value)
// Ensure HTML linting still works if the setting is updated
if (lintHtmlFiles && !scopes.includes(embeddedScope)) {
scopes.push(embeddedScope)
}
}
))
this.subscriptions.add(atom.workspace.observeTextEditors((editor) => {
editor.onDidSave(async () => {
if (hasValidScope(editor, scopes)
&& atom.config.get('linter-eslint.autofix.fixOnSave')
) {
await this.fixJob(true)
}
})
}))
this.subscriptions.add(atom.commands.add('atom-text-editor', {
'linter-eslint:debug': async () => {
loadDeps()
const debugString = await helpers.generateDebugString()
const notificationOptions = { detail: debugString, dismissable: true }
atom.notifications.addInfo('linter-eslint debugging information', notificationOptions)
}
}))
this.subscriptions.add(atom.commands.add('atom-text-editor', {
'linter-eslint:fix-file': async () => {
await this.fixJob()
}
}))
this.subscriptions.add(atom.config.observe(
'linter-eslint.advanced.showRuleIdInMessage',
(value) => { showRule = value }
))
this.subscriptions.add(atom.config.observe(
'linter-eslint.disabling.disableWhenNoEslintConfig',
(value) => { disableWhenNoEslintConfig = value }
))
this.subscriptions.add(atom.config.observe(
'linter-eslint.disabling.rulesToSilenceWhileTyping',
(ids) => { ignoredRulesWhenModified = ids }
))
this.subscriptions.add(atom.config.observe(
'linter-eslint.autofix.rulesToDisableWhileFixing',
(ids) => { ignoredRulesWhenFixing = idsToIgnoredRules(ids) }
))
this.subscriptions.add(atom.config.observe(
'linter-eslint.autofix.ignoreFixableRulesWhileTyping',
(value) => { ignoreFixableRulesWhileTyping = value }
))
this.subscriptions.add(atom.contextMenu.add({
'atom-text-editor:not(.mini), .overlayer': [{
label: 'ESLint Fix',
command: 'linter-eslint:fix-file',
shouldDisplay: (evt) => {
const activeEditor = atom.workspace.getActiveTextEditor()
if (!activeEditor) {
return false
}
// Black magic!
// Compares the private component property of the active TextEditor
// against the components of the elements
const evtIsActiveEditor = evt.path.some(elem => (
// Atom v1.19.0+
elem.component && activeEditor.component
&& elem.component === activeEditor.component))
// Only show if it was the active editor and it is a valid scope
return evtIsActiveEditor && hasValidScope(activeEditor, scopes)
}
}]
}))
scheduleIdleTasks()
},
deactivate() {
idleCallbacks.forEach(callbackID => window.cancelIdleCallback(callbackID))
idleCallbacks.clear()
if (helpers) {
// If the helpers module hasn't been loaded then there was no chance a
// worker was started anyway.
helpers.killWorker()
}
this.subscriptions.dispose()
},
provideLinter() {
return {
name: 'ESLint',
grammarScopes: scopes,
scope: 'file',
lintsOnChange: true,
lint: async (textEditor) => {
if (!atom.workspace.isTextEditor(textEditor)) {
// If we somehow get fed an invalid TextEditor just immediately return
return null
}
const filePath = textEditor.getPath()
if (!filePath) {
// The editor currently has no path, we can't report messages back to
// Linter so just return null
return null
}
loadDeps()
if (filePath.includes('://')) {
// If the path is a URL (Nuclide remote file) return a message
// telling the user we are unable to work on remote files.
return helpers.generateUserMessage(textEditor, {
severity: 'warning',
excerpt: 'Remote file open, linter-eslint is disabled for this file.',
})
}
const text = textEditor.getText()
let rules = {}
if (textEditor.isModified()) {
if (ignoreFixableRulesWhileTyping) {
// Note that the fixable rules will only have values after the first lint job
const ignoredRules = new Set(helpers.rules.getFixableRules())
ignoredRulesWhenModified.forEach(ruleId => ignoredRules.add(ruleId))
rules = idsToIgnoredRules(ignoredRules)
} else {
rules = idsToIgnoredRules(ignoredRulesWhenModified)
}
}
try {
const response = await helpers.sendJob({
type: 'lint',
contents: text,
config: atom.config.get('linter-eslint'),
rules,
filePath,
projectPath: atom.project.relativizePath(filePath)[0] || ''
})
if (textEditor.getText() !== text) {
/*
The editor text has been modified since the lint was triggered,
as we can't be sure that the results will map properly back to
the new contents, simply return `null` to tell the
`provideLinter` consumer not to update the saved results.
*/
return null
}
return helpers.processJobResponse(response, textEditor, showRule)
} catch (error) {
return helpers.handleError(textEditor, error)
}
}
}
},
async fixJob(isSave = false) {
const textEditor = atom.workspace.getActiveTextEditor()
if (!textEditor || !atom.workspace.isTextEditor(textEditor)) {
// Silently return if the TextEditor is invalid
return
}
loadDeps()
if (textEditor.isModified()) {
// Abort for invalid or unsaved text editors
const message = 'Linter-ESLint: Please save before fixing'
atom.notifications.addError(message)
}
const filePath = textEditor.getPath()
const fileDir = path.dirname(filePath)
const projectPath = atom.project.relativizePath(filePath)[0]
// Get the text from the editor, so we can use executeOnText
const text = textEditor.getText()
// Do not try to make fixes on an empty file
if (text.length === 0) {
return
}
// Do not try to fix if linting should be disabled
const configPath = workerHelpers.getConfigPath(fileDir)
const noProjectConfig = (configPath === null || isConfigAtHomeRoot(configPath))
if (noProjectConfig && disableWhenNoEslintConfig) {
return
}
let rules = {}
if (Object.keys(ignoredRulesWhenFixing).length > 0) {
rules = ignoredRulesWhenFixing
}
try {
const response = await helpers.sendJob({
type: 'fix',
config: atom.config.get('linter-eslint'),
contents: text,
rules,
filePath,
projectPath
})
if (!isSave) {
atom.notifications.addSuccess(response)
}
} catch (err) {
atom.notifications.addWarning(err.message)
}
},
}