tbdflow 0.27.0

A CLI to streamline your Git workflow for Trunk-Based Development.
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
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
use crate::config::{Config, RadarLevel, RadarOnCommit};
use crate::git;
use anyhow::Result;
use chrono::Utc;
use colored::*;
use std::collections::HashSet;

#[derive(Debug)]
pub enum OverlapKind {
    SameFile,
    LineOverlap {
        my_lines: Vec<git::HunkRange>,
        their_lines: Vec<git::HunkRange>,
    },
}

#[derive(Debug)]
pub struct FileOverlap {
    pub file_path: String,
    pub overlap_kind: OverlapKind,
}

#[derive(Debug)]
pub struct BranchOverlap {
    pub branch_name: String,
    pub author: String,
    pub commits_ahead: u32,
    pub overlapping_files: Vec<FileOverlap>,
}

#[derive(Debug)]
pub struct RadarResult {
    pub overlaps: Vec<BranchOverlap>,
    pub branches_scanned: usize,
    pub local_files_count: usize,
}

#[derive(Debug)]
pub struct TrunkStatus {
    pub ci: git::CiStatus,
    pub time_ago: Option<String>,
}

/// human-readable X ago
fn format_duration_ago(seconds: i64) -> String {
    if seconds < 60 {
        format!("{}s ago", seconds)
    } else if seconds < 3600 {
        format!("{}m ago", seconds / 60)
    } else if seconds < 86400 {
        format!("{}h ago", seconds / 3600)
    } else {
        format!("{}d ago", seconds / 86400)
    }
}

pub fn get_trunk_status(config: &Config, verbose: bool, dry_run: bool) -> TrunkStatus {
    let main = &config.main_branch_name;

    let ci = if config.ci_check.enabled {
        git::check_ci_status(main, verbose, dry_run)
    } else {
        git::CiStatus::Unknown("CI check not enabled".to_string())
    };

    let time_ago = git::get_latest_commit_time(main, verbose, dry_run)
        .ok()
        .flatten()
        .map(|dt| {
            let elapsed = Utc::now().signed_duration_since(dt).num_seconds().max(0);
            format_duration_ago(elapsed)
        });

    TrunkStatus { ci, time_ago }
}

fn print_trunk_status(status: &TrunkStatus, main_branch: &str) {
    let (label, colour_fn): (&str, fn(&str) -> ColoredString) = match &status.ci {
        git::CiStatus::Green => ("Green", |s: &str| s.green()),
        git::CiStatus::Failed => ("Red", |s: &str| s.red()),
        git::CiStatus::Pending => ("Pending", |s: &str| s.yellow()),
        git::CiStatus::Unknown(_) => ("Unknown", |s: &str| s.dimmed()),
    };

    let detail = status
        .time_ago
        .as_deref()
        .map(|t| format!(" (Last integrated {})", t))
        .unwrap_or_default();

    let line = format!("{} is {}{}", main_branch, label, detail);
    println!("{}", colour_fn(&line));
}

// max 5 files latest 72 hours
pub type Hotspot = (String, usize);
const CHURN_HOURS: u64 = 72;
const CHURN_LIMIT: usize = 5;

pub fn get_hotspots(config: &Config, verbose: bool, dry_run: bool) -> Result<Vec<Hotspot>> {
    git::get_file_churn(
        &config.main_branch_name,
        CHURN_HOURS,
        CHURN_LIMIT,
        verbose,
        dry_run,
    )
}

fn print_hotspots(hotspots: &[Hotspot]) {
    if hotspots.is_empty() {
        println!("{}", "No file changes in the last 3 days.".dimmed());
    } else {
        for (file, count) in hotspots {
            let label = if *count == 1 { "change" } else { "changes" };
            println!(
                "  {} ({} {})",
                file.bold(),
                count.to_string().yellow(),
                label
            );
        }
    }
}

