/
gen.go
98 lines (77 loc) · 1.48 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
package main
import (
_ "embed"
"os"
"reflect"
"text/template"
"xorm.io/xorm"
)
//go:generate bash ./gen.sh
//go:embed template.tmpl
var tmpl string
func main() {
gen(getMethods())
}
type in struct {
Type string
}
type method struct {
Name string
Ins []in
IsVariadic bool
}
func getMethods() (methods []method) {
sessType := reflect.TypeOf((*xorm.Session)(nil))
for i := 0; i < sessType.NumMethod(); i++ {
methodType := sessType.Method(i).Type
// overrides only methods that return exclusively a *xorm.Session
if methodType.NumOut() != 1 {
continue
}
if methodType.Out(0) != sessType {
continue
}
m := method{
Name: sessType.Method(i).Name,
Ins: nil,
IsVariadic: methodType.IsVariadic(),
}
numIn := methodType.NumIn()
if numIn == 0 { // impossible
continue
}
for j := 1; j < numIn; j++ {
inType := methodType.In(j)
if j == numIn-1 && methodType.IsVariadic() {
m.Ins = append(m.Ins, in{
Type: "..." + inType.Elem().String(),
})
} else {
m.Ins = append(m.Ins, in{
Type: inType.String(),
})
}
}
methods = append(methods, m)
}
return
}
func subtract(a, b int) int {
return a - b
}
func gen(data any) {
fnMap := template.FuncMap{
"subtract": subtract,
}
tmplvar := template.Must(
template.New("tmpl").Funcs(fnMap).Parse(tmpl),
)
f, err := os.Create("../session.go")
if err != nil {
panic(err)
}
err = tmplvar.Execute(f, data)
if err != nil {
panic(err)
}
}