git-loom 0.25.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
use std::borrow::Cow;

use anyhow::Result;
use crossterm::event::{KeyCode, KeyModifiers, MouseButton, MouseEventKind};
use ratatui::{
    Frame,
    layout::{Position, Rect},
    text::{Line, Span},
    widgets::{ListItem, Paragraph},
};

use crate::core::diff::DiffHunk;
use crate::tui::shell::{KeyResult, PaneId, Shell, ShellApp, ShellConfig};
use crate::tui::theme::TuiTheme;
use crate::tui::widgets::common::{pane_block, pane_block_titled};
use crate::tui::widgets::diff_pane::DiffPane;
use crate::tui::widgets::hunk_view::{HunkEvent, HunkView};
use crate::tui::widgets::list_pane::ListPane;
use crate::tui::widgets::popup::{self, HelpSection};

// ── Data model ───────────────────────────────────────────────────────────

/// Where a hunk came from — determines how to apply/reverse on confirm.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum HunkOrigin {
    /// From `git diff --cached` (already staged).
    Staged,
    /// From `git diff` (unstaged working-tree change).
    Unstaged,
    /// From a commit diff (`git diff <oid>^..<oid>`).
    Commit,
}

/// A single hunk with a toggle state and origin.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct HunkEntry {
    pub hunk: DiffHunk,
    pub selected: bool,
    pub origin: HunkOrigin,
}

/// A file and its parsed hunks, with git status information.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct FileEntry {
    pub path: String,
    pub hunks: Vec<HunkEntry>,
    /// Index (staged) status character: ' ', 'A', 'M', 'D', 'R', or '?'.
    pub index_status: char,
    /// Worktree (unstaged) status character: ' ', 'M', 'D', 'R', '?', or '!'.
    pub worktree_status: char,
    /// Whether this file is binary (no hunk-level patching possible).
    pub binary: bool,
}

impl FileEntry {
    /// Whether the file is not in the index at all.
    pub(crate) fn is_untracked(&self) -> bool {
        self.index_status == '?' && self.worktree_status == '?'
    }

    /// Compute the effective status characters based on current hunk selections.
    ///
    /// Returns `(index_char, worktree_char)` reflecting what `git status` would
    /// show if the current selections were applied.
    pub(crate) fn effective_status(&self) -> (char, char) {
        let will_have_staged = self.hunks.iter().any(|h| h.selected);
        let will_have_unstaged = self.hunks.iter().any(|h| !h.selected);

        if self.is_untracked() {
            return if will_have_staged {
                ('A', ' ')
            } else {
                ('?', '?')
            };
        }

        // Staged new file fully deselected → back to untracked.
        if self.index_status == 'A' && !will_have_staged {
            return ('?', '?');
        }

        let eff_index = if will_have_staged {
            match self.index_status {
                'A' | 'M' | 'D' | 'R' => self.index_status,
                _ => match self.worktree_status {
                    'D' => 'D',
                    _ => 'M',
                },
            }
        } else {
            ' '
        };

        let eff_worktree = if will_have_unstaged {
            match self.worktree_status {
                'M' | 'D' => self.worktree_status,
                _ => match self.index_status {
                    'D' => 'D',
                    _ => 'M',
                },
            }
        } else {
            ' '
        };

        (eff_index, eff_worktree)
    }
}

/// Why the selector exited.
pub(crate) enum Verdict {
    Confirm,
    Cancel,
}

/// An entry in the display list for the file tree.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DisplayRow {
    /// Directory header grouping files at indices `dir_start..=dir_end`.
    Directory { dir_start: usize, dir_end: usize },
    /// A single file — index into the `files` vec.
    File(usize),
}

/// All state for the interactive hunk selector. `pub(crate)` so a host TUI
/// can embed it as a [`ShellApp`] later.
pub(crate) struct HunkSelectorApp {
    files: Vec<FileEntry>,
    display_rows: Vec<DisplayRow>,
    /// File-list cursor and view state.
    list: ListPane,
    /// Hunk cursor and diff-pane scroll state.
    hunks: HunkView,
    theme: TuiTheme,
    /// The command the pick is for (`COMMIT`, `FOLD`), titling the file pane
    /// in place of ` Files `; only the TUI, which runs several, sets it.
    action: Option<&'static str>,
    /// The `?` popup's scroll while it is open; it owns the keyboard then.
    help: Option<DiffPane>,
}

