forked from code-golf/code-golf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.go
More file actions
121 lines (103 loc) · 2.15 KB
/
github.go
File metadata and controls
121 lines (103 loc) · 2.15 KB
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
package github
import (
"context"
"database/sql"
"log"
"os"
"time"
"github.com/shurcooL/graphql"
"golang.org/x/oauth2"
)
var accessToken = os.Getenv("GITHUB_ACCESS_TOKEN")
var client = graphql.NewClient(
"https://api.github.com/graphql",
oauth2.NewClient(
context.Background(),
oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken}),
),
)
type pageInfo struct {
EndCursor graphql.String
HasNextPage bool
}
type rateLimit struct {
Cost, Limit, Remaining int
ResetAt time.Time
}
func Run(db *sql.DB, hourly bool) {
if accessToken == "" {
return
}
var (
cost int
limit rateLimit
)
var jobs []func(*sql.DB) []rateLimit
if hourly {
jobs = append(jobs, updateUsernames)
} else {
jobs = append(jobs, ideas, pullRequests, sponsors, stars)
}
for _, job := range jobs {
for _, limit = range job(db) {
cost += limit.Cost
}
}
log.Printf(
"GitHub API: Spent %d, %d/%d left, resets in %v",
cost, limit.Remaining, limit.Limit, time.Until(limit.ResetAt).Round(time.Second),
)
}
func awardCheevos(db *sql.DB, earnedUsers map[int]time.Time, cheevoID string) {
rows, err := db.Query(
"SELECT earned, user_id FROM trophies WHERE trophy = $1",
cheevoID,
)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var earned time.Time
var userID int
if err := rows.Scan(&earned, &userID); err != nil {
panic(err)
}
if newEarned, ok := earnedUsers[userID]; ok {
delete(earnedUsers, userID)
if earned != newEarned {
if _, err := db.Exec(
`UPDATE trophies
SET earned = $1
WHERE trophy = $2
AND user_id = $3`,
newEarned,
cheevoID,
userID,
); err != nil {
panic(err)
}
}
} else if _, err := db.Exec(
"DELETE FROM trophies WHERE trophy = $1 AND user_id = $2",
cheevoID,
userID,
); err != nil {
panic(err)
}
}
if err := rows.Err(); err != nil {
panic(err)
}
for userID, earned := range earnedUsers {
if _, err := db.Exec(
`INSERT INTO trophies SELECT $1, $2, $3
WHERE EXISTS (SELECT * FROM users WHERE id = $2)`,
earned,
userID,
cheevoID,
); err != nil {
panic(err)
}
}
}