-
Notifications
You must be signed in to change notification settings - Fork 0
/
makeset.go
69 lines (63 loc) · 1.27 KB
/
makeset.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 geco
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/token"
"io"
)
type MakeSet struct {
fileSet *token.FileSet
file *ast.File
typeName string
output io.Writer
}
func (m *MakeSet) Run() error {
// find fields
var fields []*ast.Field
var name string
ast.Inspect(m.file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.Ident:
name = n.Name // save name
case *ast.StructType:
if name == m.typeName {
fields = n.Fields.List
}
}
return true
})
if len(fields) == 0 {
return fmt.Errorf("type %s: not found", m.typeName)
}
var buf bytes.Buffer
for _, field := range fields {
name := field.Names[0].Name
if !isPrivate(name) {
continue
}
rcv := receiver(m.typeName)
fmt.Fprint(&buf, "func ")
fmt.Fprint(&buf, "(")
fmt.Fprint(&buf, rcv)
fmt.Fprint(&buf, " ")
fmt.Fprint(&buf, "*")
fmt.Fprint(&buf, m.typeName)
fmt.Fprint(&buf, ") ")
fmt.Fprint(&buf, "Set")
fmt.Fprint(&buf, makePublic(name))
fmt.Fprint(&buf, "(v ")
format.Node(&buf, m.fileSet, field.Type)
fmt.Fprint(&buf, ") ")
fmt.Fprint(&buf, "{ ")
fmt.Fprint(&buf, rcv)
fmt.Fprint(&buf, ".")
fmt.Fprint(&buf, name)
fmt.Fprint(&buf, " = v ")
fmt.Fprint(&buf, "}")
fmt.Fprintln(&buf)
}
_, err := io.Copy(m.output, &buf)
return err
}