-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
213 lines (181 loc) · 4.26 KB
/
formatter.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package goif
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"regexp"
"sort"
"strings"
)
type formatter struct {
orgGroupPrefix string
importOpened bool
importLines []importLine
}
func NewFormatter(orgGroupPrefix string) *formatter {
return &formatter{
orgGroupPrefix: orgGroupPrefix,
}
}
func (f *formatter) Format(r io.Reader, w io.Writer) error {
reader := bufio.NewReader(r)
for i := 1; ; i++ {
line, err := reader.ReadString('\n')
if err == nil || err == io.EOF {
if err := f.line(line, w); err != nil {
return fmt.Errorf("%d %v", i, err)
}
if err == io.EOF {
break
}
}
}
f.flushUnclosedBlock()
return nil
}
func (f *formatter) line(line string, w io.Writer) error {
switch {
case !f.importOpened && isImportOpeningLine(line):
f.importOpened = true
case f.importOpened:
if isImportClosingLine(line) {
f.writeOrderedImports(w)
f.importOpened = false
f.importLines = []importLine{}
} else if len(strings.TrimSpace(line)) > 0 {
if id, err := parseImportLine(line); err == nil {
f.importLines = append(f.importLines, id)
} else {
return err
}
}
default:
w.Write([]byte(line))
}
return nil
}
func isImportOpeningLine(line string) bool {
return openingLineRegexp.MatchString(line)
}
func isImportClosingLine(line string) bool {
return closingLineRegexp.MatchString(line)
}
func (f *formatter) writeOrderedImports(w io.Writer) {
w.Write([]byte("import (\n"))
groups := groupAndSort(f.orgGroupPrefix, f.importLines)
count := len(groups)
for i, group := range groups {
for _, imp := range group {
w.Write([]byte(imp.String()))
w.Write([]byte("\n"))
}
if i < count-1 {
w.Write([]byte("\n"))
}
}
w.Write([]byte(")\n"))
}
func groupAndSort(orgPrefix string, imports []importLine) [][]importLine {
var stdlib, org, others []importLine
for _, imp := range imports {
if orgPrefix != "" && strings.Contains(imp.importDecl.pckg, orgPrefix) {
org = append(org, imp)
} else if strings.Contains(imp.importDecl.pckg, ".") {
others = append(others, imp)
} else {
stdlib = append(stdlib, imp)
}
}
sort.Sort(sortableImports(org))
sort.Sort(sortableImports(stdlib))
sort.Sort(sortableImports(others))
var out [][]importLine
if len(stdlib) > 0 {
out = append(out, stdlib)
}
if len(org) > 0 {
out = append(out, org)
}
if len(others) > 0 {
out = append(out, others)
}
return out
}
func (f *formatter) flushUnclosedBlock() {
if !f.importOpened {
return
}
}
type importLine struct {
importDecl importDecl
comment comment
}
type importDecl struct {
pckg string
alias string
}
func (id importDecl) empty() bool {
return id.pckg == "" && id.alias == ""
}
type comment string
func parseImportLine(line string) (importLine, error) {
if l, err := parseImportDecl(line); err == nil {
return l, nil
}
return parseComment(line)
}
var (
importDeclRegexp = regexp.MustCompile(`^\s*((\w+)\s+)?"(\S+)"`)
commentRegexp = regexp.MustCompile(`^\s*//(.+)`)
openingLineRegexp = regexp.MustCompile(`^\s*import \(`)
closingLineRegexp = regexp.MustCompile(`^\s*\)`)
)
func parseImportDecl(line string) (importLine, error) {
matches := importDeclRegexp.FindStringSubmatch(line)
if len(matches) == 0 {
return importLine{}, errors.New("unrecognized import line")
}
return importLine{
importDecl: importDecl{
alias: matches[2],
pckg: matches[3],
},
}, nil
}
func parseComment(line string) (importLine, error) {
matches := commentRegexp.FindStringSubmatch(line)
if len(matches) == 0 {
return importLine{}, errors.New("unrecognized import line")
}
return importLine{
comment: comment(matches[1]),
}, nil
}
func (il importLine) String() string {
if !il.importDecl.empty() {
buf := bytes.Buffer{}
buf.WriteString("\t")
if il.importDecl.alias != "" {
buf.WriteString(il.importDecl.alias)
buf.WriteString(" ")
}
buf.WriteString("\"")
buf.WriteString(il.importDecl.pckg)
buf.WriteString("\"")
return buf.String()
} else {
return fmt.Sprintf("\t//%s", il.comment)
}
}
type sortableImports []importLine
func (imps sortableImports) Len() int {
return len(imps)
}
func (imps sortableImports) Less(i, j int) bool {
return imps[i].importDecl.pckg < imps[j].importDecl.pckg
}
func (imps sortableImports) Swap(i, j int) {
imps[i], imps[j] = imps[j], imps[i]
}