-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
95 lines (84 loc) · 1.96 KB
/
file.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
package gogen
import (
"bytes"
"context"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io"
"strconv"
"strings"
)
type FileBuilder struct {
name string
blocks []Code
pkg string
}
func File(name string) (r *FileBuilder) {
r = &FileBuilder{}
r.name = name
return
}
func (b *FileBuilder) Body(cs ...Code) (r *FileBuilder) {
b.blocks = append(b.blocks, cs...)
return b
}
func (b *FileBuilder) BodySnippet(template string, vars ...string) (r *FileBuilder) {
b.Body(Snippet(template, vars...))
return b
}
func (b *FileBuilder) Package(pkg string) (r *FileBuilder) {
b.pkg = pkg
return b
}
func (b *FileBuilder) MarshalCode(ctx context.Context) (r []byte, err error) {
buf := bytes.NewBuffer(nil)
buf.WriteString("package " + b.pkg)
buf.WriteString("\n\n")
err = Fprint(buf, Snippets(b.blocks...), ctx)
if err != nil {
return
}
r = buf.Bytes()
return
}
func (b *FileBuilder) Fprint(w io.Writer, ctx context.Context) (err error) {
src := MustString(b, ctx)
fset := token.NewFileSet()
var f *ast.File
f, err = parser.ParseFile(fset, b.name, src, parser.ParseComments)
if err != nil {
return
}
err = printer.Fprint(w, fset, f)
return
}
func (b *FileBuilder) MustFprint(w io.Writer, ctx context.Context) {
err := b.Fprint(w, ctx)
if err != nil {
hl, _ := strconv.ParseInt(strings.Split(err.Error(), ":")[0], 10, 64)
panic(fmt.Sprintf("%s\n%s", err, codeWithLineNumber(b, hl, ctx)))
}
return
}
func (b *FileBuilder) MustString(ctx context.Context) (r string) {
buf := bytes.NewBuffer(nil)
b.MustFprint(buf, ctx)
return buf.String()
}
func codeWithLineNumber(c Code, highlightLine int64, ctx context.Context) (r string) {
src := MustString(c, ctx)
lines := strings.Split(src, "\n")
linesWithNumber := []string{}
for i, l := range lines {
hl := " "
if int64(i+1) == highlightLine {
hl = ">> "
}
linesWithNumber = append(linesWithNumber, fmt.Sprintf("%s%d: %s", hl, i+1, l))
}
r = strings.Join(linesWithNumber, "\n")
return
}