-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statistics.go
83 lines (67 loc) · 1.92 KB
/
statistics.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
package main
import (
"encoding/json"
"net/http"
"strconv"
"sync"
"fmt"
"time"
"os"
)
type statistics struct {
Assets []struct {
Name string `json:"name"`
DownloadCount uint64 `json:"download_count"`
Date time.Time `json:"updated_at"`
} `json:"assets"`
}
func fetchStatistics(repos []repository) {
wg := &sync.WaitGroup{}
wg.Add(len(repos))
const reposApiEndpoint = "https://api.github.com/repos/"
for _, repo := range repos {
go fetchStatisticsForRepo(reposApiEndpoint+repo.Name+"/releases", repo.Name, wg)
}
wg.Wait()
}
func fetchStatisticsForRepo(repourl, reponame string, wg *sync.WaitGroup) {
defer wg.Done()
resp, err := http.Get(repourl)
if err != nil {
os.Stderr.WriteString("Error: The HTTP get request failed. Error message: ")
os.Stderr.WriteString(err.Error())
os.Stderr.WriteString("\n")
os.Exit(1)
}
defer resp.Body.Close()
stats := []statistics{}
totalDownloads := uint64(0)
err = json.NewDecoder(resp.Body).Decode(&stats)
if err != nil {
os.Stderr.WriteString("Error: Failed to decode JSON data. A likely culprit is that the GitHub API limit was likely reached.\nTry again in a few hours. Error message: ")
os.Stderr.WriteString(err.Error())
os.Stderr.WriteString("\n")
os.Exit(1)
}
buffer := make([]byte, 0, 4096)
for _, stat := range stats {
if stat.Assets == nil || len(stat.Assets) == 0 {
continue
}
for _, asset := range stat.Assets {
totalDownloads += asset.DownloadCount
buffer = fmt.Appendf(buffer, "Repo: %-20v Asset: %-40v Count: %-5v",
reponame,
asset.Name,
strconv.FormatUint(asset.DownloadCount, 10),
)
buffer = asset.Date.AppendFormat(buffer, time.RFC850)
buffer = append(buffer, '\n')
}
buffer = append(buffer, '\n')
}
buffer = fmt.Appendf(buffer, "Total downloads for %s: ", reponame)
buffer = strconv.AppendUint(buffer, totalDownloads, 10)
buffer = append(buffer, '\n')
os.Stdout.Write(buffer)
}