-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
182 lines (159 loc) · 4.79 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
package main
import (
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"sort"
"strings"
"time"
"github.com/caarlos0/env"
)
type config struct {
GithubToken string `env:"GHTOKEN"`
Authors string `env:"AUTHORS"`
RequiredPRCount int `env:"REQUIRED_PR_COUNT"`
RefreshInterval int `env:"REFRESH_INTERVAL" envDefault:"1800"`
Bozzes string `env:"BOZZES"`
Timezone string `env:"TIMEZONE" envDefault:"UTC"`
}
type AuthorData struct {
AuthorClass string
Author string
PrCount int
PrCountClass string
AvatarURL string
}
type LeaderboardData struct {
AuthorData []AuthorData
RefreshInterval int
Year int
UpdatedTime string
}
type avatarResult struct {
AvatarURL string `json:"avatar_url"`
Name string `json:"name"`
}
type prCountResult struct {
PrCount int `json:"total_count"`
}
func leaderboard(writer http.ResponseWriter, request *http.Request) {
t := template.Must(template.ParseFiles("leaderboard.html"))
authorData := getAuthorData()
location, err := time.LoadLocation(cfg.Timezone)
if err != nil {
location, _ = time.LoadLocation("UTC")
}
leaderboardData := LeaderboardData{
AuthorData: authorData,
RefreshInterval: cfg.RefreshInterval,
Year: calcYear(),
UpdatedTime: time.Now().In(location).Format("2 Jan 2006 3:04 PM MST"),
}
t.Execute(writer, leaderboardData)
}
func leaderboardJSON(writer http.ResponseWriter, request *http.Request) {
jsonString, _ := json.Marshal(getAuthorData())
fmt.Fprintf(writer, "%s", jsonString)
}
// return slice of AuthorData structs ordered by PR count descending
func getAuthorData() []AuthorData {
authors := strings.Split(cfg.Authors, ":")
authorData := make([]AuthorData, len(authors))
fmt.Printf("Authors: %v\n", authors)
bozzes := strings.Split(cfg.Bozzes, ":")
for i, author := range authors {
avatarData := getAvatar(author)
var authorClass string
for _, b := range bozzes {
if author == b {
authorClass = "bozz"
}
}
// Use github login name if the `Name` field from the GitHub API is empty.
authorName := avatarData.Name
if len(authorName) == 0 {
authorName = author
}
var prCountClass string
var prCount = getPrCount(author)
if prCount >= cfg.RequiredPRCount {
prCountClass = "met-pr-count"
}
currentAuthor := AuthorData{AuthorClass: authorClass, Author: authorName, PrCount: prCount, PrCountClass: prCountClass, AvatarURL: avatarData.AvatarURL}
authorData[i] = currentAuthor
fmt.Printf("Author: %s, PR count: %d\n", currentAuthor.Author, currentAuthor.PrCount)
}
sort.Slice(authorData, func(i, j int) bool {
// If PR counts are tied, sort by name ascending
if authorData[i].PrCount == authorData[j].PrCount {
return authorData[i].Author < authorData[j].Author
}
// else sort by PR count descending
return authorData[i].PrCount > authorData[j].PrCount
})
return authorData
}
func getAvatar(author string) avatarResult {
response, err := makeAuthorizedRequest("https://api.github.com/users/%s", author)
if response != nil {
defer response.Body.Close()
}
if err != nil {
fmt.Println("Failed to fetch avatar. %s\n", err)
return avatarResult{}
} else {
ghData, _ := ioutil.ReadAll(response.Body)
result := avatarResult{}
json.Unmarshal([]byte(ghData), &result)
return result
}
}
func getPrCount(author string) (prCount int) {
year := calcYear()
response, err := makeAuthorizedRequest("https://api.github.com/search/issues?q=created:%d-09-30T00:00:00-12:00..%d-10-31T23:59:59-12:00+type:pr+is:public+author:%s", year, year, author)
if response != nil {
defer response.Body.Close()
}
if err != nil {
fmt.Println("Failed to fetch PR count. %s\n", err)
return -1
} else {
ghData, _ := ioutil.ReadAll(response.Body)
result := prCountResult{}
json.Unmarshal([]byte(ghData), &result)
return result.PrCount
}
}
func makeAuthorizedRequest(urlFormat string, arguments ...interface{}) (*http.Response, error) {
url := fmt.Sprintf(urlFormat, arguments...)
client := &http.Client{}
request, _ := http.NewRequest("GET", url, nil)
if cfg.GithubToken != "" {
request.Header.Set("Authorization", "token "+cfg.GithubToken)
}
return client.Do(request)
}
func calcYear() int {
currentTime := time.Now()
dateTimeString := fmt.Sprintf("30 Sep %d 0:00 -1200", currentTime.Year()-2000)
hacktoberfestStart, _ := time.Parse(time.RFC822Z, dateTimeString)
if currentTime.Before(hacktoberfestStart) {
return currentTime.Year() - 1
} else {
return currentTime.Year()
}
}
// global config
var cfg = config{}
func main() {
if err := env.Parse(&cfg); err != nil {
fmt.Printf("%+v\n", err)
}
fs := http.FileServer(http.Dir("assets"))
http.Handle("/", fs)
http.HandleFunc("/leaderboard.json", leaderboardJSON)
http.HandleFunc("/leaderboard", leaderboard)
http.ListenAndServe(":4000", nil)
}