/// Run the full radar scan: fetch, compare local changes against all active remote branches.
pub fn scan(config: &Config, verbose: bool, dry_run: bool) -> Result<RadarResult> {
    let main_branch = &config.main_branch_name;

    if verbose {
        println!("{}", "[RADAR] Fetching latest from origin...".dimmed());
    }
    git::fetch_origin(verbose, dry_run)?;

    let local_files = git::get_local_changed_files(verbose, dry_run)?;
    if local_files.is_empty() {
        return Ok(RadarResult {
            overlaps: vec![],
            branches_scanned: 0,
            local_files_count: 0,
        });
    }
    let local_file_set: HashSet<&str> = local_files.iter().map(|s| s.as_str()).collect();

    let active_branches = git::get_active_remote_branches(main_branch, verbose, dry_run)?;

    let current_branch = git::get_current_branch(verbose, dry_run).unwrap_or_default();
    let branches_to_scan: Vec<&String> = active_branches
        .iter()
        .filter(|b| b.as_str() != current_branch)
        .collect();

    let branches_scanned = branches_to_scan.len();
    let level = &config.radar.level;
    let ignore_patterns = &config.radar.ignore_patterns;

    let mut overlaps = Vec::new();
    let main_ref = format!("origin/{}", main_branch);

    for branch in &branches_to_scan {
        let branch_ref = format!("origin/{}", branch);

        // Get files changed by this branch relative to main
        let branch_files =
            match git::get_diff_files_between_refs(&main_ref, &branch_ref, verbose, dry_run) {
                Ok(files) => files,
                Err(_) => continue, // Skip branches that can't be diffed (e.g. orphan)
            };

        // Find intersection (file-level overlap)
        let overlapping_files: Vec<&String> = branch_files
            .iter()
            .filter(|f| local_file_set.contains(f.as_str()))
            .filter(|f| !should_ignore(f, ignore_patterns))
            .collect();

        if overlapping_files.is_empty() {
            continue;
        }

        // Get branch metadata
        let author = git::get_branch_author(branch, verbose, dry_run)
            .unwrap_or_else(|_| "unknown".to_string());
        let commits_ahead =
            git::get_remote_branch_commit_count(branch, main_branch, verbose, dry_run).unwrap_or(0);

        // Build file overlaps with appropriate detail level
        let mut file_overlaps = Vec::new();
        for file in &overlapping_files {
            let overlap_kind = match level {
                RadarLevel::Line => {
                    detect_line_overlap(file, &main_ref, &branch_ref, verbose, dry_run)
                        .unwrap_or_else(|| OverlapKind::SameFile)
                }
                RadarLevel::File => OverlapKind::SameFile,
            };

            file_overlaps.push(FileOverlap {
                file_path: file.to_string(),
                overlap_kind,
            });
        }

        overlaps.push(BranchOverlap {
            branch_name: branch.to_string(),
            author,
            commits_ahead,
            overlapping_files: file_overlaps,
        });
    }

    Ok(RadarResult {
        overlaps,
        branches_scanned,
        local_files_count: local_files.len(),
    })
}

fn detect_line_overlap(
    file: &str,
    main_ref: &str,
    branch_ref: &str,
    verbose: bool,
    dry_run: bool,
) -> Option<OverlapKind> {
    let my_hunks = git::get_local_diff_hunks(file, verbose, dry_run).ok()?;
    let their_hunks =
        git::get_diff_hunks_between_refs(main_ref, branch_ref, file, verbose, dry_run).ok()?;

    if my_hunks.is_empty() || their_hunks.is_empty() {
        return None;
    }

    // Check if any hunk pairs overlap
    let has_overlap = my_hunks
        .iter()
        .any(|mine| their_hunks.iter().any(|theirs| mine.overlaps(theirs)));

    if has_overlap {
        Some(OverlapKind::LineOverlap {
            my_lines: my_hunks,
            their_lines: their_hunks,
        })
    } else {
        // Same file but different line ranges — still report as SameFile
        Some(OverlapKind::SameFile)
    }
}

fn should_ignore(file: &str, patterns: &[String]) -> bool {
    for pattern in patterns {
        if let Ok(glob_pattern) = glob::Pattern::new(pattern) {
            if glob_pattern.matches(file) {
                return true;
            }
        }
    }
    false
}

