-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
192 lines (153 loc) · 4.23 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
package main
import (
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
"time"
"github.com/patrickmn/go-cache"
)
// A cache to avoid repeated API calls to github
var myCache *cache.Cache
func logfileCreate() {
logFile, err := os.OpenFile("logfile.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
log.SetOutput(logFile)
// t := time.Now()
// currentTime = t.Format("2020-01-02 15:04:05")
log.Println("Log created/open")
}
func cacheInit() {
// Load serialized cache from file if exists
b, err := ioutil.ReadFile("cachePersistent.dat")
if err != nil {
// panic(err)
myCache = cache.New(5*time.Minute, 10*time.Minute)
}
// Deserialize
decodedMap := make(map[string]cache.Item, 500)
d := gob.NewDecoder(bytes.NewBuffer(b))
err = d.Decode(&decodedMap)
if err != nil {
panic(err)
}
myCache = cache.NewFrom(5*time.Minute, 10*time.Minute, decodedMap)
}
func getAPIGitHubJSON(path string) string {
// Get API result from cache if available
b, found := myCache.Get(path)
if found {
bodyString := b.(string)
log.Println("cached", path, bodyString)
return bodyString
}
// To avoid API quota limit
githubDelay := 720 * time.Millisecond // 5000 QPH = 83.3 QPM = 1.38 QPS = 720ms/query
time.Sleep(githubDelay)
req, err := http.NewRequest("GET", "https://api.github.com"+path, nil)
if err != nil {
log.Fatalln(err)
}
req.Header.Set("Accept", "application/vnd.github.mercy-preview+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
log.Println("fromAPI", path, string(body))
myCache.Set(path, string(body), cache.NoExpiration) // Store API result in cache
return (string(body))
}
func getTopicsFromRepository(repo string) []string {
// Querying the API
jsonResult := getAPIGitHubJSON("/repos/" + repo + "/topics")
// Content structure
var result map[string][]string
// Unmarshal or Decode the JSON to the map
err := json.Unmarshal([]byte(jsonResult), &result)
if err != nil {
log.Fatalln(err)
}
return result["names"]
}
func getReposWithTopic(topic string) map[string]interface{} {
// Querying the API
jsonResult := getAPIGitHubJSON("/search/repositories?q=topic:" + topic + "&sort=stars&order=desc")
// Result structure
var result map[string]interface{}
// Unmarshal or Decode the JSON to the interface
err := json.Unmarshal([]byte(jsonResult), &result)
if err != nil {
log.Fatalln(err)
}
return result
}
// freqSort is used to sort a map indexed w/ strings by its integer value in descending order
// kv is the struct of (key, value) to output of the sort function
type kv struct {
Key string
Value int
}
func freqSort(values map[string]int) []kv {
var ss []kv
for k, v := range values {
ss = append(ss, kv{k, v})
}
sort.Slice(ss, func(i, j int) bool {
return ss[i].Value > ss[j].Value
})
return ss
}
func main() {
logfileCreate()
cacheInit()
reposFound := getReposWithTopic("traefik")
fmt.Printf("Repositories found: %v\n\n", reposFound["total_count"])
items := reposFound["items"].([]interface{})
// Create map to store topic frequencies
topicFreq := make(map[string]int)
for key, result := range items[:] {
item := result.(map[string]interface{})
// fullName := result["full_name"].(string)
// fmt.Println("Reading Value for Key :", key)
// Reading each value by its key
fmt.Println(key, " ", item["id"],
" || ", item["full_name"],
" || ", item["stargazers_count"],
" || ", item["description"])
topics := getTopicsFromRepository(item["full_name"].(string))
// Loop for every topic in the array
for _, topic := range topics {
// Increase topicFreq counter
topicFreq[topic]++
}
}
topicBest := freqSort(topicFreq)[:10]
fmt.Printf("\nRESULT: %v\n", topicBest)
// fmt.Printf("DEBUG: %v\n", myCache.Items())
// Store cache into persistent file
// Serialize cache
b := new(bytes.Buffer)
e := gob.NewEncoder(b)
// Encoding the map
err := e.Encode(myCache.Items())
if err != nil {
panic(err)
}
// Save serialized cache into file
err = ioutil.WriteFile("cachePersistent.dat", b.Bytes(), 0644)
if err != nil {
panic(err)
}
}