-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
295 lines (246 loc) · 6.7 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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"sort"
"time"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
type Repository struct {
Name string `json:"name"`
TotalTime int64 `json:"totalTime"`
AvgTime int64 `json:"avgTime"`
Jobs []Job `json:"jobs"`
}
type Job struct {
Name string `json:"name"`
TotalTime int64 `json:"totalTime"`
AvgTime int64 `json:"avgTime"`
RunCount int `json:"runCount"`
}
type WorkflowRun struct {
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Name string `json:"name"`
}
type WorkflowRuns struct {
TotalCount int `json:"total_count"`
WorkflowRuns []WorkflowRun `json:"workflow_runs"`
}
func main() {
var rootCmd = &cobra.Command{
Use: "ghatime",
Short: "ghatime is a tool to analyze GitHub Actions execution time in an organization",
Run: analyzeExecutionTime,
}
rootCmd.Flags().StringP("org", "o", "", "organization name (required)")
rootCmd.Flags().String("from", "", "start date (YYYY-MM-DD format)")
rootCmd.Flags().String("to", "", "end date (YYYY-MM-DD format)")
rootCmd.MarkFlagRequired("org")
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func analyzeExecutionTime(cmd *cobra.Command, args []string) {
org, _ := cmd.Flags().GetString("org")
from, _ := cmd.Flags().GetString("from")
to, _ := cmd.Flags().GetString("to")
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
fmt.Fprintln(os.Stderr, "no GitHub token provided")
os.Exit(1)
}
dateRange, err := parseDateRange(from, to)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
repos, err := getRepositories(org, token)
if err != nil {
fmt.Fprintln(os.Stderr, "failed to fetch repositories:", err)
os.Exit(1)
}
eg, ctx := errgroup.WithContext(context.Background())
orgReposChan := make(chan Repository)
for _, repo := range repos {
repo := repo
eg.Go(func() error {
runs, err := getWorkflowRuns(ctx, org, repo.Name, token, dateRange)
if err != nil {
return err
}
var totalTime, totalCount int64
jobs := make(map[string]*Job)
for _, run := range runs {
startTime, _ := time.Parse(time.RFC3339, run.CreatedAt)
endTime, _ := time.Parse(time.RFC3339, run.UpdatedAt)
duration := int64(endTime.Sub(startTime).Seconds())
totalTime += duration
totalCount++
if job, exists := jobs[run.Name]; exists {
job.TotalTime += duration
job.RunCount++
} else {
jobs[run.Name] = &Job{
Name: run.Name,
TotalTime: duration,
RunCount: 1,
}
}
}
for _, job := range jobs {
if job.RunCount > 0 {
job.AvgTime = job.TotalTime / int64(job.RunCount)
}
}
if totalCount > 0 {
repo.TotalTime = totalTime
repo.AvgTime = totalTime / totalCount
repo.Jobs = convertMapToSlice(jobs)
orgReposChan <- repo
}
return nil
})
}
go func() {
err := eg.Wait()
close(orgReposChan)
if err != nil {
fmt.Fprintln(os.Stderr, "error occurred during fetching workflow runs:", err)
}
}()
var orgRepos []Repository
for repo := range orgReposChan {
orgRepos = append(orgRepos, repo)
}
sort.Slice(orgRepos, func(i, j int) bool {
return orgRepos[i].TotalTime > orgRepos[j].TotalTime
})
output := struct {
Org string `json:"org"`
Repos []Repository `json:"repos"`
}{
Org: org,
Repos: orgRepos,
}
data, _ := json.MarshalIndent(output, "", " ")
fmt.Println(string(data))
}
func getRepositories(org, token string) ([]Repository, error) {
var allRepos []Repository
page := 1
for {
repos, err := fetchRepositoriesPage(org, token, page)
if err != nil {
return nil, err
}
if len(repos) == 0 {
break
}
allRepos = append(allRepos, repos...)
page++
}
return allRepos, nil
}
func fetchRepositoriesPage(org, token string, page int) ([]Repository, error) {
url := fmt.Sprintf("https://api.github.com/orgs/%s/repos?per_page=100&page=%d", org, page)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "token "+token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var repos []Repository
if err := json.NewDecoder(resp.Body).Decode(&repos); err != nil {
return nil, err
}
return repos, nil
}
func getWorkflowRuns(ctx context.Context, org, repo, token string, dateRage string) ([]WorkflowRun, error) {
var allRuns []WorkflowRun
page := 1
for {
runs, err := fetchWorkflowRunsPage(ctx, org, repo, token, dateRage, page)
if err != nil {
return nil, err
}
fmt.Println("Found", len(runs), "workflow runs")
if len(runs) == 0 {
break
}
allRuns = append(allRuns, runs...)
page++
}
return allRuns, nil
}
func fetchWorkflowRunsPage(ctx context.Context, org, repo, token, dateRange string, page int) ([]WorkflowRun, error) {
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/actions/runs", org, repo)
query := fmt.Sprintf("status=completed&per_page=100&page=%d&created=%s", page, dateRange)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
req.URL.RawQuery = query
req.Header.Set("Authorization", "token "+token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var runs WorkflowRuns
if err := json.NewDecoder(resp.Body).Decode(&runs); err != nil {
return nil, err
}
return runs.WorkflowRuns, nil
}
func convertMapToSlice(jobsMap map[string]*Job) []Job {
jobs := make([]Job, 0, len(jobsMap))
for _, job := range jobsMap {
jobs = append(jobs, *job)
}
return jobs
}
func parseDateRange(fromStr, toStr string) (dateRange string, err error) {
const layout = "2006-01-02"
if fromStr == "" && toStr == "" {
// If both dates are empty, set default range to the last week
fromStr = time.Now().AddDate(0, 0, -7).Format(layout)
toStr = time.Now().Format(layout)
} else {
// Validate individual dates if provided
if fromStr != "" {
_, err := time.Parse(layout, fromStr)
if err != nil {
return "", fmt.Errorf("invalid start date format: please use YYYY-MM-DD")
}
} else {
fromStr = time.Now().AddDate(0, 0, -7).Format(layout) // Default to one week ago
}
if toStr != "" {
_, err := time.Parse(layout, toStr)
if err != nil {
return "", fmt.Errorf("invalid end date format: please use YYYY-MM-DD")
}
} else {
toStr = time.Now().Format(layout) // Default to current date
}
}
// Check if the date range is valid
from, _ := time.Parse(layout, fromStr)
to, _ := time.Parse(layout, toStr)
if from.After(to) {
return "", fmt.Errorf("the start date must be before the end date")
}
return fromStr + ".." + toStr, nil
}