-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (85 loc) · 2.08 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
99
100
101
102
103
104
package main
import (
"bytes"
"flag"
"fmt"
"go/parser"
"go/printer"
"go/token"
"log"
"os"
"os/exec"
"strings"
"text/template"
"github.com/lumochift/optgen/generator"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func titleCase(s string) string {
return cases.Title(language.Und).String(s)
}
var (
sourceFile, tagName, structName string
writeMode, allFields, showVersion bool
version string = "dev"
funcMap = template.FuncMap{
"title": titleCase,
"toLower": strings.ToLower,
}
)
func initCLI() {
flag.StringVar(&sourceFile, "file", "", "path file")
flag.StringVar(&tagName, "tag", "opt", "custom tag")
flag.StringVar(&structName, "name", "", "struct name")
flag.BoolVar(&writeMode, "w", false, "enable write mode")
flag.BoolVar(&showVersion, "v", false, "show version")
flag.BoolVar(&allFields, "all", false, "generate all fields")
flag.Parse()
}
func main() {
initCLI()
if showVersion {
fmt.Printf("version: %s", version)
return
}
const exampleMessage = "e.g: optgen -file sample-file.go -name Thing"
if sourceFile == "" || structName == "" {
log.Fatalf("Source file and struct name must be provided.\n%s", exampleMessage)
}
source, err := os.ReadFile(sourceFile)
if err != nil {
log.Fatal(err)
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", source, 0)
if err != nil {
log.Fatal(err)
}
type TemplateData struct {
StructName string
Tags []generator.Tag
}
if allFields {
tagName = "_all_"
}
tags := generator.GetTags(f, structName, tagName)
tmpl := template.Must(template.New("generator").Funcs(funcMap).Parse(generator.CodeTemplate))
var buf bytes.Buffer
if err := tmpl.Execute(&buf, TemplateData{
Tags: tags,
StructName: structName,
}); err != nil {
log.Panic(err)
}
if !writeMode {
fmt.Println(buf.String())
return
}
var sourceBuf bytes.Buffer
printer.Fprint(&sourceBuf, fset, f)
if err := os.WriteFile(sourceFile, append(sourceBuf.Bytes(), buf.Bytes()...), 0644); err != nil {
log.Println(err)
}
// format generated code
exec.Command("gofmt", "-s", "-w", sourceFile)
}