-
Notifications
You must be signed in to change notification settings - Fork 99
/
gen.go
423 lines (349 loc) · 10.6 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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package main
import (
"fmt"
"go/format"
"os"
"regexp"
"sort"
"strings"
"unicode"
)
type APIDescription struct {
Types map[string]TypeDescription `json:"types"`
Methods map[string]MethodDescription `json:"methods"`
}
type TypeDescription struct {
Name string `json:"name"`
Description []string `json:"description"`
Fields []Field `json:"fields"`
Href string `json:"href"`
Subtypes []string `json:"subtypes"`
SubtypeOf []string `json:"subtype_of"`
}
func (td TypeDescription) receiverName() string {
return receiver(td.Name)
}
func receiver(n string) string {
var rs []rune
for _, r := range n {
if unicode.IsUpper(r) {
rs = append(rs, r)
}
}
return strings.ToLower(string(rs))
}
func (td TypeDescription) sentByAPI(d APIDescription) bool {
checked := map[string]bool{}
for _, m := range d.Methods {
for _, r := range m.Returns {
if isTgArray(r) {
r = strings.TrimPrefix(r, "Array of ")
}
if r == td.Name {
return true
}
child, ok := d.Types[r]
if !ok || checked[r] {
continue
}
if child.usesChildType(d, td.Name, []string{td.Name}) {
return true
}
checked[r] = true
}
}
return false
}
func (td TypeDescription) usesChildType(d APIDescription, typeName string, skip []string) bool {
for _, f := range td.Fields {
for _, t := range f.Types {
if isTgArray(t) {
t = strings.TrimPrefix(t, "Array of ")
}
if td.isChildType(d, t, typeName, skip) {
return true
}
}
}
for _, t := range td.Subtypes {
if td.isChildType(d, t, typeName, skip) {
return true
}
}
return false
}
func (td TypeDescription) isChildType(d APIDescription, t string, typeName string, skip []string) bool {
if t == typeName {
return true
}
if contains(t, skip) {
return false
}
if child, ok := d.Types[t]; ok && t != td.Name {
if child.usesChildType(d, typeName, append(skip, td.Name)) {
return true
}
}
return false
}
func (td TypeDescription) getTypeNameFromParent(parentType string) string {
// Telegram inconsistencies
if td.Name == "ChatMemberOwner" {
return "creator"
} else if td.Name == "ChatMemberBanned" {
return "kicked"
}
typeName := strings.TrimPrefix(td.Name, parentType)
typeName = strings.TrimPrefix(typeName, "Cached") // some of them are "Cached"
typeName = strings.TrimSuffix(typeName, "Field") // some of them are "Field"
return titleToSnake(typeName)
}
func (td TypeDescription) getConstantFieldFromParent(d APIDescription) (string, error) {
if len(td.Subtypes) == 0 {
return "", fmt.Errorf("expected %s to be a parent", td.Name)
}
subTypes, err := getTypesByName(d, td.Subtypes)
if err != nil {
return "", fmt.Errorf("failed to get parent type %s: %w", td.Name, err)
}
common := getCommonFields(subTypes)
if len(common) == 0 {
return "", fmt.Errorf("no common fields for parenttype %s", td.Name)
}
return getConstantFieldFromCommons(d, common)
}
func getConstantFieldFromCommons(d APIDescription, common []Field) (string, error) {
for _, v := range common {
s, err := v.getPreferredType(d)
if err != nil {
return "", err
}
// These may be better as hand-picked fields by name (type/status/source) rather than type
if s == "string" {
return v.Name, nil
}
}
return "", nil
}
func (m MethodDescription) docs() string {
return docs(strings.Title(m.Name), m.Href, m.Description)
}
func (td TypeDescription) docs() string {
return docs(td.Name, td.Href, td.Description)
}
func docs(name string, href string, ds []string) string {
bd := strings.Builder{}
// Start by mentioning name, with docs link.
bd.WriteString(fmt.Sprintf("\n// %s (%s)", name, href))
// add a newline for nice paragraphing and readability
bd.WriteString("\n//")
for _, text := range ds {
// if this is a list item, we should add extra indentation to make sure it renders right in the docs pages.
if strings.HasPrefix(text, "- ") {
text = " " + text
}
bd.WriteString("\n// " + text)
}
return bd.String()
}
type MethodDescription struct {
Name string `json:"name"`
Fields []Field `json:"fields"`
Returns []string `json:"returns"`
Description []string `json:"description"`
Href string `json:"href"`
}
type Field struct {
Name string `json:"name"`
Types []string `json:"types"`
Required bool `json:"required"`
Description string `json:"description"`
}
var usernameDocsMatcher = regexp.MustCompile(` +(or username.*)?\(.+ @[a-z]+\)`)
func (f Field) GetDescription() string {
if usernameDocsMatcher.MatchString(f.Description) {
return strings.TrimSpace(usernameDocsMatcher.ReplaceAllString(f.Description, ""))
}
return f.Description
}
func (f Field) isConstantField(d APIDescription, tgType TypeDescription) bool {
for _, parent := range tgType.SubtypeOf {
constantField, err := d.Types[parent].getConstantFieldFromParent(d)
if err != nil || constantField == "" {
continue
}
if constantField == f.Name {
return true
}
}
return false
}
const (
// These are all base telegram types which make sense in other languages.
tgTypeString = "String"
tgTypeBoolean = "Boolean"
tgTypeFloat = "Float"
tgTypeInteger = "Integer"
// These are all custom telegram types.
tgTypeMessage = "Message"
tgTypeFile = "File"
tgTypeInputFile = "InputFile"
tgTypeInputMedia = "InputMedia"
// This is actually a custom type.
tgTypeReplyMarkup = "ReplyMarkup"
)
func generate(d APIDescription) error {
// TODO: Use golang templates instead of string builders
if err := generateTypes(d); err != nil {
return fmt.Errorf("failed to generate types: %w", err)
}
if err := generateMethods(d); err != nil {
return fmt.Errorf("failed to generate helpers: %w", err)
}
if err := generateHelpers(d); err != nil {
return fmt.Errorf("failed to generate helpers: %w", err)
}
if err := generateConsts(d); err != nil {
return fmt.Errorf("failed to generate consts: %w", err)
}
return nil
}
func writeGenToFile(file strings.Builder, filename string) error {
write, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to open file %s: %w", filename, err)
}
bs := []byte(file.String())
_, err = write.WriteAt(bs, 0)
if err != nil {
return fmt.Errorf("failed to write unformatted file %s: %w", filename, err)
}
fmted, err := format.Source(bs)
if err != nil {
return fmt.Errorf("failed to format file %s: %w", filename, err)
}
err = write.Truncate(0)
if err != nil {
return fmt.Errorf("failed to truncate file %s: %w", filename, err)
}
_, err = write.WriteAt(fmted, 0)
if err != nil {
return fmt.Errorf("failed to write final file %s: %w", filename, err)
}
return nil
}
func orderedTgTypes(d APIDescription) []string {
types := make([]string, 0, len(d.Types))
for k := range d.Types {
types = append(types, k)
}
sort.Strings(types)
return types
}
func orderedMethods(d APIDescription) []string {
methods := make([]string, 0, len(d.Methods))
for k := range d.Methods {
methods = append(methods, k)
}
sort.Strings(methods)
return methods
}
func isTgType(d APIDescription, goType string) bool {
_, ok := d.Types[goType]
return ok
}
// isTgStructType returns false if there are subtypes (ie, is NOT an interface).
func isTgStructType(d APIDescription, goType string) bool {
t, ok := d.Types[goType]
if !ok {
return false
}
return len(t.Subtypes) == 0
}
func (f Field) getPreferredType(d APIDescription) (string, error) {
if f.Name == "media" {
if len(f.Types) == 1 && f.Types[0] == "String" {
return tgTypeInputFile, nil
}
var arrayType bool
// TODO: check against API description type
for _, t := range f.Types {
arrayType = arrayType || isTgArray(t)
if !strings.Contains(t, tgTypeInputMedia) {
return "", fmt.Errorf("mediatype %s is not of kind InputMedia for field %s", t, f.Name)
}
}
if arrayType {
return "[]" + tgTypeInputMedia, nil
}
return tgTypeInputMedia, nil
}
if f.Name == "reply_markup" {
if len(f.Types) == 4 {
// TODO: this should check if the values are replymarkup children, instead of checking length
// Custom type used to handle the fact that reply_markup can take one of:
// InlineKeyboardMarkup
// ReplyKeyboardMarkup
// ReplyKeyboardRemove
// ForceReply
return tgTypeReplyMarkup, nil
} else if len(f.Types) == 1 {
return toGoType(f.Types[0]), nil
} else {
return "", fmt.Errorf("unable to handle reply_markup field with types: %v", f.Types)
}
}
if len(f.Types) == 1 {
goType := toGoType(f.Types[0])
// Optional TG types should be pointers, unless they're already an interface type.
if !f.Required && isTgType(d, f.Types[0]) && !isArray(goType) && goType != tgTypeInputFile {
rawType, err := getTypeByName(d, f.Types[0])
if err != nil {
return "", fmt.Errorf("failed to get parent for %s: %w", f.Types[0], err)
}
if len(rawType.Subtypes) == 0 {
return "*" + goType, nil
}
}
// Some fields are marked as "May be empty", in which case the empty values are still meaningful.
// These should be handled as pointers, so we can differentiate the empty case.
if (strings.Contains(f.Description, "May be empty") || strings.Contains(f.Description, "If not specified")) && !(isPointer(goType) || isArray(goType)) {
// If "not specified" has the same outcome as "empty", then we dont need to use a pointer.
if strings.Contains(f.Description, "If not specified or empty") {
return goType, nil
}
// Note: we override the AnswerCallbackQuery 'text' field to not be a pointer, because "" and nil have the same outcome here.
if f.Name == "text" && strings.Contains(f.Description, "nothing will be shown") {
return goType, nil
}
return "*" + goType, nil
}
return goType, nil
}
if len(f.Types) == 2 {
if f.Types[0] == tgTypeInputFile && f.Types[1] == tgTypeString {
return toGoType(f.Types[0]), nil
} else if f.Types[0] == tgTypeInteger && f.Types[1] == tgTypeString {
return toGoType(f.Types[0]), nil
}
}
return "", fmt.Errorf("unable to choose one of %v for field %s", f.Types, f.Name)
}
func (m MethodDescription) GetReturnTypes(d APIDescription) ([]string, error) {
// We currently only support dual returns for msg+bool
if len(m.Returns) >= 2 && !(len(m.Returns) == 2 && m.Returns[0] == tgTypeMessage && m.Returns[1] == tgTypeBoolean) {
return nil, fmt.Errorf("no support for multiple returns for types %s", m.Name)
}
var retTypes []string
for _, prefRetVal := range m.Returns {
goRetType := toGoType(prefRetVal)
if isTgType(d, goRetType) && len(d.Types[prefRetVal].Subtypes) == 0 {
goRetType = "*" + goRetType
}
retTypes = append(retTypes, goRetType)
}
return retTypes, nil
}
func (m MethodDescription) optsName() string {
return snakeToTitle(m.Name) + "Opts"
}