/// The `?` popup: everything the status bar leaves out.
const HELP: &[HelpSection] = &[
    (
        "Navigation",
        &[
            (
                "↑/k  ↓/j",
                "previous / next file, or hunk when the diff has focus",
            ),
            ("Tab", "switch pane"),
            ("Ctrl-←/→", "narrow / widen the left pane"),
            ("Mouse", "click a file or a hunk, wheel to scroll"),
        ],
    ),
    (
        "Selection",
        &[
            (
                "Space",
                "toggle the hunk, or every hunk of the file or directory",
            ),
            ("Enter", "confirm the selection"),
            ("Esc / q / Ctrl-C", "cancel, changing nothing"),
            ("?", "this help"),
        ],
    ),
];

// ── Tree helpers ─────────────────────────────────────────────────────────

/// Extract the directory portion of a path, or `""` for root-level files.
fn directory_of(path: &str) -> &str {
    match path.rfind('/') {
        Some(pos) => &path[..pos],
        None => "",
    }
}

/// Extract just the filename from a path.
fn filename_of(path: &str) -> &str {
    match path.rfind('/') {
        Some(pos) => &path[pos + 1..],
        None => path,
    }
}

/// Build the display row list from sorted file entries, grouping files in the
/// same directory under a directory header.
fn build_display_rows(files: &[FileEntry]) -> Vec<DisplayRow> {
    let mut rows = Vec::new();
    let mut i = 0;
    while i < files.len() {
        let dir = directory_of(&files[i].path);
        if dir.is_empty() {
            // Root-level file — no directory header.
            rows.push(DisplayRow::File(i));
            i += 1;
        } else {
            // Directory group — find all consecutive files with the same parent dir.
            let dir_start = i;
            while i < files.len() && directory_of(&files[i].path) == dir {
                i += 1;
            }
            let dir_end = i - 1;
            rows.push(DisplayRow::Directory { dir_start, dir_end });
            for j in dir_start..=dir_end {
                rows.push(DisplayRow::File(j));
            }
        }
    }
    rows
}

// ── App logic ────────────────────────────────────────────────────────────

impl HunkSelectorApp {
    pub(crate) fn new(files: Vec<FileEntry>, theme: TuiTheme) -> Self {
        let display_rows = build_display_rows(&files);
        Self {
            files,
            display_rows,
            list: ListPane::new(0),
            hunks: HunkView::new(),
            theme,
            action: None,
            help: None,
        }
    }

    /// Return the file index if the cursor is on a file row, or `None` on a
    /// directory header.
    fn current_file_index(&self) -> Option<usize> {
        match self.display_rows.get(self.list.cursor()) {
            Some(DisplayRow::File(i)) => Some(*i),
            _ => None,
        }
    }

    // -- rendering ----------------------------------------------------------

    fn render_file_list(&mut self, frame: &mut Frame, area: Rect, focused: bool) {
        let items: Vec<ListItem> = self
            .display_rows
            .iter()
            .map(|row| match row {
                DisplayRow::Directory { dir_start, .. } => {
                    let dir = directory_of(&self.files[*dir_start].path);
                    let text = format!("\u{25BC} {}", dir);
                    ListItem::new(Line::from(Span::styled(text, self.theme.file_normal)))
                }
                DisplayRow::File(idx) => {
                    let f = &self.files[*idx];
                    let (eff_idx, eff_wt) = f.effective_status();
                    let in_dir = !directory_of(&f.path).is_empty();
                    let name = if in_dir {
                        filename_of(&f.path)
                    } else {
                        &f.path
                    };
                    let indent = if in_dir { "  " } else { "" };

                    let is_untracked = eff_idx == '?' && eff_wt == '?';
                    let mut spans: Vec<Span> = if is_untracked {
                        vec![Span::styled(
                            format!("{}??", indent),
                            self.theme.untracked_status,
                        )]
                    } else {
                        vec![
                            Span::raw(indent.to_string()),
                            Span::styled(eff_idx.to_string(), self.theme.staged_status),
                            Span::styled(eff_wt.to_string(), self.theme.unstaged_status),
                        ]
                    };
                    let name_style = if eff_idx == '?' || eff_wt == '?' {
                        self.theme.file_normal
                    } else if eff_idx != ' ' && eff_wt == ' ' {
                        self.theme.file_fully_staged
                    } else if eff_idx != ' ' && eff_wt != ' ' {
                        self.theme.file_partially_staged
                    } else {
                        self.theme.file_normal
                    };
                    spans.push(Span::styled(format!(" {}", name), name_style));
                    ListItem::new(Line::from(spans))
                }
            })
            .collect();

        let block = match self.action {
            // Styled as the status tree tags what a pending command does.
            Some(action) => pane_block_titled(
                Line::from(vec![
                    Span::raw(" "),
                    Span::styled(action, self.theme.pending_tag),
                    Span::raw(" "),
                ]),
                &self.theme,
                focused,
            ),
            None => pane_block(" Files ", &self.theme, focused),
        };
        self.list
            .render(frame, area, items, block, self.theme.file_selected);
    }

