-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
361 lines (298 loc) · 10.6 KB
/
main.go
File metadata and controls
361 lines (298 loc) · 10.6 KB
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
package main
import (
"context"
"fmt"
"os"
"strconv"
"time"
tea "charm.land/bubbletea/v2"
"github.com/fini-net/gh-observer/internal/config"
"github.com/fini-net/gh-observer/internal/debug"
ghclient "github.com/fini-net/gh-observer/internal/github"
"github.com/fini-net/gh-observer/internal/timing"
"github.com/fini-net/gh-observer/internal/tui"
"github.com/spf13/cobra"
"golang.org/x/term"
)
func main() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
var quickFlag bool
var debugFlag bool
func init() {
rootCmd.Flags().BoolVarP(&quickFlag, "quick", "q", false, "Skip fetching historical average runtimes")
rootCmd.Flags().BoolVarP(&debugFlag, "debug", "d", false, "Log suppressed errors and internal state to a file")
}
var rootCmd = &cobra.Command{
Use: "gh-observer [PR_NUMBER | PR_URL | ACTIONS_RUN_URL]",
Short: "Watch GitHub PR checks or Actions runs with runtime metrics",
Long: `gh-observer is a GitHub PR check watcher CLI tool that improves on
'gh pr checks --watch' by showing runtime metrics, queue latency,
and better handling of startup delays.
Supports watching checks on external repositories by passing a full PR URL:
gh-observer https://github.com/owner/repo/pull/123
Also supports watching GitHub Actions runs by passing a run URL:
gh-observer https://github.com/owner/repo/actions/runs/123456789`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
exitCode := run(args)
os.Exit(exitCode)
},
}
// runMode determines which mode the application is running in.
type runMode int
const (
modePR runMode = iota // Watch a PR's checks
modeRun // Watch an Actions workflow run
)
// runArgs holds the parsed arguments for either mode.
type runArgs struct {
mode runMode
owner string
repo string
prNumber int
runID int64
}
func run(args []string) int {
ctx := context.Background()
if debugFlag {
if err := debug.Enable(); err != nil {
fmt.Fprintf(os.Stderr, "Failed to enable debug logging: %v\n", err)
return 1
}
defer debug.Close()
fmt.Fprintf(os.Stderr, "Debug log: %s\n", debug.LogPath())
}
// Load configuration
cfg, err := config.Load()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to load config: %v\n", err)
return 1
}
// Create styles
styles := tui.NewStyles(
cfg.Colors.Success,
cfg.Colors.Failure,
cfg.Colors.Running,
cfg.Colors.Queued,
)
// Parse arguments
parsed, err := parseArgs(args)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
return 1
}
// Get GitHub token
token, err := ghclient.GetToken()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get GitHub token: %v\n", err)
return 1
}
switch parsed.mode {
case modePR:
return runPRMode(ctx, token, parsed, cfg, styles)
case modeRun:
return runActionsMode(ctx, token, parsed, cfg, styles)
default:
fmt.Fprintf(os.Stderr, "Unknown mode\n")
return 1
}
}
// parseArgs determines whether the argument is a PR number, PR URL, or Actions run URL.
func parseArgs(args []string) (runArgs, error) {
if len(args) == 0 {
// Auto-detect PR from current branch
prNumber, owner, repo, err := ghclient.GetCurrentPRWithRepo()
if err != nil {
if ghclient.IsJujutsu() {
return runArgs{}, fmt.Errorf("failed to detect PR in jj (Jujutsu) repo: %v\n\nHint: In a jj repo, you may need to:\n 1. Pass an explicit PR number: gh-observer 123\n 2. Pass a PR URL: gh-observer https://github.com/owner/repo/pull/123\n 3. Enable colocated mode: jj git colocation enable", err)
}
return runArgs{}, fmt.Errorf("failed to detect PR: %v\nMake sure you're on a PR branch or provide a PR number or URL", err)
}
return runArgs{mode: modePR, owner: owner, repo: repo, prNumber: prNumber}, nil
}
arg := args[0]
// Try PR URL first
if owner, repo, prNumber, err := ghclient.ParsePRURL(arg); err == nil {
return runArgs{mode: modePR, owner: owner, repo: repo, prNumber: prNumber}, nil
}
// Try Actions run URL
if owner, repo, runID, err := ghclient.ParseActionsRunURL(arg); err == nil {
return runArgs{mode: modeRun, owner: owner, repo: repo, runID: runID}, nil
}
// Try numeric PR number
if n, convErr := strconv.Atoi(arg); convErr == nil {
prNumber, owner, repo, err := ghclient.GetPRWithRepo(n)
if err != nil {
return runArgs{}, fmt.Errorf("failed to get PR #%d: %v", n, err)
}
return runArgs{mode: modePR, owner: owner, repo: repo, prNumber: prNumber}, nil
}
return runArgs{}, fmt.Errorf("invalid PR number, PR URL, or Actions run URL: %s", arg)
}
// runPRMode handles watching a PR's checks.
func runPRMode(ctx context.Context, token string, parsed runArgs, cfg *config.Config, styles tui.Styles) int {
owner, repo, prNumber := parsed.owner, parsed.repo, parsed.prNumber
// Check if running in a terminal
if !term.IsTerminal(int(os.Stdout.Fd())) {
return runSnapshot(ctx, token, owner, repo, prNumber, cfg.EnableLinks, quickFlag)
}
// Create model
model := tui.NewModel(ctx, token, owner, repo, prNumber, cfg.RefreshInterval, styles, cfg.EnableLinks, quickFlag)
// Run TUI
p := tea.NewProgram(model)
finalModel, err := p.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "Error running TUI: %v\n", err)
return 1
}
if m, ok := finalModel.(tui.Model); ok {
return m.ExitCode()
}
return 0
}
// runActionsMode handles watching an Actions workflow run.
func runActionsMode(ctx context.Context, token string, parsed runArgs, cfg *config.Config, styles tui.Styles) int {
owner, repo, runID := parsed.owner, parsed.repo, parsed.runID
// Check if running in a terminal
if !term.IsTerminal(int(os.Stdout.Fd())) {
return runRunSnapshot(ctx, owner, repo, runID, cfg.EnableLinks, quickFlag)
}
// Create run model
model := tui.NewRunModel(ctx, token, owner, repo, runID, cfg.RefreshInterval, styles, cfg.EnableLinks, quickFlag)
// Run TUI
p := tea.NewProgram(model)
finalModel, err := p.Run()
if err != nil {
fmt.Fprintf(os.Stderr, "Error running TUI: %v\n", err)
return 1
}
if m, ok := finalModel.(tui.RunModel); ok {
return m.ExitCode()
}
return 0
}
// runSnapshot prints a one-time snapshot of PR check status (non-interactive mode)
func runSnapshot(ctx context.Context, token, owner, repo string, prNumber int, enableLinks bool, quick bool) int {
client, err := ghclient.NewClient(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create GitHub client: %v\n", err)
return 1
}
prInfo, err := ghclient.FetchPRInfo(ctx, client, owner, repo, prNumber)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to fetch PR info: %v\n", err)
return 1
}
headCommitTime, err := time.Parse(time.RFC3339, prInfo.HeadCommitDate)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse commit time: %v\n", err)
return 1
}
checkRuns, _, err := ghclient.FetchCheckRunsGraphQL(ctx, token, owner, repo, prNumber)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to fetch check runs: %v\n", err)
return 1
}
fmt.Printf("PR #%d: %s\n\n", prNumber, prInfo.Title)
if len(checkRuns) == 0 {
sinceCreation := time.Since(headCommitTime)
fmt.Printf("No checks found (commit pushed %s ago)\n", timing.FormatDuration(sinceCreation))
fmt.Println("Checks may still be starting up or not configured for this PR")
return 0
}
var jobAverages map[string]time.Duration
if !quick {
client, err := ghclient.NewClient(ctx)
if err == nil {
avgs, _, _, err := ghclient.FetchJobAverages(ctx, client, owner, repo, checkRuns, nil, nil)
if err == nil {
jobAverages = avgs
}
}
}
widths := tui.CalculateColumnWidths(checkRuns, headCommitTime, jobAverages)
headerQueue, headerName, headerDuration, headerAvg := tui.FormatHeaderColumns(widths)
fmt.Printf("%s %s %s %s\n\n", headerQueue, headerName, headerDuration, headerAvg)
exitCode := 0
for _, check := range checkRuns {
nameCol := tui.BuildNameColumn(check, widths, enableLinks)
queueText := tui.FormatQueueLatency(check, headCommitTime)
durationText := tui.FormatDuration(check)
avgText := tui.FormatAvg(check, jobAverages)
icon := tui.GetCheckIcon(check.Status, check.Conclusion)
queueCol, _, durationCol, avgCol := tui.FormatAlignedColumns(queueText, tui.FormatCheckNameWithTruncate(check, widths.NameWidth), durationText, avgText, widths)
fmt.Printf("%s %s %s %s %s\n", queueCol, icon, nameCol, durationCol, avgCol)
if check.Status == "completed" {
if ghclient.FailureConclusion(check.Conclusion) {
exitCode = 1
}
}
}
return exitCode
}
// runRunSnapshot prints a one-time snapshot of Actions run status (non-interactive mode)
func runRunSnapshot(ctx context.Context, owner, repo string, runID int64, enableLinks bool, quick bool) int {
token, err := ghclient.GetToken()
if err != nil {
fmt.Fprintf(os.Stderr, "failed to get GitHub token: %v\n", err)
return 1
}
client, err := ghclient.NewClientFromToken(token)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create GitHub client: %v\n", err)
return 1
}
runInfo, err := ghclient.FetchRunInfo(ctx, client, owner, repo, runID)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to fetch run info: %v\n", err)
return 1
}
jobs, _, err := ghclient.FetchRunJobs(ctx, client, owner, repo, runID)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to fetch jobs: %v\n", err)
return 1
}
var timeSinceStr string
if runInfo.HeadCommitTime != nil && !runInfo.HeadCommitTime.IsZero() {
timeSinceStr = fmt.Sprintf("Pushed %s ago", timing.FormatDuration(time.Since(runInfo.HeadCommitTime.Time)))
} else if runInfo.CreatedAt != nil && !runInfo.CreatedAt.IsZero() {
timeSinceStr = fmt.Sprintf("Created %s ago", timing.FormatDuration(time.Since(runInfo.CreatedAt.Time)))
}
fmt.Printf("%s/%s: %s\n", owner, repo, runInfo.DisplayTitle)
if timeSinceStr != "" {
fmt.Println(timeSinceStr)
}
fmt.Println()
if len(jobs) == 0 {
fmt.Println("No jobs found")
return 0
}
var jobAverages map[string]time.Duration
if !quick {
checkRuns := ghclient.WorkflowJobInfoToCheckRuns(jobs)
avgs, _, _, err := ghclient.FetchJobAverages(ctx, client, owner, repo, checkRuns, nil, nil)
if err == nil {
jobAverages = avgs
}
}
widths := tui.CalculateRunColumnWidths(jobs, jobAverages)
headerName, headerDuration, headerAvg := tui.FormatRunHeaderColumns(widths)
fmt.Printf(" %s %s %s\n\n", headerName, headerDuration, headerAvg)
exitCode := 0
for _, job := range jobs {
nameCol := tui.BuildRunJobNameColumn(job, widths, enableLinks)
durationText := tui.FormatRunJobDuration(job)
avgText := tui.FormatRunJobAvg(job, jobAverages)
icon := tui.GetCheckIcon(job.Status, job.Conclusion)
fmt.Printf("%s %s %s %s\n", icon, nameCol, durationText, avgText)
if job.Status == "completed" {
if ghclient.FailureJobConclusion(job.Conclusion) {
exitCode = 1
}
}
}
return exitCode
}