-
Notifications
You must be signed in to change notification settings - Fork 100
/
lint_struct_literal.go
49 lines (46 loc) · 1.06 KB
/
lint_struct_literal.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
package main
import (
"go/ast"
"go/token"
"reflect"
"slices"
)
func lintStructLiteralVariable(compositeLit *ast.CompositeLit, fileSet *token.FileSet, issues *Issues) {
structType, ok := compositeLit.Type.(*ast.Ident)
if !ok {
return
}
structName := structType.Name
if slices.Contains(ignoreTypes, structName) {
return
}
fieldNames := structInstantiationFieldNames(compositeLit)
if len(fieldNames) == 0 {
return
}
sortedFields := make([]string, len(fieldNames))
copy(sortedFields, fieldNames)
slices.Sort(sortedFields)
if reflect.DeepEqual(fieldNames, sortedFields) {
return
}
*issues = append(*issues, issue{
expected: sortedFields,
position: fileSet.Position(compositeLit.Pos()),
})
}
func structInstantiationFieldNames(compositeLit *ast.CompositeLit) []string {
result := make([]string, 0, len(compositeLit.Elts))
for _, expr := range compositeLit.Elts {
kvExpr, ok := expr.(*ast.KeyValueExpr)
if !ok {
continue
}
ident, ok := kvExpr.Key.(*ast.Ident)
if !ok {
continue
}
result = append(result, ident.Name)
}
return result
}