forked from dbohdan/automatic-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
render-template.go
286 lines (268 loc) · 6.59 KB
/
render-template.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
// A script to generate a README.md from README.md.template and the data
// in data/. It fetches statistics about the repositories from GitHub.
// Copyright (c) dbohdan, 2017.
// License: MIT.
package main
import (
"bytes"
"encoding/json"
"fmt"
"html"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"text/template"
"time"
"github.com/olekukonko/tablewriter"
"gopkg.in/yaml.v2"
)
type entry struct {
Name string
URL string
DB string
API string
Lang string
License string
Stats string
Notes string
}
type table [][]string
type repo struct {
Name string
Owner string
}
type projStats struct {
Name string
DefaultBranchRef struct {
Target struct {
AuthoredDate time.Time
History struct {
TotalCount int
}
}
}
Stargazers struct {
TotalCount int
}
}
type gitHubResponse struct {
Data map[string]projStats
Message string
Errors []map[string]interface{}
}
// Load entry data from the YAML files that match the glob pattern.
func loadEntries(glob string) (entries []entry, err error) {
matches, err := filepath.Glob(glob)
if err != nil {
return nil, err
}
entries = make([]entry, len(matches))
for i, match := range matches {
data, err := ioutil.ReadFile(match)
if err != nil {
return nil, err
}
yaml.Unmarshal(data, &entries[i])
}
return entries, nil
}
// Convert each entry into a table row.
func entriesToTable(entries []entry) (tbl table) {
tbl = make(table, len(entries)+1)
tbl[0] = make([]string, 7)
tbl[0][0] = "Project name/link"
tbl[0][1] = "Database(s) supported"
tbl[0][2] = "API type"
tbl[0][3] = "Implementation language"
tbl[0][4] = "License"
tbl[0][5] = "GitHub stats"
tbl[0][6] = "Notes"
for i, ent := range entries {
j := i + 1
tbl[j] = make([]string, 7)
tbl[j][0] = fmt.Sprintf("[%s](%s)",
html.EscapeString(ent.Name),
html.EscapeString(ent.URL))
tbl[j][1] = html.EscapeString(ent.DB)
tbl[j][2] = html.EscapeString(ent.API)
tbl[j][3] = html.EscapeString(ent.Lang)
tbl[j][4] = html.EscapeString(ent.License)
// Deliberately allow HTML in Stats and Notes.
tbl[j][5] = ent.Stats
tbl[j][6] = ent.Notes
}
return tbl
}
// Convert a table to its Markdown representation. Each column in the returned
// Markdown will have a consistent width to be more readable as plain text.
func (tbl table) Format() (res string) {
buffer := bytes.NewBufferString("")
tw := tablewriter.NewWriter(buffer)
tw.SetHeader(tbl[0])
tw.SetAutoFormatHeaders(false)
tw.SetAutoWrapText(false)
tw.SetBorders(tablewriter.Border{
Left: true,
Top: false,
Right: true,
Bottom: false})
tw.SetCenterSeparator("|")
tw.AppendBulk(tbl[1:])
tw.Render()
return buffer.String()
}
// Perform a GraphQL query against the GitHub API v4.
func queryGitHub(token string, query string) (body []byte, err error) {
url := "https://api.github.com/graphql"
wrapper := map[string]string{}
wrapper["query"] = query
jsonReq, err := json.Marshal(wrapper)
if err != nil {
return nil, err
}
jsonReqBuf := bytes.NewBuffer([]byte(jsonReq))
req, err := http.NewRequest("POST", url, jsonReqBuf)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("bearer %s", token))
req.Header.Set("Content-Type", "application/graphql")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
// Build a GraphQL query to fetch the GitHub repository statistics for several
// repositories at once.
func buildStatsQuery(repos []repo) (query string, err error) {
repoQuery := `r%d: repository(owner: "%s", name: "%s") { ...ProjStats }`
projStatsFragment := `
fragment ProjStats on Repository {
name
defaultBranchRef {
target {
... on Commit {
authoredDate
history {
totalCount
}
}
}
}
stargazers {
totalCount
}
}
`
queryBuf := bytes.NewBufferString("{\n")
safe, err := regexp.Compile("^[a-zA-Z0-9_-]+$")
if err != nil {
return "", err
}
for i, r := range repos {
// We do not make a fuss about empty repository entries. We
// simply skip them here and return an empty string for them at
// the end.
if r.Name != "" {
if !(safe.MatchString(r.Owner) &&
safe.MatchString(r.Name)) {
return "", fmt.Errorf("Bad repo data: %v", r)
}
t := fmt.Sprintf(repoQuery, i, r.Owner, r.Name)
queryBuf.WriteString(t)
queryBuf.WriteString("\n")
}
}
queryBuf.WriteString("}\n")
queryBuf.WriteString(projStatsFragment)
return queryBuf.String(), nil
}
// Fetch the repository statistics (the number of stars and commits) for the
// repositories in repos and return them formatted as HTML.
func fetchGitHubStats(token string, repos []repo) (statsHTML []string,
err error) {
query, err := buildStatsQuery(repos)
if err != nil {
return nil, err
}
respBody, err := queryGitHub(token, query)
if err != nil {
return nil, err
}
var respData gitHubResponse
err = json.Unmarshal(respBody, &respData)
if err != nil {
return nil, err
}
if respData.Message != "" {
return nil, fmt.Errorf("GitHub API: %s", respData.Message)
}
if len(respData.Errors) > 0 {
return nil, fmt.Errorf("GitHub API: %s",
respData.Errors[0]["message"].(string))
}
statsHTML = make([]string, len(repos))
for k, v := range respData.Data {
i, err := strconv.Atoi(k[1:])
if err != nil {
return nil, err
}
latestCommitDate := v.DefaultBranchRef.Target.AuthoredDate.
Format("2006-01-02")
statsHTML[i] = fmt.Sprintf(
"%d ★; %d commits, latest %s",
v.Stargazers.TotalCount,
v.DefaultBranchRef.Target.History.TotalCount,
latestCommitDate)
}
return statsHTML, nil
}
func main() {
tmpl, err := template.ParseFiles("README.md.template")
if err != nil {
log.Fatal(err)
}
entries, err := loadEntries("data/*.yml")
if err != nil {
log.Fatal(err)
}
re, err := regexp.Compile(
"https?://github.com/([a-zA-Z0-9-]+)/([a-zA-Z0-9_-]+)/?")
if err != nil {
log.Fatal(err)
}
repos := make([]repo, len(entries))
for i, ent := range entries {
found := re.FindStringSubmatch(ent.URL)
if len(found) == 3 {
repos[i].Owner = found[1]
repos[i].Name = found[2]
} else {
entries[i].Stats = "n/a"
}
}
statsHTML, err := fetchGitHubStats(os.Getenv("GITHUB_TOKEN"), repos)
if err != nil {
log.Fatal(err)
}
for i, s := range statsHTML {
if s != "" {
entries[i].Stats = s
}
}
tbl := entriesToTable(entries)
dot := map[string]interface{}{}
dot["date"] = time.Now().Format("2006-01-02")
dot["table"] = tbl.Format()
tmpl.Execute(os.Stdout, dot)
}