-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
251 lines (203 loc) · 5.47 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
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"go/format"
"io"
"log"
"net/http"
"os"
"strings"
"text/template"
"time"
)
func main() {
err := writeDictionary()
if err != nil {
panic(err)
}
}
// Hard-coded exceptions that cause bad mappings.
var ignore = map[string]bool{
"drop-down": true,
"datatable": true,
"for": true,
"this": true,
}
// run this in generator_test.go.
func writeDictionary() error {
pageSize := 100
// Used in the template below
mappings := make(map[string]string)
seen := make(map[string]bool)
for site, count := range sites {
pages := count / pageSize
for page := 1; page <= pages; page++ {
wrapper, err := fetchTags(page, pageSize, site)
if err != nil {
return err
}
// Synonyms first
for _, tag := range wrapper.Items {
if tag.Moderator {
// We don't want those
continue
}
if len(tag.Synonyms) == 0 {
continue
}
canonical := tag.Name // tag name
var filtered []string
for _, synonym := range tag.Synonyms {
if ignore[synonym] {
continue
}
// Split up the grams to allow calculation max gram length by the Synonyms constructor
synonym = strings.ReplaceAll(synonym, "-", " ")
filtered = append(filtered, synonym)
}
if len(filtered) == 0 {
// Skip it
continue
}
for _, synonym := range filtered {
seen[synonym] = true
}
// Comma-separated string, a format Synonyms can handle
synonyms := strings.Join(filtered, ", ")
mappings[synonyms] = canonical
}
// Avoid duplicates; since we are querying multiple sites, duplication is common.
for _, tag := range wrapper.Items {
if tag.Moderator {
// We don't want those
continue
}
canonical := tag.Name // tag name
// Split up the grams to allow calculation max gram length by the Synonyms constructor
synonym := strings.ReplaceAll(tag.Name, "-", " ")
if ignore[synonym] {
continue
}
if seen[synonym] {
// Ignore ones we've seen
continue
}
// We want to identify tags as canonical even if they don't map to something different
mappings[synonym] = canonical
}
if !wrapper.HasMore {
break
}
if wrapper.Backoff > 10 {
// That's too much for this run
err := fmt.Errorf(
"abort: received a message to backoff %d seconds from api.stackexchange.com. That's too much, try again later. See http://api.stackexchange.com/docs/throttle",
wrapper.Backoff,
)
return err
}
// Try to avoid throttling
if wrapper.Backoff > 0 {
backoff := time.Duration(wrapper.Backoff) * time.Second
log.Printf("Backing off %d seconds, per backoff message from api.stackexchange.com. See http://api.stackexchange.com/docs/throttle", wrapper.Backoff)
time.Sleep(backoff)
}
// A little extra to be safe
// Guideline in the documentation is 30 requests/sec: http://api.stackexchange.com/docs/throttle
time.Sleep(50 * time.Millisecond)
}
}
var source bytes.Buffer
tmplErr := tmpl.Execute(&source, mappings)
if tmplErr != nil {
return tmplErr
}
// Break up some lines for readability
split := strings.ReplaceAll(source.String(), `", "`, `",
"`)
split = strings.ReplaceAll(split, `{"`, `{
"`)
split = strings.ReplaceAll(split, `"}`, `",
}`)
formatted, fmtErr := format.Source([]byte(split))
if fmtErr != nil {
return fmtErr
}
f, createErr := os.Create("generated.go")
if createErr != nil {
return createErr
}
defer f.Close()
_, writeErr := f.Write(formatted)
if writeErr != nil {
return writeErr
}
return nil
}
var tmpl = template.Must(template.New("").Parse(`
package stackoverflow
// This file is generated. Best not to modify it, as it will likely be overwritten.
var mappings = {{ printf "%#v" . }}
`))
// sites to query, with the number of tags to get, based on eyeballing how many of the top x are 'interesting'.
var sites = map[string]int{
"stackoverflow": 2000,
// "serverfault": 600,
// "gamedev": 300,
// "datascience": 200,
}
var tagsURL = "http://api.stackexchange.com/2.2/tags?page=%d&pagesize=%d&order=desc&sort=popular&site=%s&filter=!4-J-du8hXSkh2Is1a&key=%s"
//nolint:gosec // not our api key, present in upstream repo
var stackExchangeAPIKey = "*AbAX7kb)BKJTlmKgb*Tkw(("
var client = http.Client{
Timeout: time.Second * 3, // Maximum of 2 secs
}
var empty = wrapper{}
func fetchTags(page, pageSize int, site string) (wrapper, error) {
ctx := context.Background()
if page == 0 {
page = 1
}
if pageSize == 0 {
pageSize = 100
}
url := fmt.Sprintf(tagsURL, page, pageSize, site, stackExchangeAPIKey)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return empty, err
}
r, httpErr := client.Do(req)
if httpErr != nil {
return empty, httpErr
}
defer r.Body.Close()
body, readErr := io.ReadAll(r.Body)
if readErr != nil {
return empty, readErr
}
rv := wrapper{}
jsonErr := json.Unmarshal(body, &rv)
if jsonErr != nil {
return empty, jsonErr
}
if len(rv.ErrorName) > 0 || len(rv.ErrorMessage) > 0 {
return rv, fmt.Errorf("%s: %s", rv.ErrorName, rv.ErrorMessage)
}
return rv, nil
}
type item struct {
Name string `json:"name"`
Synonyms []string `json:"synonyms"`
Moderator bool `json:"is_moderator_only"`
}
type wrapper struct {
Items []item `json:"items"`
HasMore bool `json:"has_more"`
ErrorName string `json:"error_name"`
ErrorMessage string `json:"error_message"`
// In seconds
Backoff int `json:"backoff"`
}