-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (68 loc) · 1.59 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
package main
import (
lib "github.com/nicjohnson145/strugen/strugenlib"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"strings"
"os"
"path"
"text/template"
)
func main() {
if err := cmd().Execute(); err != nil {
log.Fatal(err)
}
}
func cmd() *cobra.Command {
opts := strugenOpts{}
root := &cobra.Command{
Use: "strugen",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
run(opts, args[0])
},
}
root.Flags().StringSliceVarP(&opts.Types, "type", "t", []string{}, "Types to generate for")
return root
}
type strugenOpts struct {
Types []string
}
type renderVars struct {
Pkg string
Structs []lib.Struct
}
func HasTagValue(tagValues string, query string) bool {
return lo.Contains(strings.Split(tagValues, ","), query)
}
func run(opts strugenOpts, templateFile string) {
// Parse the user supplied template
tmpl, err := template.New(path.Base(templateFile)).Funcs(template.FuncMap{"HasTagValue": HasTagValue}).ParseFiles(templateFile)
if err != nil {
log.Fatalf("error parsing template: %v", err)
}
gen := lib.Generator{
Types: opts.Types,
TagName: "strugen",
}
structs, pkgname, err := gen.FindStructs()
if err != nil {
log.Fatalf("error finding structs: %v", err)
}
f, err := os.Create(fileName())
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
err = tmpl.Execute(f, renderVars{
Pkg: pkgname,
Structs: lo.Values(structs),
})
if err != nil {
log.Fatal("error rendering template: %v", err)
}
}
func fileName() string {
return "zzz_generated_strugen.go"
}