-
Notifications
You must be signed in to change notification settings - Fork 0
/
ext.go
107 lines (93 loc) · 2.26 KB
/
ext.go
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
96
97
98
99
100
101
102
103
104
105
106
107
package difflint
import (
"encoding/json"
"log"
"os"
)
var (
// DefaultTemplates is the default list of directive templates.
DefaultTemplates = []string{
"#LINT.?",
"//LINT.?",
"/*LINT.?",
"<!--LINT.?",
"'LINT.?",
}
// DefaultFileExtMap is the default map of file extensions to directive templates.
DefaultFileExtMap = map[string][]int{
"py": {0},
"sh": {0},
"go": {1},
"js": {1, 2},
"jsx": {1, 2},
"mjs": {1, 2},
"ts": {1, 2},
"tsx": {1, 2},
"jsonc": {1, 2},
"c": {1, 2},
"cc": {1, 2},
"cpp": {1, 2},
"h": {1, 2},
"hpp": {1, 2},
"java": {1},
"rs": {1},
"swift": {1},
"svelte": {1, 2, 3},
"css": {2},
"html": {3},
"md": {3},
"markdown": {3},
"bas": {4},
}
)
// ExtFileJSON is a JSON representation of a file extension to directive template map.
type ExtFileJSON map[string][]string
// ExtMap represents the extensions and templates for a linting operation.
type ExtMap struct {
// Templates is the list of directive templates.
Templates []string
// FileExtMap is a map of file extensions to directive templates.
FileExtMap map[string][]int
}
// NewExtMap returns a new ExtMap instance.
func NewExtMap(path string) *ExtMap {
o := &ExtMap{
Templates: DefaultTemplates,
FileExtMap: DefaultFileExtMap,
}
// If a path is provided, update the templates and file extension map.
if path != "" {
// Unmarshal the JSON file.
var extFile ExtFileJSON
bytes, err := os.ReadFile(path)
if err != nil {
log.Fatalf("error reading JSON file %q: %v", path, err)
}
if err := json.Unmarshal(bytes, &extFile); err != nil {
log.Fatalf("error unmarshaling JSON file %q: %v", path, err)
}
// Update the templates and file extension map.
for ext, tpls := range extFile {
for _, tpl := range tpls {
o.With(ext, tpl)
}
}
}
return o
}
// With adds a directive template for a file extension.
func (o *ExtMap) With(ext, tpl string) *ExtMap {
tplIndex := -1
for i, t := range o.Templates {
if t == tpl {
tplIndex = i
break
}
}
if tplIndex == -1 {
tplIndex = len(o.Templates)
o.Templates = append(o.Templates, tpl)
}
o.FileExtMap[ext] = append(o.FileExtMap[ext], tplIndex)
return o
}