/
index.js
82 lines (65 loc) · 2.07 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
'use strict'
const escapeStringRegexp = require('escape-string-regexp')
const position = require('unist-util-position')
const rule = require('unified-lint-rule')
const visit = require('unist-util-visit')
const vfileLocation = require('vfile-location')
const start = position.start
module.exports = rule('remark-lint:prohibited-strings', prohibitedStrings)
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/-]*)'
const ignoreNextTo = val.ignoreNextTo ? escapeStringRegexp(val.ignoreNextTo) : ''
// 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)'
console.log(regexpString, regexpFlags, content)
const re = new RegExp(regexpString, regexpFlags)
const results = []
let result = re.exec(content)
while (result) {
if (result[1] !== val.yes) {
results.push({ result: result[1], index: result.index })
}
result = re.exec(content)
}
return results
}
function prohibitedStrings (ast, file, strings) {
const location = vfileLocation(file)
visit(ast, 'text', checkText)
function checkText (node) {
const content = node.value
const initial = start(node).offset
strings.forEach((val) => {
const results = testProhibited(val, content)
if (results.length) {
results.forEach(({ result, index }) => {
const message = val.yes ? `Use "${val.yes}" instead of "${result}"` : `Do not use "${result}"`
file.message(message, {
start: location.toPosition(initial + index),
end: location.toPosition(initial + index + [...result].length)
})
})
}
})
}
}