-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
550 lines (454 loc) · 13.3 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"os"
"strconv"
"strings"
"text/template"
"time"
"golang.org/x/term"
"github.com/charmbracelet/lipgloss"
"github.com/cli/go-gh"
flag "github.com/spf13/pflag"
"github.com/vilmibm/actions-dashboard/util"
)
const defaultMaxRuns = 5
const defaultWorkflowNameLength = 17
const defaultApiCacheTime = "60m"
type run struct {
Finished time.Time
Elapsed time.Duration
Status string
Conclusion string
URL string
}
type workflow struct {
Name string
Runs []run
BillableMs int
}
func (w *workflow) RenderHealth() string {
successStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#32cd32"))
neutralStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#808080"))
failedStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#dc143c"))
var results string
health := workflowHealth(*w)
for _, r := range health {
switch r {
case '✓':
results += successStyle.Render("✓")
case '-':
results += neutralStyle.Render("-")
default:
results += failedStyle.Render("x")
}
}
return results
}
func (w *workflow) AverageElapsed() time.Duration {
var totalTime int
var averageTime int
for i, r := range w.Runs {
if i > defaultMaxRuns {
break
}
totalTime += int(r.Elapsed.Seconds())
}
averageTime = totalTime / defaultMaxRuns
s := fmt.Sprintf("%ds", averageTime)
d, _ := time.ParseDuration(s)
return d
}
func truncateWorkflowName(name string, length int) string {
if len(name) > length {
return name[:length] + "..."
}
return name
}
func getTerminalWidth() int {
if !term.IsTerminal(int(os.Stdout.Fd())) {
return 80
}
width, _, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
panic(err.Error())
}
return width
}
func (w *workflow) RenderCard() string {
workflowNameStyle := lipgloss.NewStyle().Bold(true)
labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#808080"))
var tmpl *template.Template
tmplData := struct {
Name string
AvgElapsed time.Duration
Health string
BillableMs int
PrettyMS func(int) string
Label func(string) string
}{
Name: workflowNameStyle.Render(truncateWorkflowName(w.Name, defaultWorkflowNameLength)),
AvgElapsed: w.AverageElapsed(),
Health: w.RenderHealth(),
BillableMs: w.BillableMs,
PrettyMS: util.PrettyMS,
Label: func(s string) string {
return labelStyle.Render(s)
},
}
// Assumes that run data is time filtered already
// TODO add color etc in here:
if len(w.Runs) == 0 {
tmpl, _ = template.New("emptyWorkflowCard").Parse(
`{{ .Name }}
{{call .Label "No runs"}}`)
} else {
tmpl, _ = template.New("workflowCard").Parse(
`{{ .Name }}
{{call .Label "Health:"}} {{ .Health }}
{{call .Label "Avg elapsed:"}} {{ .AvgElapsed }}
{{- if .BillableMs }}
{{call .Label "Billable time:"}} {{call .PrettyMS .BillableMs }}{{end}}`)
}
buf := bytes.Buffer{}
_ = tmpl.Execute(&buf, tmplData)
return buf.String()
}
type repositoryData struct {
HtmlUrl string `json:"html_url"`
Name string `json:"full_name"`
Private bool
Workflows []*workflow
}
type options struct {
Repositories []string
Last time.Duration
Selector string
Status string
}
func workflowHealth(w workflow) string {
health := ""
for i, r := range w.Runs {
if i > defaultMaxRuns {
break
}
if r.Status != "completed" {
health += "-"
continue
}
switch r.Conclusion {
case "success":
health += "✓"
case "skipped", "cancelled", "neutral":
health += "-"
default:
health += "x"
}
}
return health
}
func noTerminalRender(repos []*repositoryData) error {
for _, r := range repos {
if len(r.Workflows) == 0 {
continue
}
fmt.Println()
fmt.Println(r.Name)
fmt.Printf("%s/actions\n", r.HtmlUrl)
fmt.Println()
for _, w := range r.Workflows {
fmt.Println()
fmt.Printf("%s:\n", w.Name)
if len(w.Runs) == 0 {
fmt.Printf(" No runs\n")
} else {
health := workflowHealth(*w)
fmt.Printf(" %-15s %v\n", "Health: ", health)
fmt.Printf(" %-15s %v\n", "Avg elapsed: ", w.AverageElapsed())
fmt.Printf(" %-15s %v\n", "Billable time: ", util.PrettyMS(w.BillableMs))
}
}
fmt.Println()
}
return nil
}
func terminalRender(repos []*repositoryData) error {
columnWidth := defaultWorkflowNameLength + 5 // account for ellipsis and padding/border
cardsPerRow := (getTerminalWidth() / columnWidth) - 1
cardStyle := lipgloss.NewStyle().
Align(lipgloss.Left).
Padding(1).
Width(columnWidth).
BorderStyle(lipgloss.DoubleBorder()).
BorderForeground(lipgloss.Color("63"))
repoNameStyle := lipgloss.NewStyle().Bold(true)
repoHintStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#808080")).Italic(true)
for _, r := range repos {
if len(r.Workflows) == 0 {
continue
}
fmt.Println()
fmt.Print(repoNameStyle.Render(r.Name))
fmt.Print(repoHintStyle.Render(fmt.Sprintf(" %s/actions\n", r.HtmlUrl)))
fmt.Println()
totalRows := int(math.Ceil(float64(len(r.Workflows)) / float64(cardsPerRow)))
cardRows := make([][]string, totalRows)
rowIndex := 0
for _, w := range r.Workflows {
if len(cardRows[rowIndex]) == cardsPerRow {
rowIndex++
}
cardRows[rowIndex] = append(cardRows[rowIndex], cardStyle.Render(w.RenderCard()))
}
for _, row := range cardRows {
fmt.Println(lipgloss.JoinHorizontal(lipgloss.Top, row...))
}
}
return nil
}
func _main(opts *options) error {
selector := opts.Selector
last := opts.Last
repos, err := populateRepos(opts)
if err != nil {
return fmt.Errorf("could not fetch repository data: %w", err)
}
totalBillableMs := 0
for _, r := range repos {
workflows, err := getWorkflows(*r, last, opts)
if err != nil {
return err
}
r.Workflows = workflows
for _, w := range workflows {
totalBillableMs += w.BillableMs
}
}
if term.IsTerminal(int(os.Stdout.Fd())) {
titleStyle := lipgloss.NewStyle().Bold(true).Align(lipgloss.Center).Width(getTerminalWidth())
subTitleStyle := lipgloss.NewStyle().Align(lipgloss.Center).Width(getTerminalWidth())
fmt.Println(titleStyle.Render(fmt.Sprintf("GitHub Actions dashboard for %s for the past %s", selector, util.FuzzyAgo(opts.Last))))
fmt.Println(subTitleStyle.Render(fmt.Sprintf("Total billable time: %s", util.PrettyMS(totalBillableMs))))
terminalRender(repos)
} else {
fmt.Printf("GitHub Actions dashboard for %s for the past %s\n", selector, util.FuzzyAgo(opts.Last))
fmt.Printf("Total billable time: %s\n", util.PrettyMS(totalBillableMs))
noTerminalRender(repos)
}
return nil
}
func populateRepos(opts *options) ([]*repositoryData, error) {
result := []*repositoryData{}
if len(opts.Repositories) > 0 {
for _, repoName := range opts.Repositories {
repoData, err := getRepo(opts.Selector, repoName)
if err != nil {
return nil, fmt.Errorf("failed to fetch data for %s/%s: %w", opts.Selector, repoName, err)
}
result = append(result, repoData)
}
return result, nil
}
var orgErr error
var userErr error
result, orgErr = getAllRepos(fmt.Sprintf("orgs/%s/repos", opts.Selector))
if orgErr != nil {
result, userErr = getAllRepos(fmt.Sprintf("users/%s/repos", opts.Selector))
if userErr != nil {
return nil, fmt.Errorf("could not find a user or org called '%s': %s; %s", opts.Selector, orgErr, userErr)
}
}
return result, nil
}
func getRepo(owner, name string) (*repositoryData, error) {
path := fmt.Sprintf("repos/%s/%s", owner, name)
var stdout bytes.Buffer
var data repositoryData
var err error
if stdout, _, err = gh.Exec("api", "--cache", defaultApiCacheTime, path); err != nil {
return nil, err
}
if err := json.Unmarshal(stdout.Bytes(), &data); err != nil {
return nil, err
}
return &data, nil
}
func getAllRepos(path string) ([]*repositoryData, error) {
stdout, _, err := gh.Exec("api", "--cache", defaultApiCacheTime, path)
if err != nil {
return nil, err
}
repoData := []*repositoryData{}
err = json.Unmarshal(stdout.Bytes(), &repoData)
if err != nil {
return nil, err
}
return repoData, nil
}
func getWorkflows(repoData repositoryData, last time.Duration, opts *options) ([]*workflow, error) {
workflowsPath := fmt.Sprintf("repos/%s/actions/workflows", repoData.Name)
stdout, _, err := gh.Exec("api", "--cache", defaultApiCacheTime, workflowsPath, "--jq", ".workflows")
if err != nil {
return nil, err
}
type workflowsPayload struct {
Id int `json:"id"`
State string
Name string
URL string `json:"url"`
}
p := []workflowsPayload{}
err = json.Unmarshal(stdout.Bytes(), &p)
if err != nil {
return nil, err
}
out := []*workflow{}
type runPayload struct {
Id int `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Status string
Conclusion string
URL string
}
type billablePayload struct {
MacOs struct {
TotalMs int `json:"total_ms"`
} `json:"MACOS"`
Windows struct {
TotalMs int `json:"total_ms"`
} `json:"WINDOWS"`
Ubuntu struct {
TotalMs int `json:"total_ms"`
} `json:"UBUNTU"`
}
var totalMs int
for _, w := range p {
if strings.HasPrefix(w.State, "disabled") {
continue
}
var runsPath string
if opts.Status != "" {
runsPath = fmt.Sprintf("%s/runs?status=%s", w.URL, opts.Status)
} else {
runsPath = fmt.Sprintf("%s/runs", w.URL)
}
stdout, _, err = gh.Exec("api", "--cache", defaultApiCacheTime, runsPath, "--jq", ".workflow_runs")
if err != nil {
return nil, fmt.Errorf("could not call gh: %w", err)
}
rs := []runPayload{}
err = json.Unmarshal(stdout.Bytes(), &rs)
if err != nil {
return nil, fmt.Errorf("could not parse json: %w", err)
}
runs := []run{}
for _, r := range rs {
rr := run{Status: r.Status, Conclusion: r.Conclusion, URL: r.URL}
if r.Status == "completed" {
rr.Finished = r.UpdatedAt
rr.Elapsed = r.UpdatedAt.Sub(r.CreatedAt)
finishedAgo := time.Since(rr.Finished)
if last-finishedAgo > 0 {
runs = append(runs, rr)
}
}
}
if repoData.Private && strings.Index(repoData.HtmlUrl, "https://github.com") == 0 {
for _, r := range runs {
runTimingPath := fmt.Sprintf("%s/timing", r.URL)
stdout, _, err = gh.Exec("api", "--cache", defaultApiCacheTime, runTimingPath, "--jq", ".billable")
if err != nil {
return nil, fmt.Errorf("could not call gh: %w", err)
}
bp := billablePayload{}
err = json.Unmarshal(stdout.Bytes(), &bp)
if err != nil {
return nil, fmt.Errorf("could not parse json: %w", err)
}
totalMs += bp.MacOs.TotalMs + bp.Windows.TotalMs + bp.Ubuntu.TotalMs
}
}
out = append(out, &workflow{
Name: w.Name,
Runs: runs,
BillableMs: totalMs,
})
}
return out, nil
}
func parseArgs() (*options, error) {
var selector string
repositories := flag.StringSliceP("repos", "r", []string{}, "One or more repository names from the provided org or user")
last := flag.StringP("last", "l", "30d", "What period of time to cover in hours (eg 1h) or days (eg 30d). Default: 30d")
runStatus := flag.StringP("status", "s", "", "What workflow run status (eg completed, cancelled, failure, success) to query for")
flag.Parse()
// Try to determine user or org name form single argument
if len(flag.Args()) == 1 {
// Single argument to use as org/user name
selector = flag.Arg(0)
} else if len(flag.Args()) != 0 {
// Too many arguments, don't try to infer anything, just fail
return nil, errors.New("need exactly one argument, either an organization or user name.")
} else if _, stderr, err := gh.Exec("auth", "status"); err != nil {
// Couldn't infer username, gh auth returned error
return nil, fmt.Errorf("need exactly one argument, either an organization or user name. Could not determine username from auth status: %w", err)
} else if status := stderr.String(); status != "" {
// Successfully got auth status, look through it for something that
// looks like a username.
search := "Logged in to github.com as "
for _, line := range strings.Split(status, "\n") {
if start := strings.Index(line, search); start >= 0 {
tokens := strings.Split(line[start+len(search):], " ")
// Stop looking if username was found
if len(tokens) > 0 {
selector = tokens[0]
break
}
}
}
} else {
// Couldn't infer username
return nil, errors.New("need exactly one argument, either an organization or user name.")
}
lastVal := *last
timeUnit := string(lastVal[len(lastVal)-1])
// Go cannot parse duration "1d" which is stupid; need to convert it to hours before we can get a proper duration.
if timeUnit == "d" {
asNum, err := strconv.Atoi(lastVal[0 : len(lastVal)-1])
if err != nil {
return nil, fmt.Errorf("could not parse number: %w", err)
}
lastVal = fmt.Sprintf("%dh", asNum*24)
}
if timeUnit != "h" && timeUnit != "d" {
return nil, fmt.Errorf("report duration should be in hours or duration (eg 1h or 30d)")
}
duration, err := time.ParseDuration(lastVal)
if err != nil {
return nil, fmt.Errorf("failed to parse duration: %w", err)
}
return &options{
Repositories: *repositories,
Last: duration,
Selector: selector,
Status: *runStatus,
}, nil
}
func main() {
opts, err := parseArgs()
if err != nil {
fmt.Fprintf(os.Stderr, "failed to parse arguments: %s\n", err)
os.Exit(1)
}
// TODO testing is annoying bc of flag.Parse() in _main
err = _main(opts)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
}