-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstruct.go
137 lines (112 loc) · 2.49 KB
/
struct.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package jot
import (
"fmt"
"io"
)
type StructSpec struct {
Doc string
Name string
Fields []*FieldSpec
Methods []*MethodSpec
}
type FieldSpec struct {
Doc string
Name string
Typ TypeSpec
Tags map[string]string
}
type MethodSpec struct {
// TODO: Change the way methods are created to support individual docs?
Func *FunctionSpec
RecvName string
Ptr bool
}
func Field(name string, typ TypeSpec) *FieldSpec {
return &FieldSpec{Name: name, Typ: typ, Tags: make(map[string]string)}
}
func (s *FieldSpec) SetTag(key, value string) *FieldSpec {
s.Tags[key] = value
return s
}
func (s *FieldSpec) SetDoc(doc string) *FieldSpec {
s.Doc = doc
return s
}
func (s *FieldSpec) Write(w io.Writer) error {
WriteDoc(w, s.Doc)
io.WriteString(w, fmt.Sprintf("%s ", s.Name))
s.Typ.Write(w)
if len(s.Tags) > 0 {
tags := "`"
for key, value := range s.Tags {
if len(tags) > len("`") {
tags += " "
}
tags += key + ":\"" + value + "\""
}
tags += "`"
io.WriteString(w, " "+tags)
}
return nil
}
func Struct(name string) *StructSpec {
return &StructSpec{Name: name}
}
func (s *StructSpec) AddField(f *FieldSpec) *StructSpec {
s.Fields = append(s.Fields, f)
return s
}
func (s *StructSpec) AddMethod(f *FunctionSpec) *StructSpec {
s.Methods = append(s.Methods, &MethodSpec{Func: f})
return s
}
func (s *StructSpec) AddMethodRecv(recvName string, ptr bool, f *FunctionSpec) *StructSpec {
s.Methods = append(s.Methods, &MethodSpec{Func: f, RecvName: recvName, Ptr: ptr})
return s
}
func (s *StructSpec) SetDoc(doc string) *StructSpec {
s.Doc = doc
return s
}
func (s *StructSpec) TypeSpec() TypeSpec {
return &BaseTypeSpec{name: s.Name}
}
func (s *StructSpec) Write(w io.Writer) error {
WriteDoc(w, s.Doc)
io.WriteString(w, fmt.Sprintf("type %s struct {", s.Name))
if len(s.Fields) > 0 {
io.WriteString(w, "\n")
for _, f := range s.Fields {
f.Write(w)
io.WriteString(w, "\n")
}
}
io.WriteString(w, "}")
io.WriteString(w, "\n")
if len(s.Methods) > 0 {
for i, m := range s.Methods {
if i > 0 {
io.WriteString(w, "\n")
}
io.WriteString(w, "func (")
if m.RecvName != "" {
io.WriteString(w, fmt.Sprintf("%s ", m.RecvName))
}
typ := s.TypeSpec()
if m.Ptr {
typ = Ptr(typ)
}
typ.Write(w)
io.WriteString(w, ") ")
m.Func.writeSignature(w)
io.WriteString(w, " {")
io.WriteString(w, "\n")
m.Func.writeCode(w)
io.WriteString(w, "}")
io.WriteString(w, "\n")
}
}
return nil
}
// write struct
// write methods