-
Notifications
You must be signed in to change notification settings - Fork 2
/
method.go
81 lines (72 loc) · 2.24 KB
/
method.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
package getdoc
import (
"fmt"
"io"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
)
// Method represents method documentation.
type Method struct {
Name string `json:"name"`
Description []string `json:"description,omitempty"`
Links []string `json:"links,omitempty"`
Parameters map[string]ParamDescription `json:"parameters,omitempty"`
Errors []Error `json:"errors,omitempty"`
BotCanUse bool `json:"bot_can_use,omitempty"`
}
// Error represent possible error documentation.
type Error struct {
Code int `json:"code"`
Type string `json:"type"`
Description string `json:"description,omitempty"`
}
func docBotCanUser(doc *goquery.Document) bool {
return doc.Find("#bots-can-use-this-method").Length() > 0
}
// docErrors extract error code documentation from document.
func docErrors(doc *goquery.Document) []Error {
var output []Error
docTableAfterFunc(doc, func(s *goquery.Selection) bool {
return s.Find("#possible-errors").Length() > 0 ||
// Some pages have no such selector, so we try to detect "Possible errors" header by text.
//
// TODO(tdakkota): try to parse attributes
strings.HasPrefix(s.Text(), "Possible errors")
}).Each(func(i int, row *goquery.Selection) {
var rowContents []string
row.Find("td").Each(func(i int, column *goquery.Selection) {
rowContents = append(rowContents, column.Text())
})
if len(rowContents) != 3 {
return
}
code, err := strconv.Atoi(rowContents[0])
if err != nil {
return
}
e := Error{
Code: code,
Type: strings.TrimSpace(rowContents[1]),
Description: strings.TrimSpace(rowContents[2]),
}
output = append(output, e)
})
return output
}
// ParseMethod extracts method documentation from reader.
func ParseMethod(reader io.Reader) (*Method, error) {
doc, err := goquery.NewDocumentFromReader(reader)
if err != nil {
return nil, fmt.Errorf("failed to parse document: %w", err)
}
desc, links := docDescription(doc)
return &Method{
Name: docTitle(doc),
Description: desc,
Links: links,
Parameters: docParams(doc),
Errors: docErrors(doc),
BotCanUse: docBotCanUser(doc),
}, nil
}