forked from vasi-stripe/gogroup
-
Notifications
You must be signed in to change notification settings - Fork 1
/
validate.go
69 lines (60 loc) · 1.67 KB
/
validate.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
package gogroup
import (
"fmt"
"io"
)
func (e *ValidationError) Error() string {
return fmt.Sprintf("%s: %s (line %d)", e.Message, e.ImportPath, e.Line)
}
// Yield a validation error.
func validationError(g *groupedImport, msg string) *ValidationError {
return &ValidationError{
Message: msg,
ImportPath: g.path,
Line: g.startLine,
}
}
const (
errstrStatementOrder = "Import out of order within import group"
errstrStatementExtraLine = "Extra empty line inside import group"
errstrStatementGroup = "Import in incorrect group"
errstrGroupOrder = "Import groups out of order"
errstrGroupExtraLine = "Extra empty line between import groups"
)
// Validate an import group.
func (gs groupedImports) validate() *ValidationError {
if len(gs) < 2 {
// Always valid!
return nil
}
var prev *groupedImport
for _, g := range gs {
if prev != nil {
emptyLines := g.startLine - prev.endLine - 1
if g.group == prev.group {
if emptyLines > 0 {
return validationError(g, errstrStatementExtraLine)
} else if g.path < prev.path {
return validationError(g, errstrStatementOrder)
}
} else if emptyLines == 0 {
// This could also be a missing empty line.
return validationError(g, errstrStatementGroup)
} else if g.group < prev.group {
return validationError(g, errstrGroupOrder)
} else if emptyLines > 1 {
return validationError(g, errstrGroupExtraLine)
}
}
prev = g
}
return nil
}
// Validate a file.
func (p *Processor) validate(fileName string, r io.Reader) (validErr *ValidationError, err error) {
gs, err := p.readImports(fileName, r)
if err != nil {
return nil, err
}
return gs.validate(), nil
}