pr-bro 0.5.1

Know which PR to review next. Ranks pull requests by weighted scoring.
Documentation
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
use chrono::Duration;
use owo_colors::OwoColorize;
use std::io::IsTerminal;
use terminal_size::{terminal_size, Width};

use crate::github::types::PullRequest;

/// Format a list of PRs as one line per PR
/// Format: "{title} | {repo} | {author} | {url}"
pub fn format_pr_list(prs: &[PullRequest], use_colors: bool) -> String {
    if prs.is_empty() {
        return "No pull requests found.".to_string();
    }

    prs.iter()
        .map(|pr| format_pr_line(pr, use_colors))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Format a single PR as one line
fn format_pr_line(pr: &PullRequest, use_colors: bool) -> String {
    if use_colors {
        format!(
            "{} | {} | {} | {}",
            pr.title.bold(),
            pr.repo.cyan(),
            pr.author.yellow(),
            pr.short_ref().underline()
        )
    } else {
        format!(
            "{} | {} | {} | {}",
            pr.title,
            pr.repo,
            pr.author,
            pr.short_ref()
        )
    }
}

/// Format a single PR with detailed multi-line output (for verbose mode)
pub fn format_pr_detail(pr: &PullRequest, use_colors: bool) -> String {
    let age = format_age(pr.age());
    let total_size = pr.size();

    if use_colors {
        format!(
            "{}\n  Repo: {}\n  Author: {}\n  Age: {}\n  Size: +{}/{} ({} lines)\n  Approvals: {}\n  URL: {}",
            pr.title.bold(),
            pr.repo.cyan(),
            pr.author.yellow(),
            age,
            pr.additions.green(),
            pr.deletions.red(),
            total_size,
            pr.approvals,
            pr.url.underline()
        )
    } else {
        format!(
            "{}\n  Repo: {}\n  Author: {}\n  Age: {}\n  Size: +{}/{} ({} lines)\n  Approvals: {}\n  URL: {}",
            pr.title,
            pr.repo,
            pr.author,
            age,
            pr.additions,
            pr.deletions,
            total_size,
            pr.approvals,
            pr.url
        )
    }
}

/// Check if stdout is a TTY (for auto-detecting color support)
pub fn should_use_colors() -> bool {
    std::io::stdout().is_terminal()
}

/// Format a score in compact notation (1.5k, 2.3M, 847)
/// If incomplete is true, appends asterisk to indicate partial scoring
pub fn format_score(score: f64, incomplete: bool) -> String {
    let formatted = if score >= 1_000_000.0 {
        format!("{:.1}M", score / 1_000_000.0)
    } else if score >= 1_000.0 {
        format!("{:.1}k", score / 1_000.0)
    } else {
        format!("{:.0}", score)
    };

    // Trim trailing .0 (e.g., "1.0k" -> "1k")
    let trimmed = formatted.replace(".0M", "M").replace(".0k", "k");

    if incomplete {
        format!("{}*", trimmed)
    } else {
        trimmed
    }
}

/// A PR with its calculated score for display
pub struct ScoredPr<'a> {
    pub pr: &'a PullRequest,
    pub score: f64,
    pub incomplete: bool,
}

/// Get terminal width, defaulting to None for pipes (unlimited)
fn get_terminal_width() -> Option<usize> {
    terminal_size().map(|(Width(w), _)| w as usize)
}

/// Truncate title to fit available width, accounting for Unicode
fn truncate_title(title: &str, max_width: usize) -> String {
    let chars: Vec<char> = title.chars().collect();
    if chars.len() <= max_width {
        title.to_string()
    } else if max_width > 3 {
        format!("{}...", chars[..max_width - 3].iter().collect::<String>())
    } else {
        chars[..max_width].iter().collect()
    }
}

