-
Notifications
You must be signed in to change notification settings - Fork 38
/
main.go
98 lines (81 loc) · 1.91 KB
/
main.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
package main
import (
"bytes"
"html/template"
"log"
"os"
"path/filepath"
"github.com/iancoleman/strcase"
"github.com/pkg/errors"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/imports"
)
var funcs = template.FuncMap{
"snake": func(str string) string {
return strcase.ToSnake(str)
},
"kebab": func(str string) string {
return strcase.ToKebab(str)
},
"camel": func(str string) string {
return strcase.ToCamel(str)
},
"lowercamel": func(str string) string {
return strcase.ToLowerCamel(str)
},
}
type Data struct {
PackageName string
Output string
Flags Flags
Args []string
}
func main() {
log.SetPrefix("gen: ")
log.SetFlags(0)
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
flags, args, err := Parse(os.Args[1:])
if err != nil {
return err
}
output := flags.String("", "output")
if output == "" {
return errors.New("output option is required")
}
templatePaths := flags.Strings("", "template")
if len(templatePaths) == 0 {
return errors.New("template option is required")
}
pkgs, err := packages.Load(&packages.Config{Dir: filepath.Dir(output)}, ".")
if err != nil {
return errors.Wrap(err, "failed to load package")
}
templ, err := template.New(filepath.Base(templatePaths[0])).Funcs(funcs).ParseFiles(templatePaths...)
if err != nil {
return errors.Wrap(err, "unable to load templates")
}
data := Data{
PackageName: pkgs[0].Name,
Output: output,
Flags: flags,
Args: args,
}
buf := &bytes.Buffer{}
buf.WriteString("// Code generated by gen, DO NOT EDIT.\n\n")
if err := templ.Execute(buf, data); err != nil {
return errors.Wrap(err, "unable to generate code")
}
src, err := imports.Process("", buf.Bytes(), nil)
if err != nil {
return errors.Wrap(err, "unable to gofmt")
}
err = os.WriteFile(output, src, 0644)
if err != nil {
return errors.Wrap(err, "unable to write file")
}
return nil
}