-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_rest_tape_player.go
114 lines (99 loc) · 2.25 KB
/
generate_rest_tape_player.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
109
110
111
112
113
114
//go:build ignore
// +build ignore
package main
import (
"io/ioutil"
"reflect"
"strconv"
"strings"
"github.com/Postcord/rest"
)
const start = `// Code generated by generate_rest_tape_player.go; DO NOT EDIT.
package router
//go:generate go run generate_rest_tape_player.go
import (
"context"
"image"
"github.com/Postcord/objects"
"github.com/Postcord/rest"
)
type restTapePlayer struct {
t TestingT
tape tape
index int
}
`
func strbool(b bool) string {
if b {
return "true"
}
return "false"
}
func generateRestFunctions() string {
letters := []string{"", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}
t := reflect.TypeOf((*rest.Client)(nil))
methodNum := t.NumMethod()
funcs := make([]string, methodNum)
for i := 0; i < methodNum; i++ {
method := t.Method(i)
f := "func (r *restTapePlayer) " + method.Name + "("
// Handle inputs within the signature
inParams := ""
numIn := method.Type.NumIn()
for j := 1; j < numIn; j++ {
if j > 1 {
f += ", "
inParams += ", "
}
l := letters[j]
potentialVard := method.Type.In(j).String()
if method.Type.IsVariadic() && j == numIn-1 {
potentialVard = "..." + method.Type.In(j).Elem().String()
}
f += l + " " + potentialVard
inParams += l
}
f += ") "
// Handle outputs within the signature
outParams := ""
numOut := method.Type.NumOut()
if numOut != 0 {
f += "("
}
for j := 0; j < numOut; j++ {
if j != 0 || numIn != 1 {
outParams += ", "
}
if j > 0 {
f += ", "
}
l := letters[j+numIn]
f += l + " " + method.Type.Out(j).String()
outParams += "&" + l
}
if numOut != 0 {
f += ") "
}
f += `{
if r.index == len(r.tape) {
r.t.Fatal("unexpected ` + method.Name + ` at end of tape")
return // Here for unit tests - in production this will never be hit.
}
action := r.tape[r.index]
r.index++
action.match(r.t, "` + method.Name + `", ` + strbool(method.Type.IsVariadic()) + `, ` + strconv.Itoa(numIn-1) + ", " + inParams + outParams + `)
`
if outParams == "" {
f += "}"
} else {
f += "\treturn\n}"
}
funcs[i] = f
}
return start + strings.Join(funcs, "\n\n") + "\n"
}
func main() {
if err := ioutil.WriteFile("rest_tape_player_gen.go", []byte(generateRestFunctions()), 0666); err != nil {
panic(err)
}
}