/// Format PRs as scored table with columns: Index, Score, Title, URL
/// No headers (minimal format per CONTEXT.md)
/// Index column: 3 chars (fits "99."), right-aligned
/// Score column is right-aligned, 7 chars wide (fits "9999.9M")
pub fn format_scored_table(prs: &[ScoredPr], use_colors: bool) -> String {
    if prs.is_empty() {
        return "No pull requests found.".to_string();
    }

    let term_width = get_terminal_width();

    // Index column: 3 chars + 1 space = 4
    // Score column: 7 chars + 2 spaces = 9
    // URL: varies, ~50 chars typical for GitHub
    // Leave rest for title
    let index_width = 3;
    let score_width = 7;
    let separator = "  ";

    prs.iter()
        .enumerate()
        .map(|(idx, scored)| {
            // 1-based index, right-aligned with trailing dot
            let index_str = format!("{:>2}.", idx + 1);
            let score_str = format_score(scored.score, scored.incomplete);
            let score_padded = format!("{:>width$}", score_str, width = score_width);

            // Calculate available title width (accounting for index column)
            let ref_len = scored.pr.short_ref().len();
            let fixed_width = index_width + 1 + score_width + separator.len() * 2 + ref_len;

            let title = if let Some(width) = term_width {
                if width > fixed_width + 10 {
                    truncate_title(&scored.pr.title, width - fixed_width)
                } else {
                    // Very narrow terminal, show truncated
                    truncate_title(&scored.pr.title, 20)
                }
            } else {
                // No terminal (pipe), don't truncate
                scored.pr.title.clone()
            };

            if use_colors {
                format!(
                    "{} {}{}{}{}{}",
                    index_str.dimmed(),
                    score_padded.bold(),
                    separator,
                    title,
                    separator,
                    scored.pr.short_ref().underline()
                )
            } else {
                format!(
                    "{} {}{}{}{}{}",
                    index_str,
                    score_padded,
                    separator,
                    title,
                    separator,
                    scored.pr.short_ref()
                )
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Format PRs as tab-separated values for scripting
/// Columns: score, title, repo, pr_ref (no headers, no colors)
pub fn format_tsv(prs: &[ScoredPr]) -> String {
    if prs.is_empty() {
        return String::new();
    }

    prs.iter()
        .map(|scored| {
            let score = scored.score.round() as i64;
            format!(
                "{}\t{}\t{}\t{}",
                score,
                scored.pr.title,
                scored.pr.repo,
                scored.pr.short_ref()
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Format a duration into a human-readable age string
/// "2h" for hours, "3d" for days, "1w" for weeks
pub fn format_age(duration: Duration) -> String {
    let hours = duration.num_hours();
    let days = duration.num_days();
    let weeks = days / 7;

    if weeks >= 1 {
        format!("{}w", weeks)
    } else if days >= 1 {
        format!("{}d", days)
    } else if hours >= 1 {
        format!("{}h", hours)
    } else {
        let minutes = duration.num_minutes();
        if minutes >= 1 {
            format!("{}m", minutes)
        } else {
            "now".to_string()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;

    fn sample_pr() -> PullRequest {
        PullRequest {
            title: "Fix login bug".to_string(),
            number: 123,
            author: "octocat".to_string(),
            repo: "owner/repo".to_string(),
            url: "https://github.com/owner/repo/pull/123".to_string(),
            created_at: Utc::now() - Duration::hours(5),
            updated_at: Utc::now() - Duration::hours(1),
            additions: 50,
            deletions: 10,
            approvals: 1,
            draft: false,
            labels: vec![],
            user_has_reviewed: false,
            filtered_size: None,
        }
    }

    #[test]
    fn test_format_pr_list_empty() {
        let prs: Vec<PullRequest> = vec![];
        let result = format_pr_list(&prs, false);
        assert_eq!(result, "No pull requests found.");
    }

    #[test]
    fn test_format_pr_list_single() {
        let prs = vec![sample_pr()];
        let result = format_pr_list(&prs, false);
        assert!(result.contains("Fix login bug"));
        assert!(result.contains("owner/repo"));
        assert!(result.contains("octocat"));
        assert!(result.contains("owner/repo#123"));
    }

    #[test]
    fn test_format_pr_detail() {
        let pr = sample_pr();
        let result = format_pr_detail(&pr, false);
        assert!(result.contains("Fix login bug"));
        assert!(result.contains("Repo: owner/repo"));
        assert!(result.contains("Author: octocat"));
        assert!(result.contains("Size: +50/10 (60 lines)"));
        assert!(result.contains("Approvals: 1"));
    }

    #[test]
    fn test_format_age_hours() {
        let duration = Duration::hours(3);
        assert_eq!(format_age(duration), "3h");
    }

    #[test]
    fn test_format_age_days() {
        let duration = Duration::days(2);
        assert_eq!(format_age(duration), "2d");
    }

    #[test]
    fn test_format_age_weeks() {
        let duration = Duration::weeks(2);
        assert_eq!(format_age(duration), "2w");
    }

    #[test]
    fn test_format_age_minutes() {
        let duration = Duration::minutes(30);
        assert_eq!(format_age(duration), "30m");
    }

    #[test]
    fn test_format_age_now() {
        let duration = Duration::seconds(30);
        assert_eq!(format_age(duration), "now");
    }

    // format_score tests
    #[test]
    fn test_format_score_small() {
        assert_eq!(format_score(500.0, false), "500");
    }

    #[test]
    fn test_format_score_zero() {
        assert_eq!(format_score(0.0, false), "0");
    }

    #[test]
    fn test_format_score_thousand_exact() {
        assert_eq!(format_score(1000.0, false), "1k");
    }

    #[test]
    fn test_format_score_thousand_decimal() {
        assert_eq!(format_score(1500.0, false), "1.5k");
    }

    #[test]
    fn test_format_score_million_exact() {
        assert_eq!(format_score(1_000_000.0, false), "1M");
    }

    #[test]
    fn test_format_score_million_decimal() {
        assert_eq!(format_score(2_300_000.0, false), "2.3M");
    }

    #[test]
    fn test_format_score_with_incomplete() {
        assert_eq!(format_score(1500.0, true), "1.5k*");
    }

    #[test]
    fn test_format_score_small_with_incomplete() {
        assert_eq!(format_score(847.0, true), "847*");
    }

    // truncate_title tests
    #[test]
    fn test_truncate_title_short() {
        assert_eq!(truncate_title("Short title", 20), "Short title");
    }

    #[test]
    fn test_truncate_title_exact() {
        assert_eq!(truncate_title("Exact", 5), "Exact");
    }

    #[test]
    fn test_truncate_title_long() {
        assert_eq!(
            truncate_title("This is a very long title", 15),
            "This is a ve..."
        );
    }

    #[test]
    fn test_truncate_title_unicode() {
        // Unicode characters should be handled correctly (by char, not by byte)
        assert_eq!(truncate_title("Hello cafe", 10), "Hello cafe");
        assert_eq!(truncate_title("Hello cafe world", 10), "Hello c...");
    }

    #[test]
    fn test_truncate_title_very_narrow() {
        // Very narrow case (max_width <= 3)
        assert_eq!(truncate_title("Hello world", 3), "Hel");
    }

    // format_scored_table tests
    #[test]
    fn test_format_scored_table_empty() {
        let prs: Vec<ScoredPr> = vec![];
        let result = format_scored_table(&prs, false);
        assert_eq!(result, "No pull requests found.");
    }

    #[test]
    fn test_format_scored_table_single() {
        let pr = sample_pr();
        let scored_prs = vec![ScoredPr {
            pr: &pr,
            score: 1500.0,
            incomplete: false,
        }];
        let result = format_scored_table(&scored_prs, false);
        // Index should be 1-based
        assert!(result.contains(" 1."));
        // Score should be right-aligned in 7-char column
        assert!(result.contains("1.5k"));
        assert!(result.contains("Fix login bug"));
        assert!(result.contains("owner/repo#123"));
    }

    #[test]
    fn test_format_scored_table_incomplete() {
        let pr = sample_pr();
        let scored_prs = vec![ScoredPr {
            pr: &pr,
            score: 847.0,
            incomplete: true,
        }];
        let result = format_scored_table(&scored_prs, false);
        assert!(result.contains(" 1."));
        assert!(result.contains("847*"));
    }

    #[test]
    fn test_format_scored_table_multiple() {
        let pr1 = sample_pr();
        let mut pr2 = sample_pr();
        pr2.title = "Add new feature".to_string();
        pr2.number = 456;
        pr2.url = "https://github.com/owner/repo/pull/456".to_string();

        let scored_prs = vec![
            ScoredPr {
                pr: &pr1,
                score: 2000.0,
                incomplete: false,
            },
            ScoredPr {
                pr: &pr2,
                score: 500.0,
                incomplete: false,
            },
        ];
        let result = format_scored_table(&scored_prs, false);
        let lines: Vec<&str> = result.lines().collect();
        assert_eq!(lines.len(), 2);
        // Check indices are sequential
        assert!(lines[0].contains(" 1."));
        assert!(lines[1].contains(" 2."));
        // Check scores and titles
        assert!(lines[0].contains("2k"));
        assert!(lines[0].contains("Fix login bug"));
        assert!(lines[1].contains("500"));
        assert!(lines[1].contains("Add new feature"));
    }

    // format_tsv tests
    #[test]
    fn test_format_tsv_empty() {
        let prs: Vec<ScoredPr> = vec![];
        let result = format_tsv(&prs);
        assert_eq!(result, "");
    }

    #[test]
    fn test_format_tsv_single() {
        let pr = sample_pr();
        let scored_prs = vec![ScoredPr {
            pr: &pr,
            score: 1500.7,
            incomplete: false,
        }];
        let result = format_tsv(&scored_prs);
        assert_eq!(result, "1501\tFix login bug\towner/repo\towner/repo#123");
    }

    #[test]
    fn test_format_tsv_multiple() {
        let pr1 = sample_pr();
        let mut pr2 = sample_pr();
        pr2.title = "Add feature".to_string();
        pr2.url = "https://github.com/owner/repo/pull/456".to_string();

        let scored_prs = vec![
            ScoredPr {
                pr: &pr1,
                score: 2000.0,
                incomplete: false,
            },
            ScoredPr {
                pr: &pr2,
                score: 500.0,
                incomplete: true,
            },
        ];
        let result = format_tsv(&scored_prs);
        let lines: Vec<&str> = result.lines().collect();
        assert_eq!(lines.len(), 2);
        // Verify tab-separated format
        assert!(lines[0].contains('\t'));
        assert_eq!(lines[0].split('\t').count(), 4);
        assert!(lines[0].starts_with("2000\t"));
        assert!(lines[1].starts_with("500\t"));
    }

    #[test]
    fn test_format_scored_table_index_format() {
        // Verify index format: right-aligned, 1-based, with trailing dot
        let pr = sample_pr();
        let scored_prs = vec![ScoredPr {
            pr: &pr,
            score: 100.0,
            incomplete: false,
        }];
        let result = format_scored_table(&scored_prs, false);
        // Should start with " 1." (space for alignment, then index)
        assert!(result.starts_with(" 1."));
    }
}