    fn render_diff_view(&mut self, frame: &mut Frame, area: Rect, focused: bool) {
        let block = pane_block(" Diff ", &self.theme, focused);

        if self.files.is_empty() {
            let empty = Paragraph::new("No files").block(block);
            frame.render_widget(empty, area);
            return;
        }

        // Directory header selected — show summary.
        let file_idx = match self.current_file_index() {
            Some(i) => i,
            None => {
                if let Some(DisplayRow::Directory { dir_start, dir_end }) =
                    self.display_rows.get(self.list.cursor())
                {
                    let count = dir_end - dir_start + 1;
                    let dir = directory_of(&self.files[*dir_start].path);
                    let text = format!("{} file(s) in {}/", count, dir);
                    let p = Paragraph::new(text).block(block);
                    frame.render_widget(p, area);
                } else {
                    let empty = Paragraph::new("No files").block(block);
                    frame.render_widget(empty, area);
                }
                return;
            }
        };

        let file = &self.files[file_idx];
        let lines = self.hunks.build_lines(file, &self.theme, focused);
        self.hunks.render(frame, area, lines, block);
    }

    // -- navigation -----------------------------------------------------------

    /// Move the file-list cursor; the hunk cursor follows to the new file.
    fn move_file_cursor(&mut self, dir: isize) {
        if self
            .list
            .move_cursor(dir, self.display_rows.len(), |_| true)
        {
            self.hunks.reset();
        }
    }

    fn navigate_up(&mut self, pane: PaneId) {
        if self.display_rows.is_empty() {
            return;
        }
        match pane {
            PaneId::Left => self.move_file_cursor(-1),
            PaneId::Right => {
                let Some(file_idx) = self.current_file_index() else {
                    return;
                };
                if let HunkEvent::WrapToPrevFile = self.hunks.move_up(&self.files[file_idx].hunks) {
                    // Move to the last hunk of the previous file.
                    if let Some(prev) = self.prev_file_row() {
                        self.list.set_cursor(prev);
                        let file_idx = match self.display_rows[prev] {
                            DisplayRow::File(i) => i,
                            _ => unreachable!(),
                        };
                        self.hunks.focus_last(&self.files[file_idx].hunks);
                    }
                }
            }
        }
    }

    fn navigate_down(&mut self, pane: PaneId) {
        if self.display_rows.is_empty() {
            return;
        }
        match pane {
            PaneId::Left => self.move_file_cursor(1),
            PaneId::Right => {
                let Some(file_idx) = self.current_file_index() else {
                    return;
                };
                if let HunkEvent::WrapToNextFile = self.hunks.move_down(&self.files[file_idx].hunks)
                {
                    // Move to the first hunk of the next file.
                    if let Some(next) = self.next_file_row() {
                        self.list.set_cursor(next);
                        self.hunks.reset();
                    }
                }
            }
        }
    }

