-
Notifications
You must be signed in to change notification settings - Fork 0
/
gogen.go
115 lines (96 loc) · 2.05 KB
/
gogen.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
/*
# gogen: Generate Go code with structured blocks and composition
import . "github.com/sunfmin/gogen"
*/
package gogen
import (
"bytes"
"context"
"fmt"
"io"
)
type Code interface {
MarshalCode(ctx context.Context) (r []byte, err error)
}
type CodeFunc func(ctx context.Context) (r []byte, err error)
type Raw string
func (rc Raw) MarshalCode(ctx context.Context) (r []byte, err error) {
r = []byte(rc)
return
}
func (cf CodeFunc) MarshalCode(ctx context.Context) (r []byte, err error) {
return cf(ctx)
}
type SnippetsBuilder struct {
cs []Code
sep string
appendLast bool
}
func Snippets(cs ...Code) (r *SnippetsBuilder) {
r = &SnippetsBuilder{cs: cs}
r.sep = "\n"
r.appendLast = true
return
}
func (b *SnippetsBuilder) Separator(sep string, appendLast bool) (r *SnippetsBuilder) {
b.sep = sep
b.appendLast = appendLast
return b
}
func (b *SnippetsBuilder) Clone() (r *SnippetsBuilder) {
r = &SnippetsBuilder{
cs: b.cs,
sep: b.sep,
appendLast: b.appendLast,
}
return
}
func (b *SnippetsBuilder) Append(Snippets ...Code) (r *SnippetsBuilder) {
b.cs = append(b.cs, Snippets...)
return b
}
func (b *SnippetsBuilder) AppendSnippet(template string, vars ...string) (r *SnippetsBuilder) {
b.Append(Snippet(template, vars...))
return b
}
func (b *SnippetsBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
buf := bytes.NewBuffer(nil)
l := len(b.cs)
for i, c := range b.cs {
if c == nil {
continue
}
err = Fprint(buf, c, ctx)
if err != nil {
return
}
if b.appendLast || i+1 < l {
buf.WriteString(b.sep)
}
}
r = buf.Bytes()
return
}
func Fprint(w io.Writer, c Code, ctx context.Context) (err error) {
if c == nil {
return
}
var b []byte
b, err = c.MarshalCode(ctx)
if err != nil {
return
}
_, err = fmt.Fprint(w, string(b))
return
}
func MustString(c Code, ctx context.Context) (r string) {
buf := bytes.NewBuffer(nil)
err := Fprint(buf, c, ctx)
if err != nil {
panic(err)
}
return buf.String()
}
func Quote(q string) (r string) {
return fmt.Sprintf("%q", q)
}