pub fn handle_radar(verbose: bool, dry_run: bool, config: &Config) -> Result<()> {
    println!("{}", "--- Trunk Status ---".blue());
    let trunk = get_trunk_status(config, verbose, dry_run);
    print_trunk_status(&trunk, &config.main_branch_name);

    println!(
        "\n{}",
        format!("--- Hotspots (Last {} days) ---", CHURN_HOURS / 24).blue()
    );

    if verbose {
        println!("{}", "[RADAR] Fetching latest from origin...".dimmed());
    }
    git::fetch_origin(verbose, dry_run)?;
    let hotspots = get_hotspots(config, verbose, dry_run)?;
    print_hotspots(&hotspots);

    println!("\n{}", "--- Scanning for overlapping work ---".blue());

    if !config.radar.enabled {
        println!(
            "{}",
            "Radar is disabled. Enable it in .tbdflow.yml with:\n\n  radar:\n    enabled: true"
                .yellow()
        );
        return Ok(());
    }

    println!("Fetching latest from origin...");
    let result = scan(config, verbose, dry_run)?;

    if result.local_files_count == 0 {
        println!("{}", "No local changes detected. Nothing to scan.".green());
        return Ok(());
    }

    println!(
        "Scanned {} active branch(es) against {} local file(s).\n",
        result.branches_scanned, result.local_files_count
    );

    if result.overlaps.is_empty() {
        println!(
            "{}",
            format!(
                "No overlaps detected across {} active branch(es). You're clear!",
                result.branches_scanned
            )
            .green()
        );
    } else {
        println!(
            "{}",
            format!(
                "OVERLAP DETECTED with {} active branch(es):\n",
                result.overlaps.len()
            )
            .yellow()
            .bold()
        );

        for overlap in &result.overlaps {
            print_branch_overlap(overlap);
        }

        let clean_count = result.branches_scanned - result.overlaps.len();
        if clean_count > 0 {
            println!(
                "{}",
                format!(
                    "  {} other active branch(es) have no overlap with your changes.",
                    clean_count
                )
                .green()
            );
        }

        println!(
            "\n{}",
            "Hint: Coordinate with the overlapping author(s) before pushing. Consider syncing more frequently."
                .dimmed()
        );
    }

    Ok(())
}

/// Print a single branch overlap in a tree-like format.
fn print_branch_overlap(overlap: &BranchOverlap) {
    println!(
        "  {} (by {}, {} commit(s) ahead)",
        overlap.branch_name.bold(),
        format!("@{}", overlap.author).cyan(),
        overlap.commits_ahead
    );

    let file_count = overlap.overlapping_files.len();
    for (i, file_overlap) in overlap.overlapping_files.iter().enumerate() {
        let connector = if i == file_count - 1 {
            "└──"
        } else {
            "├──"
        };
        let indicator = match &file_overlap.overlap_kind {
            OverlapKind::LineOverlap { .. } => "[!!] LINE OVERLAP".red().bold().to_string(),
            OverlapKind::SameFile => "[!] SAME FILE".yellow().to_string(),
        };

        let detail = match &file_overlap.overlap_kind {
            OverlapKind::LineOverlap {
                my_lines,
                their_lines,
            } => {
                let my_ranges = format_hunk_ranges(my_lines);
                let their_ranges = format_hunk_ranges(their_lines);
                format!("  you: lines {}, them: lines {}", my_ranges, their_ranges)
            }
            OverlapKind::SameFile => String::new(),
        };

        println!(
            "  {} {}    {}{}",
            connector, file_overlap.file_path, indicator, detail
        );
    }
    println!();
}

