-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
95 lines (79 loc) · 2.45 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
'use strict'
import escapeStringRegexp from 'escape-string-regexp'
import { pointStart } from 'unist-util-position'
import { lintRule } from 'unified-lint-rule'
import { visit } from 'unist-util-visit'
import { location } from 'vfile-location'
const remarkLintProhibitedStrings = lintRule('remark-lint:prohibited-strings', prohibitedStrings)
export default remarkLintProhibitedStrings
function testProhibited (val, content) {
let regexpFlags = 'g'
let no = val.no
if (!no) {
no = escapeStringRegexp(val.yes)
regexpFlags += 'i'
}
let regexpString = '(?<!\\.|@[a-zA-Z0-9/-]*)'
let ignoreNextTo
if (val.ignoreNextTo) {
if (Array.isArray(val.ignoreNextTo)) {
const parts = val.ignoreNextTo.map(a => escapeStringRegexp(a)).join('|')
ignoreNextTo = `(?:${parts})`
} else {
ignoreNextTo = escapeStringRegexp(val.ignoreNextTo)
}
} else {
ignoreNextTo = ''
}
const replaceCaptureGroups = !!val.replaceCaptureGroups
// If it starts with a letter, make sure it is a word break.
if (/^\b/.test(no)) {
regexpString += '\\b'
}
if (ignoreNextTo) {
regexpString += `(?<!${ignoreNextTo})`
}
regexpString += `(${no})`
if (ignoreNextTo) {
regexpString += `(?!${ignoreNextTo})`
}
// If it ends with a letter, make sure it is a word break.
if (/\b$/.test(no)) {
regexpString += '\\b'
}
regexpString += '(?!\\.\\w)'
const re = new RegExp(regexpString, regexpFlags)
const results = []
let result = re.exec(content)
while (result) {
if (result[1] !== val.yes) {
let yes = val.yes
if (replaceCaptureGroups) {
yes = result[1].replace(new RegExp(no), yes)
}
results.push({ result: result[1], index: result.index, yes })
}
result = re.exec(content)
}
return results
}
function prohibitedStrings (ast, file, strings) {
const myLocation = location(file)
visit(ast, 'text', checkText)
function checkText (node) {
const content = node.value
const initial = pointStart(node).offset
strings.forEach((val) => {
const results = testProhibited(val, content)
if (results.length) {
results.forEach(({ result, index, yes }) => {
const message = val.yes ? `Use "${yes}" instead of "${result}"` : `Do not use "${result}"`
file.message(message, {
start: myLocation.toPoint(initial + index),
end: myLocation.toPoint(initial + index + [...result].length)
})
})
}
})
}
}