-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
323 lines (280 loc) · 8.48 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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package main
import (
"flag"
"fmt"
//"github.com/davecgh/go-spew/spew"
"html/template"
"io"
"log"
"os"
"path/filepath"
"sort"
"strings"
)
const (
// Glob matching challenges directory.
// Common syntax is <anything>-<challenge_name_or_number>/author
challengesGlob = "./desafio-*/*"
// Name of the main template file.
templateFile = "scoreboard.template"
)
// playerChallenge holds one user/challenge pair read from the disk.
type playerChallenge struct {
username string
challenge string
}
// CompletedChallenge holds information about the challenges completed by
// a user.
type CompletedChallenge struct {
Name string
Points int
}
// playerScore holds the total number of points and completed challenges for
// one particular player.
type playerScore struct {
Points int
Completed []CompletedChallenge
}
// scoreboardEntry holds one entry in the scoreboard. It contains all
// information required to emit output for this player.
type scoreboardEntry struct {
Rank int
GithubUser string
Score playerScore
Completed []CompletedChallenge
// Full info from github
GithubInfo GithubUserResponse
// True if this is the first user in a group.
FirstInGroup bool
// True if this user is the last in a group. Typically the last of a number
// of people with the same score.
LastInGroup bool
}
func main() {
// Log file name and line number.
log.SetFlags(log.LstdFlags | log.Lshortfile)
configFile := flag.String("config", "", "configuration file")
token := flag.String("token", "", "Github Personal Access Token (optional)")
tokenvar := flag.String("tokenvar", "", "Environment variable containing the github Personal Access Token (optional)")
githubAccess := flag.Bool("github", true, "Use github for user details (set to false for testing)")
flag.Parse()
r, err := os.Open(*configFile)
if err != nil {
log.Fatal(err)
}
config, err := parseConfig(r)
if err != nil {
log.Fatal(err)
}
log.Printf("Config: %+v\n", config)
// If token not set and we have tokenvar, set it.
if *token == "" {
*token = os.Getenv(*tokenvar)
}
challenges, err := readChallenges(config.ChallengesDir)
if err != nil {
log.Fatal(err)
}
if len(challenges) == 0 {
log.Fatal("No challenges found. Check the value of challenge_dir in the config file.")
}
scores, err := makePlayerScores(challenges, config.IgnoreUsers, config.Points)
if err != nil {
log.Fatal(err)
}
// Log the total scores
for user, score := range scores {
log.Printf("Final score: %s: %+v", user, score)
}
scoreboard, err := createScoreboard(scores, *token, *githubAccess)
if err != nil {
log.Fatal(err)
}
tfile := filepath.Join(config.TemplateDir, templateFile)
if err := writeTemplateFile(filepath.Join(config.WebsiteDir, "/content/scores.md"), scoreboard, tfile); err != nil {
log.Fatal(err)
}
}
// readChallenges reads all relevant directories under ddir and
// return a list containing the users and challenges found.
func readChallenges(ddir string) ([]playerChallenge, error) {
var ret []playerChallenge
dpaths, err := filepath.Glob(filepath.Join(ddir, challengesGlob))
if err != nil {
return nil, err
}
for _, v := range dpaths {
username, challenge, err := parsePath(v)
if err != nil {
return nil, err
}
ret = append(ret, playerChallenge{username: username, challenge: challenge})
log.Printf("Challenge found: username=%s, challenge=%v\n", username, challenge)
}
return ret, nil
}
// makePlayerScores generates a map of playerScores structures from the list of
// player/challenges keyed on github username. Any username on the 'ignore'
// list will be silently ignored. Uses the pointsConfig map to calculate how
// much each challenge is worth in points.
func makePlayerScores(challenges []playerChallenge, ignore []string, pointsConfig map[string]Point) (map[string]playerScore, error) {
scores := map[string]playerScore{}
for _, c := range challenges {
// Make sure user is not ignored.
if inSlice(ignore, c.username) {
log.Printf("Ignored user: %s", c.username)
continue
}
// Compute score for this player/challenge
pts, err := calcScores(c, pointsConfig)
if err != nil {
return nil, err
}
s, ok := scores[c.username]
if !ok {
s = playerScore{}
}
// Add challenge to list of completed for this player
if !alreadyCompleted(s.Completed, c.challenge) {
cc := CompletedChallenge{
Name: c.challenge,
Points: pts,
}
s.Completed = append(s.Completed, cc)
}
// Add total points.
s.Points += pts
scores[c.username] = s
}
return scores, nil
}
// parsePath parses a path under challengesDir and returns the user and
// designation of that particular challenge (or error). This function assumes
// that directories under path are laid out as challenge_name/username
func parsePath(path string) (string, string, error) {
elems := strings.Split(path, "/")
if len(elems) < 2 {
return "", "", fmt.Errorf("invalid file/dir: %q", path)
}
cname := elems[len(elems)-2]
username := elems[len(elems)-1]
return username, cname, nil
}
// calcScores returns the calcScores for a single username
func calcScores(challenge playerChallenge, points map[string]Point) (int, error) {
pointvalue, ok := points[challenge.challenge]
if !ok {
return 0, fmt.Errorf("missing points configuration for: %q", challenge.challenge)
}
return pointvalue.Value, nil
}
// inSlice returns true if a given string is inside a slice of strings.
func inSlice(sl []string, str string) bool {
for _, v := range sl {
if str == v {
return true
}
}
return false
}
// alreadyCompleted returns true if a given challenge is already in a slice of
// completeChallenge structs.
func alreadyCompleted(cc []CompletedChallenge, name string) bool {
for _, v := range cc {
if name == v.Name {
return true
}
}
return false
}
// createScoreboard creates a "scoreboard" slice, ready to be rendered by
// templates. We need a slice here to make it easier to sort by points.
func createScoreboard(scores map[string]playerScore, token string, githubAccess bool) ([]scoreboardEntry, error) {
var (
githubInfo GithubUserResponse
scoreboard []scoreboardEntry
ok bool
err error
)
for u, s := range scores {
// If no github access (E.g. when debugging), generate a fake
// githubInfo structure. This allows the program to be used
// without github quota issues.
githubInfo = GithubUserResponse{
AvatarURL: "http://localhost",
Login: u,
}
if githubAccess {
githubInfo, ok, err = githubUserInfo(u, token)
if err != nil {
return nil, err
}
// No user on github?
if !ok {
continue
}
}
sbe := scoreboardEntry{
GithubUser: u,
Score: s,
Completed: s.Completed,
GithubInfo: githubInfo,
}
scoreboard = append(scoreboard, sbe)
}
// Descending sort by points, ascending sort by username for users
// with the same number of points.
sort.Slice(scoreboard, func(i, j int) bool {
if scoreboard[i].Score.Points == scoreboard[j].Score.Points {
return strings.ToLower(scoreboard[i].GithubUser) < strings.ToLower(scoreboard[j].GithubUser)
}
return scoreboard[i].Score.Points > scoreboard[j].Score.Points
})
// Scan scoreboard and add rank and end of group indicators.
rank := 0
oldpoints := 0
for k := range scoreboard {
points := scoreboard[k].Score.Points
if points != oldpoints {
rank++
scoreboard[k].FirstInGroup = true
if k != 0 {
scoreboard[k-1].LastInGroup = true
}
}
scoreboard[k].Rank = rank
oldpoints = points
}
// Last element is always marked as last in group.
if len(scoreboard) != 0 {
scoreboard[len(scoreboard)-1].LastInGroup = true
}
return scoreboard, nil
}
// writeTemplateFile writes a scoreboard to the default output file using a
// specified template file.
func writeTemplateFile(outfile string, scoreboard []scoreboardEntry, tfile string) error {
w, err := os.Create(outfile)
if err != nil {
return err
}
defer w.Close()
// Debug output
log.Printf("--- new content/scores.md contents ---")
writeTemplate(os.Stderr, scoreboard, tfile)
return writeTemplate(w, scoreboard, tfile)
}
// writeTemplate writes a scoreboard to an io.Writer using a specified template
// file.
func writeTemplate(w io.Writer, scoreboard []scoreboardEntry, tfile string) error {
_, tbasefile := filepath.Split(tfile)
t := template.New(tbasefile)
t, err := t.ParseFiles(tfile)
if err != nil {
return fmt.Errorf("writeTemplate: error parsing template: %v", err)
}
if err = t.Execute(w, scoreboard); err != nil {
return fmt.Errorf("writeTemplate: error executing template: %v", err)
}
return nil
}