-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi_word_ident_name.go
81 lines (68 loc) · 1.97 KB
/
multi_word_ident_name.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
package checker
import (
"fmt"
"go/ast"
"regexp"
)
func init() {
must(Register("multi_word_ident_name", NewMultiWordIdentNameChecker))
}
// MultiWordIdentNameChecker checks the correctness of type names.
// Correct type names adhere to the following rules:
// * PascalCase for exported types.
// * camelCase for non-exported types.
type MultiWordIdentNameChecker struct{}
// NewMultiWordIdentNameChecker constructs a MultiWordIdentNameChecker.
func NewMultiWordIdentNameChecker(configData interface{}) NodeChecker {
return &MultiWordIdentNameChecker{}
}
// Title implements the NodeChecker interface.
func (c *MultiWordIdentNameChecker) Title() string {
return "Multi-Word Identifiers"
}
// Description implements the NodeChecker interface.
func (c *MultiWordIdentNameChecker) Description() string {
return `An identifier consisting of multiple words must be in camelCase form.`
}
// Examples implements the NodeChecker interface.
func (c *MultiWordIdentNameChecker) Examples() []Example {
return []Example{
{
Good: `type processTracker struct{}`,
Bad: `type process_tracker struct{}`,
},
{
Good: `type ProcessTracker struct{}`,
Bad: `type Process_Tracker struct{}`,
},
}
}
// Register implements the NodeChecker interface.
func (c *MultiWordIdentNameChecker) Register(fc *FileChecker) {
fc.On(&ast.Ident{}, c)
}
// Check implements the NodeChecker interface.
func (c *MultiWordIdentNameChecker) Check(
node ast.Node,
content string,
report *Report) {
name := node.(*ast.Ident).Name
if isCorrectIdentName(name) {
return
}
report.Errors = append(report.Errors, Error{
Pos: node.Pos(),
Message: fmt.Sprintf("name '%s' is not valid", name),
})
}
func isCorrectIdentName(name string) bool {
return name == "_" ||
exportedNameRegexp.MatchString(name) ||
nonExportedNameRegexp.MatchString(name)
}
var (
exportedNameRegexp = regexp.MustCompile(
`^([A-Z0-9][a-z0-9]*)+$`)
nonExportedNameRegexp = regexp.MustCompile(
`^[a-z0-9]+([A-Z0-9][a-z0-9]*)*$`)
)