-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathno-inconsistent-quotes.ts
62 lines (52 loc) · 1.97 KB
/
no-inconsistent-quotes.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
import { switchOrSeverityorSeverityAndStringSchema } from '../schemas'
import Schema from '../schema'
import Rule from '../rule'
import { RawSchema, AcceptedSchema, Location } from '../types'
import Document from '../document'
import Line from '../line'
export default class NoInconsistentQuotes implements Rule {
public readonly name: string = 'no-inconsistent-quotes'
public readonly acceptedSchema: AcceptedSchema = switchOrSeverityorSeverityAndStringSchema
public readonly schema: Schema
public constructor(rawSchema: RawSchema) {
this.schema = new Schema(rawSchema)
}
public async run(document: Document): Promise<void> {
const quotesUsed: Map<string, Array<Location>> = new Map()
quotesUsed.set(`"`, [])
quotesUsed.set(`'`, [])
document.lines.forEach((line: Line, index: number): void => {
const singleIndex = line.text.indexOf(`'`)
if (singleIndex > -1) {
quotesUsed.set(`'`, [
...quotesUsed.get(`'`),
{ line: index + 1, column: line.indentation + line.keyword.length + singleIndex + 1 },
])
}
const doubleIndex = line.text.indexOf(`"`)
if (doubleIndex > -1) {
quotesUsed.set(`"`, [
...quotesUsed.get(`"`),
{ line: index + 1, column: line.indentation + line.keyword.length + doubleIndex + 1 },
])
}
})
if (quotesUsed.get(`'`).length > 0 && quotesUsed.get(`"`).length > 0) {
quotesUsed.forEach((locations: Array<Location>) => {
locations.forEach((location: Location): void => {
document.addError(this, 'Found a mix of single and double quotes.', location)
})
})
}
}
public async fix(document: Document): Promise<void> {
let replacer = `'`
if (this.schema.args) {
replacer = this.schema.args as string
}
document.lines.forEach((line: Line, index: number): void => {
document.lines[index].text = line.text.replaceAll(/['"]/g, replacer)
})
await document.regenerate()
}
}