-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsole.go
601 lines (514 loc) · 14.6 KB
/
console.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
package main
import (
"context"
"fmt"
"io"
"os"
"sort"
"strings"
"sync"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/XiaoConstantine/dspy-go/pkg/logging"
"github.com/briandowns/spinner"
"github.com/google/go-github/v68/github"
"github.com/logrusorgru/aurora"
"github.com/mattn/go-isatty"
)
type ConsoleInterface interface {
StartSpinner(message string)
StopSpinner()
WithSpinner(ctx context.Context, message string, fn func() error) error
ShowComments(comments []PRReviewComment, metric MetricsCollector)
ShowSummary(comments []PRReviewComment, metric MetricsCollector)
StartReview(pr *github.PullRequest)
ReviewingFile(file string, current, total int)
ConfirmReviewPost(commentCount int) (bool, error)
ReviewComplete()
UpdateSpinnerText(text string)
ShowReviewMetrics(metrics MetricsCollector, comments []PRReviewComment)
Confirm(opts PromptOptions) (bool, error)
FileError(filepath string, err error)
Printf(format string, a ...interface{})
Println(a ...interface{})
PrintHeader(text string)
NoIssuesFound(file string, chunkNumber, totalChunks int)
SeverityIcon(severity string) string
Color() bool
Spinner() *spinner.Spinner
}
// Console handles user-facing output separate from logging.
type Console struct {
w io.Writer
logger *logging.Logger // For debug logs
spinner *spinner.Spinner
color bool
mu sync.Mutex
}
type SpinnerConfig struct {
Color string
Speed time.Duration
CharSet []string
Prefix string
Suffix string
}
// PromptOptions configures how the confirmation prompt behaves.
type PromptOptions struct {
Message string // The question to ask
Default bool // Default answer if user just hits enter
HelpText string // Optional help text shown below prompt
Timeout time.Duration // Optional timeout for response
Color bool // Whether to use colors in prompt
}
func DefaultPromptOptions() PromptOptions {
return PromptOptions{
Message: "Continue?",
Default: false,
HelpText: "",
Timeout: 30 * time.Second,
Color: true,
}
}
func DefaultSpinnerConfig() SpinnerConfig {
return SpinnerConfig{
Color: "cyan",
Speed: 100 * time.Millisecond,
CharSet: spinner.CharSets[14], // Using the character set from your example
Prefix: "Processing ",
Suffix: "",
}
}
func NewConsole(w io.Writer, logger *logging.Logger, cfg *SpinnerConfig) ConsoleInterface {
if cfg == nil {
defaultCfg := DefaultSpinnerConfig()
cfg = &defaultCfg
}
s := spinner.New(cfg.CharSet, cfg.Speed)
s.Prefix = cfg.Prefix
s.Suffix = cfg.Suffix
if err := s.Color(cfg.Color); err != nil {
logger.Warn(context.Background(), "Failed to set spinner color: %v", err)
}
// Detect if terminal supports color
color := true
if f, ok := w.(*os.File); ok {
color = isatty.IsTerminal(f.Fd())
}
return &Console{
w: w,
logger: logger,
color: color,
spinner: s,
}
}
func (c *Console) Spinner() *spinner.Spinner {
c.mu.Lock()
defer c.mu.Unlock()
return c.spinner
}
func (c *Console) StartSpinner(message string) {
c.mu.Lock()
defer c.mu.Unlock()
c.spinner.Suffix = fmt.Sprintf(" %s", message)
c.spinner.Start()
}
// StopSpinner stops the current spinner.
func (c *Console) StopSpinner() {
c.mu.Lock()
defer c.mu.Unlock()
if c.spinner.Active() {
c.spinner.Stop()
}
}
func (c *Console) Color() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.color
}
func (c *Console) Confirm(opts PromptOptions) (bool, error) {
// Create the survey prompt with styling
prompt := &survey.Confirm{
Message: opts.Message,
Default: opts.Default,
Help: opts.HelpText,
}
// Configure survey settings
surveyOpts := []survey.AskOpt{
survey.WithIcons(func(icons *survey.IconSet) {
if c.color {
icons.Question.Text = "?"
icons.Question.Format = "cyan+b"
icons.Help.Format = "blue"
}
}),
}
// Handle piped input (non-interactive mode)
if !isatty.IsTerminal(os.Stdin.Fd()) {
return opts.Default, nil
}
var response bool
err := survey.AskOne(prompt, &response, surveyOpts...)
// Special handling for interrupt (Ctrl+C)
if err == terminal.InterruptErr {
if c.color {
c.Println(aurora.Red("\n✖ Operation cancelled").String())
} else {
c.Println("\n✖ Operation cancelled")
}
return false, nil
}
return response, err
}
func (c *Console) ConfirmReviewPost(commentCount int) (bool, error) {
// Format message based on comment count
message := fmt.Sprintf("Post %d review comment", commentCount)
if commentCount != 1 {
message += "s"
}
message += " to GitHub?"
// Create options with helpful context
opts := DefaultPromptOptions()
opts.Message = message
opts.HelpText = "This will create a pull request review with the comments shown above"
opts.Color = c.color
return c.Confirm(opts)
}
// Helper method for handling LLM operations with spinner.
func (c *Console) WithSpinner(ctx context.Context, message string, fn func() error) error {
c.StartSpinner(message)
defer c.StopSpinner()
// Create a channel for the result
errCh := make(chan error, 1)
// Run the operation in a goroutine
go func() {
errCh <- fn()
}()
// Wait for either completion or context cancellation
select {
case err := <-errCh:
return err
case <-ctx.Done():
return ctx.Err()
}
}
func (c *Console) printFields(fields map[string]interface{}) {
// Get maximum key length for alignment
maxKeyLen := 0
for k := range fields {
if len(k) > maxKeyLen {
maxKeyLen = len(k)
}
}
// Sort keys for consistent output
keys := make([]string, 0, len(fields))
for k := range fields {
keys = append(keys, k)
}
sort.Strings(keys)
// Print each field with proper alignment
for _, k := range keys {
// Create the label with proper padding
label := fmt.Sprintf("%-*s", maxKeyLen, k)
if c.color {
// Color the label but not the value
label = aurora.Blue(label).String()
}
// Print the formatted line
c.Printf("%s : %v\n", label, fields[k])
}
}
func (c *Console) StartReview(pr *github.PullRequest) {
// Safely handle GitHub API pointer types
title := ""
if pr.Title != nil {
title = *pr.Title
}
owner := ""
if pr.Base != nil && pr.Base.Repo != nil && pr.Base.Repo.Owner != nil && pr.Base.Repo.Owner.Login != nil {
owner = *pr.Base.Repo.Owner.Login
}
repoName := ""
if pr.Base != nil && pr.Base.Repo != nil && pr.Base.Repo.Name != nil {
repoName = *pr.Base.Repo.Name
}
author := ""
if pr.User != nil && pr.User.Login != nil {
author = *pr.User.Login
}
changedFiles := 0
if pr.ChangedFiles != nil {
changedFiles = *pr.ChangedFiles
}
c.PrintHeader(fmt.Sprintf("Reviewing PR #%d: %s", pr.Number, title))
// Now we use interface{} for the map to handle different value types
c.printFields(map[string]interface{}{
"Repository": fmt.Sprintf("%s/%s", owner, repoName),
"Author": author,
"Files": fmt.Sprintf("%d files changed", changedFiles),
})
c.Println()
}
func (c *Console) ReviewingFile(file string, current, total int) {
if c.color {
c.Printf("%s %s %s\n",
aurora.Blue("⟳").Bold(),
aurora.White(fmt.Sprintf("[%d/%d]", current, total)).Bold(),
aurora.Cyan(fmt.Sprintf("Analyzing %s...", file)).Bold(),
)
} else {
c.Printf("⟳ [%d/%d] Analyzing %s...\n", current, total, file)
}
}
func (c *Console) NoIssuesFound(file string, chunkNumber, totalChunks int) {
c.Printf("✨ No issues found in chunk (%d/%d) of %s\n", chunkNumber, totalChunks, file)
}
func (c *Console) ShowComments(comments []PRReviewComment, metric MetricsCollector) {
if len(comments) == 0 {
return
}
c.Println("\nReview Comments:")
for _, comment := range comments {
if c.color {
c.Printf("%s %s:%d\n",
c.SeverityIcon(comment.Severity),
comment.FilePath,
comment.LineNumber,
)
} else {
c.Printf("[%s] %s:%d\n",
comment.Severity,
comment.FilePath,
comment.LineNumber,
)
}
c.Println(indent(comment.Content, 2))
if comment.Suggestion != "" {
if c.color {
c.Println(aurora.Green(" Suggestion:").String())
} else {
c.Println(" Suggestion:")
}
c.Println(indent(comment.Suggestion, 4))
}
c.Println()
if err := c.collectFeedback(comment, metric); err != nil {
c.logger.Warn(context.Background(), "Failed to collect feedback: %v", err)
}
}
}
func (c *Console) ShowSummary(comments []PRReviewComment, metric MetricsCollector) {
c.PrintHeader("Review Summary")
// Group by severity
bySeverity := make(map[string]int)
for _, comment := range comments {
bySeverity[comment.Severity]++
}
if len(bySeverity) == 0 {
c.Println("✨ No issues found")
return
}
// Print counts by severity
for _, severity := range []string{"critical", "warning", "suggestion"} {
if count := bySeverity[severity]; count > 0 {
icon := c.SeverityIcon(severity)
c.Printf("%s %s: %d\n", icon, severity, count)
}
}
c.ShowComments(comments, metric)
}
func (c *Console) FileError(filepath string, err error) {
if c.color {
c.Printf("%s Error processing %s: %v\n",
aurora.Red("✖").String(),
aurora.Bold(filepath).String(),
err)
} else {
c.Printf("✖ Error processing %s: %v\n", filepath, err)
}
}
func (c *Console) PostingComments(count int) {
if count > 0 {
c.Printf("\nPosting %d comments to GitHub...\n", count)
}
}
func (c *Console) ReviewComplete() {
if c.color {
c.Println(aurora.Green("\n✓ Review completed successfully").String())
} else {
c.Println("\n✓ Review completed successfully")
}
}
func (c *Console) SeverityIcon(severity string) string {
if !c.color {
return "[" + severity + "]"
}
switch severity {
case "critical":
return aurora.Red("●").String()
case "warning":
return aurora.Yellow("●").String()
case "suggestion":
return aurora.Blue("●").String()
default:
return "●"
}
}
func (c *Console) PrintHeader(text string) {
if c.color {
text = aurora.Bold(text).String()
}
c.Printf("\n=== %s ===\n", text)
}
func (c *Console) Println(a ...interface{}) {
fmt.Fprintln(c.w, a...)
}
func (c *Console) Printf(format string, a ...interface{}) {
fmt.Fprintf(c.w, format, a...)
}
func (c *Console) ShowReviewMetrics(metrics MetricsCollector, comments []PRReviewComment) {
c.PrintHeader("Review Metrics Summary")
// First show immediate review statistics
c.Println("\nImmediate Review Impact:")
// Group comments by category for analysis
categoryCounts := make(map[string]int)
severityCounts := make(map[string]int)
for _, comment := range comments {
categoryCounts[comment.Category]++
severityCounts[comment.Severity]++
}
// Show total comments with breakdown
if c.color {
c.Printf("Total Comments: %s\n", aurora.Blue(len(comments)).Bold())
} else {
c.Printf("Total Comments: %d\n", len(comments))
}
// Show category distribution
if len(categoryCounts) > 0 {
c.Println("\nComments by Category:")
categories := make([]string, 0, len(categoryCounts))
for category := range categoryCounts {
categories = append(categories, category)
}
sort.Strings(categories)
for _, category := range categories {
count := categoryCounts[category]
percentage := float64(count) / float64(len(comments)) * 100
if c.color {
c.Printf(" %-25s %s (%0.1f%%)\n",
aurora.Blue(category),
aurora.White(count).Bold(),
percentage)
} else {
c.Printf(" %-25s %d (%0.1f%%)\n", category, count, percentage)
}
// Show category-specific metrics
if stats := metrics.GetCategoryMetrics(category); stats.TotalComments > 0 {
outdatedRate := stats.GetOutdatedRate() * 100
c.Printf(" • Historical Outdated Rate: %0.1f%%\n", outdatedRate)
}
}
}
// Show severity distribution
if len(severityCounts) > 0 {
c.Println("\nComments by Severity:")
severities := []string{"critical", "warning", "suggestion"}
for _, severity := range severities {
if count := severityCounts[severity]; count > 0 {
percentage := float64(count) / float64(len(comments)) * 100
icon := c.SeverityIcon(severity)
if c.color {
c.Printf(" %s %-12s %s (%0.1f%%)\n",
icon,
severity,
aurora.White(count).Bold(),
percentage)
} else {
c.Printf(" %s %-12s %d (%0.1f%%)\n",
icon,
severity,
count,
percentage)
}
}
}
}
// Show historical impact metrics if available
c.Println("\nHistorical Impact Metrics:")
c.printFields(map[string]interface{}{
"Overall Outdated Rate": fmt.Sprintf("%0.1f%%", metrics.GetOverallOutdatedRate()*100),
"Weekly Active Users": metrics.GetWeeklyActiveUsers(),
"Review Response Rate": fmt.Sprintf("%0.1f%%", metrics.GetReviewResponseRate()*100),
})
// Add helpful context about the metrics
c.Println("\nMetric Explanations:")
c.Println("• Outdated Rate measures how often flagged code is modified, indicating review effectiveness")
c.Println("• Review Response Rate shows how frequently developers engage with review comments")
c.Println("• Historical metrics help track long-term impact of automated reviews")
}
func (c *Console) collectFeedback(comment PRReviewComment, metric MetricsCollector) error {
helpful, err := c.Confirm(PromptOptions{
Message: "Was this comment helpful?",
Default: true,
})
if err != nil {
return err
}
if !helpful {
// Collect reason if not helpful
reason, err := c.promptFeedbackReason()
if err != nil {
return err
}
metric.TrackUserFeedback(context.Background(), *comment.ThreadID, false, reason)
} else {
metric.TrackUserFeedback(context.Background(), *comment.ThreadID, true, "")
}
return nil
}
// promptFeedbackReason collects the reason for unhelpful feedback.
func (c *Console) promptFeedbackReason() (string, error) {
reasons := []string{
"Not relevant to the code",
"Too vague or unclear",
"Already fixed",
"Incorrect suggestion",
"Other",
}
var selectedReason string
prompt := &survey.Select{
Message: "Why wasn't this comment helpful?",
Options: reasons,
Default: reasons[0],
}
err := survey.AskOne(prompt, &selectedReason)
if err != nil {
return "", fmt.Errorf("failed to get feedback reason: %w", err)
}
// If "Other" was selected, prompt for specific reason
if selectedReason == "Other" {
var customReason string
customPrompt := &survey.Input{
Message: "Please specify the reason:",
}
err := survey.AskOne(customPrompt, &customReason)
if err != nil {
return "", fmt.Errorf("failed to get custom reason: %w", err)
}
return customReason, nil
}
return selectedReason, nil
}
// UpdateSpinnerText updates the spinner's suffix text while maintaining animation.
func (c *Console) UpdateSpinnerText(text string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.spinner.Active() {
c.spinner.Suffix = fmt.Sprintf(" %s", text)
}
}
// indent adds spaces to the start of each line.
func indent(s string, spaces int) string {
prefix := strings.Repeat(" ", spaces)
return prefix + strings.ReplaceAll(s, "\n", "\n"+prefix)
}