-
Notifications
You must be signed in to change notification settings - Fork 28
/
main.go
138 lines (120 loc) · 2.54 KB
/
main.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
type Rule interface {
Check(content string, path string) LintViolations
}
type LintViolation struct {
Path string
Line int
Column int
Message string
}
type LintViolations []LintViolation
func (violations LintViolations) Error() string {
var buf strings.Builder
violationsByPath := make(map[string]LintViolations)
for _, v := range violations {
violationsByPath[v.Path] = append(violationsByPath[v.Path], v)
}
for _, violations := range violationsByPath {
for _, v := range violations {
fmt.Fprintf(&buf, "%s:%d:%d: %s\n", v.Path, v.Line, v.Column, v.Message)
}
}
return buf.String()
}
type Linter struct {
Path string
IgnorePatterns []string
Rules []Rule
}
func isGoTemplateFile(info os.FileInfo) bool {
name := info.Name()
return !info.IsDir() && strings.HasSuffix(name, ".html")
}
func (l *Linter) Lint() (violations LintViolations, err error) {
err = filepath.Walk(l.Path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !isGoTemplateFile(info) {
return nil
}
for _, pattern := range l.IgnorePatterns {
if filepath.Base(path) == pattern {
return nil
}
matched, err := filepath.Match(pattern, path)
if err != nil {
return err
}
if matched {
return nil
}
}
fileViolations, err := l.LintFile(path, info)
if err != nil {
return err
}
violations = append(violations, fileViolations...)
return nil
})
return
}
func (l *Linter) LintFile(path string, info os.FileInfo) (violations LintViolations, err error) {
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
content, err := io.ReadAll(f)
if err != nil {
return
}
for _, rule := range l.Rules {
violations = append(violations, rule.Check(string(content), path)...)
}
return
}
func doMain() (violations LintViolations, err error) {
if len(os.Args) < 2 {
err = fmt.Errorf("usage: gotemplatelinter <path/to/htmls>")
return
}
path := os.Args[1]
linter := Linter{
IgnorePatterns: []string{
"__generated_asset.html",
},
Rules: []Rule{
IndentationRule{},
FinalNewlineRule{},
},
Path: path,
}
violations, err = linter.Lint()
if err != nil {
return
}
return
}
func main() {
violations, err := doMain()
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
if len(violations) > 0 {
var err error
err = violations
fmt.Fprintf(os.Stderr, "%v", err)
fmt.Fprintf(os.Stderr, "%v errors found\n", len(violations))
os.Exit(1)
}
}