forked from fvictorio/solhint-plugin-prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (81 loc) · 2.49 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
const { showInvisibles, generateDifferences } = require('prettier-linter-helpers')
const { INSERT, DELETE, REPLACE } = generateDifferences
const getLocFromIndex = (text, index) => {
let line = 1
let column = 0
let i = 0
while (i < index) {
if (text[i] === '\n') {
line++
column = 0
} else {
column++
}
i++
}
return { line, column }
}
class PrettierChecker {
constructor(reporter, config, inputSrc, fileName) {
this.prettier = null
this.ruleId = 'prettier'
this.reporter = reporter
this.config = config
this.inputSrc = inputSrc
this.fileName = fileName
}
async enterSourceUnit() {
await this.SourceUnit()
}
async SourceUnit() {
try {
// Check for optional dependencies with the try catch
// Prettier is expensive to load, so only load it if needed.
if (!this.prettier) {
this.prettier = require('prettier')
}
const filepath = this.fileName
const prettierRcOptions = await this.prettier.resolveConfig(filepath, {
editorconfig: true
})
const prettierOptions = Object.assign({}, prettierRcOptions, {
filepath,
plugins: ['prettier-plugin-solidity']
})
const formatted = await this.prettier.format(this.inputSrc, prettierOptions)
const differences = generateDifferences(this.inputSrc, formatted)
differences.forEach(difference => {
let loc = null
switch (difference.operation) {
case INSERT:
loc = getLocFromIndex(this.inputSrc, difference.offset)
this.errorAt(loc.line, loc.column, `Insert ${showInvisibles(difference.insertText)}`)
break
case DELETE:
loc = getLocFromIndex(this.inputSrc, difference.offset)
this.errorAt(loc.line, loc.column, `Delete ${showInvisibles(difference.deleteText)}`)
break
case REPLACE:
loc = getLocFromIndex(this.inputSrc, difference.offset)
this.errorAt(
loc.line,
loc.column,
`Replace ${showInvisibles(difference.deleteText)} with ${showInvisibles(
difference.insertText
)}`
)
break
default:
// A switch must have a default
}
})
} catch (e) {
console.error(e)
process.exit(1)
}
}
errorAt(line, column, message) {
this.reporter.errorAt(line, column, this.ruleId, message)
}
}
module.exports = [PrettierChecker]