/
stringer.go
93 lines (85 loc) · 2.39 KB
/
stringer.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
package main
import (
_ "embed"
"fmt"
"io"
"text/template"
)
//go:embed templates/stringer.go.tmpl
var stringerTemplateString string
var stringerTemplate *template.Template
func init() {
stringerTemplate = loadTemplate("Stringer", stringerTemplateString)
}
func processStringer(data *typeProcessorData) error {
commands, found := hasComment(data.typeComments, "Stringer")
if found {
_, err := parseStringerConfig(commands, data.structName)
if err != nil {
return err
}
fieldNames := []string{}
for _, fieldName := range data.fieldNames {
commands, found := hasComment(data.fieldComments[fieldName], "Stringer")
if found {
fieldConfig, err := parseStringerFieldConfig(commands, data.structName, fieldName)
if err != nil {
return err
}
if !fieldConfig.exclude {
fieldNames = append(fieldNames, fieldName)
}
} else {
fieldNames = append(fieldNames, fieldName)
}
}
data.addImport("fmt")
debugLogger.Printf("Generating Stringer for %s", data.structName)
data.addCodeWriter(func(wr io.Writer) error {
return stringerTemplate.Execute(wr, map[string]interface{}{
"packageName": data.packageName,
"structName": data.structName,
"fieldNames": fieldNames,
"genericTypes": data.genericTypes,
"genericTypeNames": data.genericTypeNames,
})
})
}
return nil
}
type stringerConfig struct {
}
func parseStringerConfig(commands []string, structName string) (*stringerConfig, error) {
for _, command := range commands {
return nil, fmt.Errorf("invalid command %s on %s Stringer", command, structName)
}
return &stringerConfig{}, nil
}
type stringerFieldConfig struct {
exclude bool
}
func parseStringerFieldConfig(commands []string, structName, fieldName string) (*stringerFieldConfig, error) {
exclude := false
excludeSet := false
for _, command := range commands {
switch command {
case "exclude":
if excludeSet {
return nil, fmt.Errorf("invalid command %s on %s.%s Stringer", command, structName, fieldName)
}
exclude = true
excludeSet = true
case "include":
if excludeSet {
return nil, fmt.Errorf("invalid command %s on %s.%s Stringer", command, structName, fieldName)
}
exclude = false
excludeSet = true
default:
return nil, fmt.Errorf("invalid command %s on %s.%s Stringer", command, structName, fieldName)
}
}
return &stringerFieldConfig{
exclude: exclude,
}, nil
}