-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
222 lines (181 loc) · 5.86 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
package main
import (
"encoding/json"
"fmt"
"github.com/gammazero/workerpool"
"github.com/joho/godotenv"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/gologger/levels"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/push"
"io/ioutil"
"net/http"
"os"
"time"
)
type repoData struct {
key string
org string
repoName string
completionChan chan bool
}
// getRepos returns an array of repository names on codacy
func getRepos(key string, org string) []string {
// struct to receive and breakdown repository list json data
type repoResults struct {
Data []struct {
Repository struct {
Name string `json:"name"`
} `json:"repository"`
}
}
req, err := http.NewRequest("GET", fmt.Sprintf("https://app.codacy.com/api/v3/analysis/organizations/gh/%s/repositories", org), nil)
if err != nil {
gologger.Warning().Str("state", "errored").Str("status", "404").
Msg("Unable to get repo list")
return nil
}
req.Header = map[string][]string{
"Accept": {"application/json"},
"api-token": {key},
} // provides auth to http request
client := &http.Client{Timeout: 10 * time.Second} // http client times out to prevent getting stuck while making request
resp, err := client.Do(req)
if err != nil {
gologger.Warning().Str("state", "errored").Str("status", "404").
Msg("timed out while getting list of repo")
return nil
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
gologger.Warning().Str("state", "errored").Str("status", "404").
Msg("unable to unmarshal body response while getting repos")
return nil
}
res := &repoResults{}
err = json.Unmarshal(body, res) // translates json response body into struct
if err != nil {
gologger.Warning().Str("state", "errored").Str("status", "404").
Msg("unable to unmarshal json issues response while getting repos")
return nil
}
var repoList []string
// makes slice of repository names to return
for _, v := range res.Data {
repoList = append(repoList, v.Repository.Name)
}
return repoList
}
// getIssues returns a map with issues of the respective repo
func (r *repoData) getIssues() map[string]int {
// struct to receive and breakdown repository issue json data
type Results struct {
Data []struct {
Category struct {
Name string `json:"categoryType"`
} `json:"category"`
TotalResults int `json:"totalResults"`
} `json:"data"`
}
req, err := http.NewRequest("GET", fmt.Sprintf("https://app.codacy.com/api/v3/analysis/organizations/gh/%s/repositories/%s/category-overviews", r.org, r.repoName), nil)
if err != nil {
gologger.Warning().Str("state", "errored").Str("status", "404").
Msg(fmt.Sprintf("failed to get issues for repo %s", r.repoName))
r.completionChan <- false
return nil
}
req.Header = map[string][]string{
"Accept": {"application/json"},
"api-token": {r.key},
} // provides auth to http request
client := &http.Client{Timeout: 10 * time.Second} // http client times out to prevent getting stuck while making request
resp, err := client.Do(req)
if err != nil {
gologger.Warning().Str("state", "errored").Str("status", "404").
Msg(fmt.Sprintf("timed out while getting issues for repo %s", r.repoName))
r.completionChan <- false
return nil
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
gologger.Warning().Str("state", "errored").Str("status", "404").
Msg(fmt.Sprintf("unable to unmarshal body response for repo %s", r.repoName))
r.completionChan <- false
return nil
}
res := &Results{}
err = json.Unmarshal(body, res) // translates json response body into struct
if err != nil {
gologger.Warning().Str("state", "errored").Str("status", "404").
Msg(fmt.Sprintf("unable to unmarshal json issues response for repo %s", r.repoName))
r.completionChan <- false
return nil
}
issuesMap := make(map[string]int)
// makes issuesMap to return
for _, v := range res.Data {
issuesMap[v.Category.Name] = v.TotalResults
}
return issuesMap
}
// pushIssues pushes issue data to prometheus pushgateway
func (r *repoData) pushIssues(issuesMap map[string]int) {
// creates a gauge to store issue metrics
codacyIssuesMetric := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "codacy_issues_metric",
Help: "Number of issues in Codacy code",
})
// pushes each metric in issueList
for i := range issuesMap {
codacyIssuesMetric.Set(float64(issuesMap[i]))
if err := push.New("http://localhost:9091", "codacy_issues_metric").
Collector(codacyIssuesMetric).
Grouping("Categories", i).
Grouping("Repository", r.repoName).
Push(); err != nil {
gologger.Warning().Str("state", "errored").Str("status", "404").
Msg(fmt.Sprintf("Could not push %s, %s to Pushgateway:", i, r.repoName))
}
}
r.completionChan <- true
}
// Process implements IJob by combining getIssues and pushIssues
func (r *repoData) Process() error {
issuesMap := r.getIssues()
if issuesMap != nil {
r.pushIssues(issuesMap)
}
return nil
}
func main() {
err := godotenv.Load("local.env")
key := os.Getenv("KEY")
org := os.Getenv("ORG")
if err != nil {
gologger.Fatal().Msg("Failed to retrieve api key")
return
}
gologger.DefaultLogger.SetMaxLevel(levels.LevelDebug)
repoList := getRepos(key, org)
if repoList != nil {
dispatcher := workerpool.New(len(repoList) / 5)
completionChan := make(chan bool, len(repoList)) // Chan used to block till all jobs are complete
go func() {
for _, repoName := range repoList { // creates job for each repository in repoList
job := &repoData{key: key, org: org, repoName: repoName, completionChan: completionChan}
dispatcher.Submit(func() {
issues := job.getIssues()
job.pushIssues(issues)
})
}
}()
for {
if len(completionChan) == cap(completionChan) {
gologger.Print().Msgf("Completed All Repos\n")
return
}
}
}
}