    fn toggle(&mut self, pane: PaneId) {
        if self.display_rows.is_empty() {
            return;
        }
        match pane {
            PaneId::Left => match self.display_rows[self.list.cursor()] {
                DisplayRow::Directory { dir_start, dir_end } => {
                    // Toggle all hunks in all files under this directory.
                    let any_selected = (dir_start..=dir_end)
                        .any(|i| self.files[i].hunks.iter().any(|h| h.selected));
                    let new_state = !any_selected;
                    for i in dir_start..=dir_end {
                        for h in &mut self.files[i].hunks {
                            h.selected = new_state;
                        }
                    }
                }
                DisplayRow::File(idx) => {
                    // Toggle all hunks in the current file.
                    let any_selected = self.files[idx].hunks.iter().any(|h| h.selected);
                    let new_state = !any_selected;
                    for h in &mut self.files[idx].hunks {
                        h.selected = new_state;
                    }
                }
            },
            PaneId::Right => {
                if let Some(file_idx) = self.current_file_index() {
                    self.hunks.toggle_focused(&mut self.files[file_idx].hunks);
                }
            }
        }
    }

    /// Find the previous File row before the cursor, skipping directory headers.
    fn prev_file_row(&self) -> Option<usize> {
        let mut pos = self.list.cursor();
        while pos > 0 {
            pos -= 1;
            if matches!(self.display_rows[pos], DisplayRow::File(_)) {
                return Some(pos);
            }
        }
        None
    }

    /// Find the next File row after the cursor, skipping directory headers.
    fn next_file_row(&self) -> Option<usize> {
        let mut pos = self.list.cursor();
        while pos + 1 < self.display_rows.len() {
            pos += 1;
            if matches!(self.display_rows[pos], DisplayRow::File(_)) {
                return Some(pos);
            }
        }
        None
    }
}

// ── Shell integration ────────────────────────────────────────────────────

impl ShellApp for HunkSelectorApp {
    type Exit = Verdict;

    fn config(&self) -> ShellConfig {
        // Two panes: ~30% file list, ~70% diff view.
        ShellConfig { split: (30, 70) }
    }

    fn theme(&self) -> &TuiTheme {
        &self.theme
    }

    fn quit_exit(&mut self) -> Verdict {
        Verdict::Cancel
    }

    fn handle_key(
        &mut self,
        focused: PaneId,
        code: KeyCode,
        modifiers: KeyModifiers,
    ) -> KeyResult<Verdict> {
        // The help is modal, so the shell forwards Ctrl-C here too.
        if let Some(mut scroll) = self.help.take() {
            match code {
                KeyCode::Esc | KeyCode::Char('q' | '?') => {}
                KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
                    return KeyResult::Exit(Verdict::Cancel);
                }
                KeyCode::Up | KeyCode::Char('k') => {
                    scroll.scroll_by(-1);
                    self.help = Some(scroll);
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    scroll.scroll_by(1);
                    self.help = Some(scroll);
                }
                _ => self.help = Some(scroll),
            }
            return KeyResult::Handled;
        }
        match code {
            KeyCode::Esc => KeyResult::Exit(Verdict::Cancel),
            // Ctrl-C never reaches here — the shell intercepts it first.
            KeyCode::Enter => KeyResult::Exit(Verdict::Confirm),
            KeyCode::Char('?') => {
                self.help = Some(DiffPane::new());
                KeyResult::Handled
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.navigate_up(focused);
                KeyResult::Handled
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.navigate_down(focused);
                KeyResult::Handled
            }
            KeyCode::Char(' ') => {
                self.toggle(focused);
                KeyResult::Handled
            }
            _ => KeyResult::Handled,
        }
    }

    fn handle_mouse(&mut self, pane: PaneId, kind: MouseEventKind, pos: Position, area: Rect) {
        match pane {
            PaneId::Left => match kind {
                MouseEventKind::Down(MouseButton::Left) => {
                    let Some(clicked) = self.list.hit_test(area, pos.y) else {
                        return;
                    };
                    if clicked < self.display_rows.len() {
                        self.list.set_cursor(clicked);
                        self.hunks.reset();
                    }
                }
                MouseEventKind::ScrollUp => self.move_file_cursor(-1),
                MouseEventKind::ScrollDown => self.move_file_cursor(1),
                _ => {}
            },
            PaneId::Right => match kind {
                MouseEventKind::Down(MouseButton::Left) => {
                    let Some(file_idx) = self.current_file_index() else {
                        return;
                    };
                    // Inner area: subtract 1-row border top, then account for scroll.
                    let inner_top = area.y + 1;
                    let inner_height = area.height.saturating_sub(2);
                    if pos.y < inner_top || pos.y >= inner_top + inner_height {
                        return;
                    }
                    let clicked_line = (pos.y - inner_top) as usize + self.hunks.scroll() as usize;
                    self.hunks
                        .click(&mut self.files[file_idx].hunks, clicked_line);
                }
                MouseEventKind::ScrollUp => self.hunks.scroll_by(-3),
                MouseEventKind::ScrollDown => self.hunks.scroll_by(3),
                _ => {}
            },
        }
    }

    fn render_pane(&mut self, frame: &mut Frame, pane: PaneId, area: Rect, focused: bool) {
        match pane {
            PaneId::Left => self.render_file_list(frame, area, focused),
            PaneId::Right => self.render_diff_view(frame, area, focused),
        }
    }

    fn status_hints(&self, _focused: PaneId) -> Vec<Cow<'static, str>> {
        vec![
            "Toggle: space".into(),
            "Confirm: Enter".into(),
            "Help: ?".into(),
            "Cancel: Esc".into(),
        ]
    }

    fn modal_active(&self) -> bool {
        self.help.is_some()
    }

    fn render_overlay(&mut self, frame: &mut Frame, area: Rect) {
        if let Some(scroll) = &mut self.help {
            popup::render_help(frame, area, HELP, scroll, &self.theme);
        }
    }
}

