forked from haguro/elevenlabs-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
216 lines (199 loc) · 5.25 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package main
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"text/template"
)
const (
pkgName = "elevenlabs"
receiverType = "Client"
defaultReceiver = "getDefaultClient()"
genFileName = "shorthand.go"
genFileTemplate = `// Code generated by {{.GeneratorPath}}; DO NOT EDIT.
// Run 'go generate' after adding new methods with a '{{.ReceiverType}}' pointer receiver.
package elevenlabs
import "io"
{{range .Functions}}
// {{.FuncIdent}} calls the {{.FuncIdent}} method on the default client.
func {{.FuncIdent}}{{.FuncParams}}{{.FuncResults}} {
{{if .FuncResults}}return {{end}}{{.MethodReceiver}}.{{.FuncIdent}}{{.FuncArgs}}
}
{{end}}`
)
var sourceFiles []string = []string{"client.go", "models.go", "errors.go"}
type proxyFuncFile struct {
GeneratorPath string
ReceiverType string
Functions []proxyFunc
}
type proxyFunc struct {
FuncIdent, FuncParams, FuncArgs, FuncResults, MethodReceiver string
}
func main() {
b := bytes.Buffer{}
pkg, err := parsePackage(pkgName, ".", []string{genFileName})
if err != nil {
log.Fatal(err)
}
n, err := generate(&b, pkg.Files)
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile(genFileName, b.Bytes(), 0644); err != nil {
log.Fatal(err)
}
fmt.Printf("Wrote %d functions to %s\n", n, genFileName)
}
func generate(w io.Writer, pkgFiles map[string]*ast.File) (int, error) {
var total int
g, err := getCurrentRelPath()
if err != nil {
return 0, err
}
sFile := proxyFuncFile{
GeneratorPath: g,
ReceiverType: receiverType,
}
for _, pf := range pkgFiles {
methods := ptrRcvMethods(pf, receiverType)
for _, m := range methods {
sFile.Functions = append(sFile.Functions, proxyFunc{
FuncIdent: m.Name.Name,
FuncParams: genTypedParams(m.Type.Params),
FuncArgs: genFuncArgs(m.Type.Params),
FuncResults: genFuncReturnTypes(m.Type.Results),
MethodReceiver: defaultReceiver,
})
}
total += len(methods)
}
t := template.Must(template.New("").Parse(genFileTemplate))
if err := t.Execute(w, sFile); err != nil {
return 0, err
}
return total, nil
}
func parsePackage(pkgName string, path string, excludeFiles []string) (*ast.Package, error) {
excludeFunc := func(fi fs.FileInfo) bool {
for _, f := range excludeFiles {
if fi.Name() == f {
return false
}
}
return true
}
pkgs, err := parser.ParseDir(token.NewFileSet(), path, excludeFunc, 0)
if err != nil {
return nil, fmt.Errorf("failed to parse directory %q: %w", path, err)
}
pkg, ok := pkgs[pkgName]
if !ok {
return nil, fmt.Errorf("package %s not found in directory", pkgName)
}
return pkg, nil
}
func ptrRcvMethods(f *ast.File, receiverTypeStr string) []*ast.FuncDecl {
methodDecls := []*ast.FuncDecl{}
for _, decl := range f.Decls {
if funcDecl, ok := decl.(*ast.FuncDecl); ok &&
funcDecl.Name.IsExported() &&
funcDecl.Recv != nil && len(funcDecl.Recv.List) > 0 { //If declaration is a exported function that has a receiver (i.e. method)
if ptrRecvExpr, ok := funcDecl.Recv.List[0].Type.(*ast.StarExpr); ok &&
fmt.Sprint(ptrRecvExpr.X) == receiverTypeStr {
methodDecls = append(methodDecls, funcDecl)
}
}
}
return methodDecls
}
func genTypedParams(fl *ast.FieldList) string {
if fl.List == nil {
return "()"
}
params := make([]string, len(fl.List))
for i, f := range fl.List {
names := make([]string, len(f.Names))
for j, fn := range f.Names {
names[j] = fn.Name
}
paramNames := strings.Join(names, ", ")
if paramNames != "" {
paramNames += " "
}
params[i] = paramNames + exprToString(f.Type)
}
return fmt.Sprintf("(%s)", strings.Join(params, ", "))
}
func genFuncArgs(fl *ast.FieldList) string {
if fl.List == nil {
return "()"
}
args := make([]string, len(fl.List))
for i, p := range fl.List {
names := make([]string, len(p.Names))
for j, pName := range p.Names {
names[j] = pName.Name
}
paramNames := strings.Join(names, ", ")
switch p.Type.(type) {
case *ast.Ellipsis:
args[i] = fmt.Sprintf("%s...", paramNames)
default:
args[i] = paramNames
}
}
return fmt.Sprintf("(%s)", strings.Join(args, ", "))
}
func genFuncReturnTypes(fl *ast.FieldList) string {
if fl == nil || fl.List == nil {
return ""
}
ret := make([]string, len(fl.List))
for i, f := range fl.List {
ret[i] = exprToString(f.Type)
}
if len(ret) == 1 {
return " " + ret[0]
}
return fmt.Sprintf(" (%s)", strings.Join(ret, ", "))
}
func exprToString(expr ast.Expr) string {
switch fieldType := expr.(type) {
case *ast.ArrayType:
return fmt.Sprintf("[]%s", exprToString(fieldType.Elt))
case *ast.Ellipsis:
return fmt.Sprintf("...%s", exprToString(fieldType.Elt))
case *ast.StarExpr:
return fmt.Sprintf("*%s", exprToString(fieldType.X))
case *ast.FuncType:
return fmt.Sprintf("func%s%s", genTypedParams(fieldType.Params), genFuncReturnTypes(fieldType.Results))
case *ast.SelectorExpr:
return fmt.Sprintf("%s.%s", fieldType.X, fieldType.Sel)
}
return fmt.Sprintf("%s", expr)
}
func getCurrentRelPath() (string, error) {
var path string
_, filename, _, ok := runtime.Caller(0)
if ok {
currentDir, err := os.Getwd()
if err != nil {
return "", err
}
path, err = filepath.Rel(currentDir, filename)
if err != nil {
return "", err
}
}
return path, nil
}