/// Format hunk ranges into a human-readable string like "14-28, 42-50".
fn format_hunk_ranges(hunks: &[git::HunkRange]) -> String {
    hunks
        .iter()
        .map(|h| {
            if h.line_count <= 1 {
                format!("{}", h.start_line)
            } else {
                format!("{}-{}", h.start_line, h.start_line + h.line_count - 1)
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// Lightweight radar check for the sync command
pub fn quick_scan_for_sync(
    config: &Config,
    verbose: bool,
    dry_run: bool,
) -> Result<Option<String>> {
    if !config.radar.enabled || !config.radar.on_sync {
        return Ok(None);
    }

    let result = scan(config, verbose, dry_run)?;
    if result.overlaps.is_empty() || result.local_files_count == 0 {
        return Ok(None);
    }

    // Build a compact summary
    let mut lines = Vec::new();
    for overlap in &result.overlaps {
        for file_overlap in &overlap.overlapping_files {
            lines.push(format!(
                "  @{} is also modifying {} on {}",
                overlap.author, file_overlap.file_path, overlap.branch_name
            ));
        }
    }

    let summary = format!(
        "Radar: {}\n   Run 'tbdflow radar' for details.",
        lines.join("\n")
    );

    Ok(Some(summary))
}

/// Radar check for the commit workflow.
pub fn check_before_commit(config: &Config, verbose: bool, dry_run: bool) -> Result<bool> {
    if config.radar.on_commit == RadarOnCommit::Off {
        return Ok(true);
    }

    if !config.radar.enabled {
        return Ok(true);
    }

    let result = scan(config, verbose, dry_run)?;
    if result.overlaps.is_empty() || result.local_files_count == 0 {
        return Ok(true);
    }

    // Print warnings
    println!("\n{}", "Radar detected overlapping work:".yellow().bold());
    for overlap in &result.overlaps {
        for file_overlap in &overlap.overlapping_files {
            let indicator = match &file_overlap.overlap_kind {
                OverlapKind::LineOverlap { .. } => "[!!]",
                OverlapKind::SameFile => "[!]",
            };
            println!(
                "  {} {} — @{} on {}",
                indicator, file_overlap.file_path, overlap.author, overlap.branch_name
            );
        }
    }

    match config.radar.on_commit {
        RadarOnCommit::Warn => {
            println!("{}", "  Consider coordinating before pushing.\n".dimmed());
            Ok(true)
        }
        RadarOnCommit::Confirm => {
            let proceed =
                dialoguer::Confirm::with_theme(&dialoguer::theme::ColorfulTheme::default())
                    .with_prompt("Overlapping work detected. Continue with commit?")
                    .default(true)
                    .interact()?;
            Ok(proceed)
        }
        RadarOnCommit::Off => Ok(true),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git::HunkRange;

    #[test]
    fn test_hunk_overlap_detection() {
        let a = HunkRange {
            start_line: 10,
            line_count: 5,
        }; // lines 10-14
        let b = HunkRange {
            start_line: 12,
            line_count: 5,
        }; // lines 12-16
        assert!(a.overlaps(&b));
        assert!(b.overlaps(&a));
    }

    #[test]
    fn test_hunk_no_overlap() {
        let a = HunkRange {
            start_line: 10,
            line_count: 5,
        }; // lines 10-14
        let b = HunkRange {
            start_line: 20,
            line_count: 5,
        }; // lines 20-24
        assert!(!a.overlaps(&b));
        assert!(!b.overlaps(&a));
    }

    #[test]
    fn test_hunk_adjacent_no_overlap() {
        let a = HunkRange {
            start_line: 10,
            line_count: 5,
        }; // lines 10-14
        let b = HunkRange {
            start_line: 15,
            line_count: 5,
        }; // lines 15-19
        assert!(!a.overlaps(&b));
    }

    #[test]
    fn test_hunk_single_line_overlap() {
        let a = HunkRange {
            start_line: 10,
            line_count: 1,
        }; // line 10
        let b = HunkRange {
            start_line: 10,
            line_count: 1,
        }; // line 10
        assert!(a.overlaps(&b));
    }

    #[test]
    fn test_hunk_contained() {
        let a = HunkRange {
            start_line: 5,
            line_count: 20,
        }; // lines 5-24
        let b = HunkRange {
            start_line: 10,
            line_count: 3,
        }; // lines 10-12
        assert!(a.overlaps(&b));
        assert!(b.overlaps(&a));
    }

    #[test]
    fn test_should_ignore_patterns() {
        let patterns = vec![
            "*.lock".to_string(),
            "*.generated.*".to_string(),
            "CHANGELOG.md".to_string(),
        ];

        assert!(should_ignore("Cargo.lock", &patterns));
        assert!(!should_ignore("package-lock.json", &patterns)); // *.lock does not match .json extension
        assert!(should_ignore("CHANGELOG.md", &patterns));
        assert!(should_ignore("api.generated.rs", &patterns));
        assert!(!should_ignore("src/main.rs", &patterns));
        assert!(!should_ignore("README.md", &patterns));
    }

    #[test]
    fn test_format_hunk_ranges() {
        let hunks = vec![
            HunkRange {
                start_line: 14,
                line_count: 15,
            },
            HunkRange {
                start_line: 42,
                line_count: 1,
            },
        ];
        let formatted = format_hunk_ranges(&hunks);
        assert_eq!(formatted, "14-28, 42");
    }

    #[test]
    fn test_format_hunk_ranges_empty() {
        let hunks: Vec<HunkRange> = vec![];
        let formatted = format_hunk_ranges(&hunks);
        assert_eq!(formatted, "");
    }
}