// ── Public entry point ───────────────────────────────────────────────────

/// Run the interactive hunk selector TUI.
///
/// Returns `Ok(Some(files))` with updated selection state if the user confirms,
/// or `Ok(None)` if cancelled / empty input.
pub fn run_hunk_selector(files: Vec<FileEntry>, theme: TuiTheme) -> Result<Option<Vec<FileEntry>>> {
    refuse_in_agent_mode()?;
    if files.is_empty() {
        return Ok(None);
    }

    let (app, verdict) = Shell::new(HunkSelectorApp::new(files, theme)).run()?;
    Ok(confirmed(app, verdict))
}

/// Backstop for agent mode: every `-p` path answers with a hunk listing before
/// it gets here, and no call path may open a full-screen TUI either. Every
/// entry point goes through this, nested ones included.
fn refuse_in_agent_mode() -> Result<()> {
    if crate::core::agent_mode::enabled() {
        anyhow::bail!(
            "the hunk picker is a full-screen UI and cannot run in agent mode\n\
             This path should have answered with a hunk listing (spec 019)"
        );
    }
    Ok(())
}

/// The selector inside a host TUI: it draws on the terminal the host already
/// set up, so the screen never switches between the two. `action` names the
/// command the pick is for.
pub(crate) fn run_hunk_selector_nested(
    files: Vec<FileEntry>,
    theme: TuiTheme,
    action: &'static str,
    terminal: &mut ratatui::DefaultTerminal,
) -> Result<Option<Vec<FileEntry>>> {
    refuse_in_agent_mode()?;
    if files.is_empty() {
        return Ok(None);
    }
    let mut app = HunkSelectorApp::new(files, theme);
    app.action = Some(action);
    let (app, verdict) = Shell::new(app).run_nested(terminal)?;
    Ok(confirmed(app, verdict))
}

fn confirmed(app: HunkSelectorApp, verdict: Verdict) -> Option<Vec<FileEntry>> {
    match verdict {
        Verdict::Confirm => Some(app.files),
        Verdict::Cancel => None,
    }
}

/// Fixtures shared with the shell tests.
#[cfg(test)]
pub(crate) mod test_support {
    use super::*;
    use crate::core::graph::Theme;

    /// A selector over one single-hunk file, for render-level tests.
    pub(crate) fn sample_app() -> HunkSelectorApp {
        let files = vec![FileEntry {
            path: "main.rs".to_string(),
            hunks: vec![HunkEntry {
                hunk: DiffHunk {
                    text: "@@ -1,1 +1,1 @@\n-a\n+b\n".to_string(),
                    modified_lines: vec![],
                },
                selected: false,
                origin: HunkOrigin::Unstaged,
            }],
            index_status: ' ',
            worktree_status: 'M',
            binary: false,
        }];
        HunkSelectorApp::new(files, TuiTheme::from_graph_theme(&Theme::dark()))
    }
}

#[cfg(test)]
#[path = "hunk_selector_test.rs"]
mod tests;