This repository has been archived by the owner on Jun 20, 2023. It is now read-only.
/
index.js
126 lines (103 loc) · 2.52 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
/** @babel */
import path from 'path';
import {CompositeDisposable, Range} from 'atom';
import {allowUnsafeNewFunction} from 'loophole';
import setText from 'atom-set-text';
import pkgDir from 'pkg-dir';
import {sync as loadJson} from 'load-json-file';
let lintText;
allowUnsafeNewFunction(() => {
lintText = require('xo').lintText;
});
function lint(textEditor) {
const filePath = textEditor.getPath();
const dir = pkgDir.sync(path.dirname(filePath));
// no package.json
if (!dir) {
return [];
}
// ugly hack to workaround ESLint's lack of a `cwd` option
// TODO: remove this when https://github.com/sindresorhus/atom-linter-xo/issues/19 is resolved
const defaultCwd = process.cwd();
process.chdir(dir);
const pkg = loadJson(path.join(dir, 'package.json'));
// only lint when `xo` is a dependency
if (!(pkg.dependencies && pkg.dependencies.xo) &&
!(pkg.devDependencies && pkg.devDependencies.xo)) {
return [];
}
let report;
allowUnsafeNewFunction(() => {
report = lintText(textEditor.getText(), {
cwd: dir,
filename: filePath
});
});
process.chdir(defaultCwd);
const textBuffer = textEditor.getBuffer();
return report.results[0].messages.map(x => {
let fix;
if (x.fix) {
fix = {
range: new Range(
textBuffer.positionForCharacterIndex(x.fix.range[0]),
textBuffer.positionForCharacterIndex(x.fix.range[1])
),
newText: x.fix.text
};
}
const ret = {
filePath,
fix,
type: x.severity === 2 ? 'Error' : 'Warning',
text: `${x.message} (${x.ruleId})`
};
// some messages don't have these
if (typeof x.line === 'number' && typeof x.column === 'number') {
ret.range = [
[x.line - 1, x.column - 1],
[x.line - 1, x.column - 1]
];
}
return ret;
});
}
export function provideLinter() {
return {
name: 'XO',
grammarScopes: [
'source.js',
'source.jsx',
'source.js.jsx'
],
scope: 'file',
lintOnFly: true,
lint
};
}
export function activate() {
require('atom-package-deps').install('linter-xo');
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.commands.add('atom-text-editor', {
'XO:Fix': () => {
const editor = atom.workspace.getActiveTextEditor();
if (!editor) {
return;
}
let report;
allowUnsafeNewFunction(() => {
report = lintText(editor.getText(), {
fix: true,
cwd: path.dirname(editor.getPath())
});
});
const output = report.results[0].output;
if (output) {
setText(output);
}
}
}));
}
export function deactivate() {
this.subscriptions.dispose();
}