-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
mkrun.go
115 lines (100 loc) · 2.29 KB
/
mkrun.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
// Package mkrun contains some helpers for generation scripts.
package mkrun
import (
"bytes"
"flag"
"fmt"
"go/format"
"io"
"os"
"strings"
"text/template"
"time"
"unicode"
"unicode/utf8"
"github.com/go-faster/errors"
"go.uber.org/multierr"
)
// Config is generation config.
type Config struct {
PackageName string
Data interface{}
}
func generate(w io.Writer, pkgName string, g Generator) error {
start := time.Now()
data, err := g.Data()
if err != nil {
return err
}
collectInfoTime := time.Since(start)
start = time.Now()
buf := bytes.Buffer{}
t, err := template.New("gen").Funcs(template.FuncMap{
"trimPrefix": strings.TrimPrefix,
"trimSuffix": strings.TrimSuffix,
"lowerFirst": func(s string) string {
r, size := utf8.DecodeRuneInString(s)
if r == utf8.RuneError || unicode.IsLower(r) {
return s
}
return string(unicode.ToLower(r)) + s[size:]
},
}).Parse(g.Template())
if err != nil {
return errors.Errorf("parse: %w", err)
}
if err := t.Execute(&buf, Config{
PackageName: pkgName,
Data: data,
}); err != nil {
return errors.Errorf("execute: %w", err)
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
_, _ = os.Stderr.Write(buf.Bytes())
return errors.Errorf("format: %w", err)
}
if _, err := w.Write(formatted); err != nil {
return errors.Errorf("write: %w", err)
}
writeTime := time.Since(start)
fmt.Printf("Generation %s complete, collect time: %s, write time: %s\n",
g.Name(),
collectInfoTime,
writeTime,
)
return nil
}
func run(g Generator) (rErr error) {
set := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
var (
o = set.String("output", "", "output file")
pkgName = set.String("package", os.Getenv("GOPACKAGE"), "package name")
)
g.Flags(set)
if err := set.Parse(os.Args[1:]); err != nil {
return errors.Wrap(err, "parse")
}
if *pkgName == "" {
if *o != "" {
return errors.New("package name is empty")
}
*pkgName = "pkg"
}
var w io.Writer = os.Stdout
if path := *o; path != "" {
f, err := os.Create(path) // #nosec G304
if err != nil {
return err
}
defer multierr.AppendInvoke(&rErr, multierr.Close(f))
w = f
}
return generate(w, *pkgName, g)
}
// Main is generation main function.
func Main(g Generator) {
if err := run(g); err != nil {
panic(err)
}
}