-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
remark.ts
92 lines (89 loc) · 2.72 KB
/
remark.ts
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
import path from 'path'
import { Rule } from 'eslint'
import { DEFAULT_EXTENSIONS, MARKDOWN_EXTENSIONS } from 'eslint-mdx'
import vfile from 'vfile'
import { getRemarkProcessor } from './helper'
export const remark: Rule.RuleModule = {
meta: {
type: 'layout',
docs: {
description: 'Linter integration with remark plugins',
category: 'Stylistic Issues',
recommended: true,
},
messages: {
remarkReport: '{{ source }}:{{ ruleId }} - {{ reason }}',
},
fixable: 'code',
schema: [],
},
create(context) {
const filename = context.getFilename()
const extname = path.extname(filename)
const sourceCode = context.getSourceCode()
const extensions = DEFAULT_EXTENSIONS.concat(
context.parserOptions.extensions || [],
MARKDOWN_EXTENSIONS,
context.parserOptions.markdownExtensions || [],
)
return {
Program(node) {
/* istanbul ignore if */
if (!extensions.includes(extname)) {
return
}
const sourceText = sourceCode.getText(node)
const remarkProcessor = getRemarkProcessor(filename)
const file = remarkProcessor.processSync(
vfile({
path: filename,
contents: sourceText,
}),
)
file.messages.forEach(
({ source, reason, ruleId, location: { start, end } }) =>
context.report({
messageId: 'remarkReport',
data: {
reason,
source,
ruleId,
},
loc: {
// ! eslint ast column is 0-indexed, but unified is 1-indexed
start: {
...start,
column: start.column - 1,
},
end: {
...end,
column: end.column - 1,
},
},
node,
fix(fixer) {
/* istanbul ignore if */
if (start.offset == null) {
return null
}
const range: [number, number] = [
start.offset,
/* istanbul ignore next */
end.offset == null ? start.offset + 1 : end.offset,
]
const partialText = sourceText.slice(...range)
const fixed = remarkProcessor
.processSync(partialText)
.toString()
return fixer.replaceTextRange(
range,
/* istanbul ignore next */
partialText.endsWith('\n') ? fixed : fixed.slice(0, -1), // remove redundant new line
)
},
}),
)
},
}
},
}