-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenutil.go
59 lines (50 loc) · 1.08 KB
/
genutil.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
package main
import (
"bytes"
"embed"
"fmt"
goformat "go/format"
"os"
"strings"
"text/template"
)
const (
templateName = "output.tpl"
)
var (
//go:embed output.tpl
templatesFS embed.FS
)
func generateOutput(pkg string, typ, suffix, tplFilename string, fields []field) ([]byte, error) {
var (
err error
buf bytes.Buffer
)
t := template.New(templateName)
if tplFilename == "" {
t, err = t.ParseFS(templatesFS, templateName)
if err != nil {
return nil, fmt.Errorf("could not parse template: %v", err)
}
} else {
t, err = t.ParseFiles(tplFilename)
if err != nil {
return nil, fmt.Errorf("could not parse template: %v", err)
}
}
err = t.Execute(&buf, map[string]any{
"Package": pkg,
"Type": typ,
"Suffix": suffix,
"Fields": fields,
"CMD": fmt.Sprintf("fielder %s", strings.Join(os.Args[1:], " ")),
})
if err != nil {
return nil, fmt.Errorf("could not execute template: %v", err)
}
formatted, err := goformat.Source(buf.Bytes())
if err != nil {
return nil, fmt.Errorf("could not format source: %v", err)
}
return formatted, nil
}