-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimports.go
57 lines (48 loc) · 1.03 KB
/
imports.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
package gogen
import (
"bytes"
"context"
"fmt"
)
type ImportBuilder struct {
blocks []Code
}
func Imports(imps ...string) (r *ImportBuilder) {
r = &ImportBuilder{}
for _, im := range imps {
imr := []rune(im)
if imr[len(imr)-1] != '"' {
im = fmt.Sprintf("%q", im)
}
r.blocks = append(r.blocks, Raw(im))
}
return
}
func (b *ImportBuilder) Body(imps ...Code) (r *ImportBuilder) {
b.blocks = append(b.blocks, imps...)
return b
}
func (b *ImportBuilder) BodySnippet(template string, vars ...string) (r *ImportBuilder) {
b.Body(Snippet(template, vars...))
return b
}
func (b *ImportBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
if len(b.blocks) == 0 {
return
}
buf := bytes.NewBuffer(nil)
buf.WriteString("import (\n")
err = Fprint(buf, Snippets(b.blocks...), ctx)
if err != nil {
panic(err)
}
buf.WriteString(")\n")
r = buf.Bytes()
return
}
func ImportAs(as string, imp string) (r Code) {
if len(as) == 0 {
return Raw(fmt.Sprintf(`"%s"`, imp))
}
return Raw(fmt.Sprintf(`%s "%s"`, as, imp))
}