-
Notifications
You must be signed in to change notification settings - Fork 5
/
gen.go
108 lines (94 loc) · 2.45 KB
/
gen.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
//go:build ignore
// +build ignore
package main
import (
"bytes"
"embed"
"go/format"
"log"
"os"
"regexp"
"text/template"
"github.com/sashamelentyev/usestdlibvars/pkg/analyzer/internal/mapping"
)
//go:embed template/*
var templateDir embed.FS
func main() {
t := template.Must(
template.New("template").
Funcs(map[string]any{"quoteMeta": regexp.QuoteMeta}).
ParseFS(templateDir, "template/*.tmpl"),
)
operations := []struct {
mapping map[string]string
packageName string
templateName string
fileName string
}{
{
mapping: mapping.CryptoHash,
packageName: "crypto_test",
templateName: "test-template.go.tmpl",
fileName: "pkg/analyzer/testdata/src/a/crypto/crypto.go",
},
{
mapping: mapping.HTTPMethod,
packageName: "http_test",
templateName: "test-httpmethod.go.tmpl",
fileName: "pkg/analyzer/testdata/src/a/http/method.go",
},
{
mapping: mapping.HTTPStatusCode,
packageName: "http_test",
templateName: "test-httpstatuscode.go.tmpl",
fileName: "pkg/analyzer/testdata/src/a/http/statuscode.go",
},
{
mapping: mapping.DefaultRPCPath,
packageName: "rpc_test",
templateName: "test-template.go.tmpl",
fileName: "pkg/analyzer/testdata/src/a/rpc/rpc.go",
},
{
mapping: mapping.TimeWeekday,
packageName: "time_test",
templateName: "test-template.go.tmpl",
fileName: "pkg/analyzer/testdata/src/a/time/weekday.go",
},
{
mapping: mapping.TimeMonth,
packageName: "time_test",
templateName: "test-template.go.tmpl",
fileName: "pkg/analyzer/testdata/src/a/time/month.go",
},
{
mapping: mapping.TimeLayout,
packageName: "time_test",
templateName: "test-template.go.tmpl",
fileName: "pkg/analyzer/testdata/src/a/time/layout.go",
},
}
for _, operation := range operations {
data := map[string]any{
"PackageName": operation.packageName,
"Mapping": operation.mapping,
}
if err := execute(t, operation.templateName, data, operation.fileName); err != nil {
log.Fatal(err)
}
}
}
func execute(t *template.Template, templateName string, data any, fileName string) error {
var builder bytes.Buffer
if err := t.ExecuteTemplate(&builder, templateName, data); err != nil {
return err
}
sourceData, err := format.Source(builder.Bytes())
if err != nil {
return err
}
if err := os.WriteFile(fileName, sourceData, os.ModePerm); err != nil {
return err
}
return nil
}