brain: Fix hunk un-accept

2ec50517ad662b074fe46eb0abcd592a959e1584
Alexis Sellier committed ago 1 parent b4dbf0bd
crates/brain/src/backend.rs +29 -9
695 695
        let blob = self.repository.write_blob(text.as_bytes())?;
696 696
        self.repository.update_ref(&self.comments_ref, blob)?;
697 697
        Ok(())
698 698
    }
699 699
700 -
    /// Applies one selected hunk patch to the hidden tree and persists it.
700 +
    /// Applies selected hunk patches to the hidden tree and persists them.
701 701
    ///
702 702
    /// The hidden tree is the source of truth for accepted review content. Each
703 -
    /// accepted hunk produces a new synthetic commit whose parent remains the
704 -
    /// exact review base, so later loads can reject state from a different base
705 -
    /// instead of trying to reinterpret it.
706 -
    pub fn apply_patch(&mut self, patch: &str) -> Result<(), Error> {
707 -
        let tree = self.repository.apply_patch_to_tree(self.commit, patch)?;
703 +
    /// acceptance update produces a new synthetic commit whose parent remains
704 +
    /// the exact review base, so later loads can reject state from a different
705 +
    /// base instead of trying to reinterpret it.
706 +
    pub fn apply_patches<'a>(
707 +
        &mut self,
708 +
        patches: impl IntoIterator<Item = &'a str>,
709 +
    ) -> Result<(), Error> {
710 +
        let mut tree = self.repository.tree_id(self.commit)?;
711 +
        for patch in patches {
712 +
            tree = self.repository.apply_patch_to_tree(tree, patch)?;
713 +
        }
708 714
        self.advance_to_tree(tree)
709 715
    }
710 716
711 -
    /// Applies the reverse of one selected hunk patch to the hidden tree.
712 -
    pub fn reverse_patch(&mut self, patch: &str) -> Result<(), Error> {
713 -
        let tree = self.repository.reverse_patch_to_tree(self.commit, patch)?;
717 +
    /// Rebuilds the hidden tree from patches that should remain accepted.
718 +
    ///
719 +
    /// Patches that depended on a removed patch are omitted when they no
720 +
    /// longer apply to the rebuilt tree. Reconciliation then marks those hunks
721 +
    /// unaccepted as well.
722 +
    pub fn replace_patches<'a>(
723 +
        &mut self,
724 +
        patches: impl IntoIterator<Item = &'a str>,
725 +
    ) -> Result<(), Error> {
726 +
        let mut tree = self.repository.tree_id(self.base)?;
727 +
        for patch in patches {
728 +
            match self.repository.apply_patch_to_tree(tree, patch) {
729 +
                Ok(next) => tree = next,
730 +
                Err(rustik_repo::RepoError::Git(_)) => continue,
731 +
                Err(error) => return Err(error.into()),
732 +
            }
733 +
        }
714 734
        self.advance_to_tree(tree)
715 735
    }
716 736
717 737
    /// Carries matching accepted patches into this review state.
718 738
    fn rebase_accepted_patches(
f +0 -0
crates/brain/src/session.rs +61 -18
1 1
//! Terminal session loop for the `brain` review TUI.
2 2
3 +
use std::collections::BTreeSet;
3 4
use std::io;
4 5
use std::mem;
5 6
use std::sync::mpsc::{self, Receiver, Sender};
6 7
7 8
use rustik_diff::{
8 -
    ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffViewer, FileDiff,
9 -
    FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ReviewProgress, ViewChange,
10 -
    spawn_highlighter,
9 +
    ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffViewer, Encode as _,
10 +
    FileDiff, FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ReviewProgress,
11 +
    ViewChange, spawn_highlighter,
11 12
};
12 13
use rustik_repo::DiffStat;
13 14
use rustik_tui::{Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, Terminal};
14 15
use rustik_tui_termion as tui_termion;
15 16
126 127
        comments,
127 128
        events_tx,
128 129
        generation: 0,
129 130
        highlighter: None,
130 131
        context_fetch: ContextFetch::default(),
132 +
        error: None,
131 133
    };
132 134
    session.current()?;
133 135
    session.reconcile_reviews()?;
134 136
    session.activate()?;
135 137
    session.focus_initial_hunk(viewer_area(session.terminal.area()))?;
139 141
        let mut redraw = false;
140 142
        let mut next = Some(event);
141 143
        // Drain queued events before repainting so bursts coalesce into one
142 144
        // frame.
143 145
        while let Some(event) = next {
144 -
            match session.update(event)? {
145 -
                Update::Continue => {}
146 -
                Update::Redraw => redraw = true,
147 -
                Update::Quit => return Ok(()),
146 +
            match session.update(event) {
147 +
                Ok(Update::Continue) => {}
148 +
                Ok(Update::Redraw) => redraw = true,
149 +
                Ok(Update::Quit) => return Ok(()),
150 +
                Err(error) => {
151 +
                    session.error = Some(error.to_string().replace('\n', " · "));
152 +
                    redraw = true;
153 +
                }
148 154
            }
149 155
            next = events_rx.try_recv().ok();
150 156
        }
151 157
        if redraw {
152 158
            session.redraw()?;
185 191
    generation: u64,
186 192
    /// Highlighter for the current commit, respawned on each switch.
187 193
    highlighter: Option<Highlighter>,
188 194
    /// Whether a context refetch is in flight.
189 195
    context_fetch: ContextFetch,
196 +
    /// Most recent recoverable session error shown in the status bar.
197 +
    error: Option<String>,
190 198
}
191 199
192 200
impl Session<'_> {
193 201
    /// Returns the current commit's diff state, decoding it on first access.
194 202
    fn current(&mut self) -> Result<&mut CommitReview, Error> {
221 229
    /// output is tagged with a generation, letting stale highlighter results
222 230
    /// from a previous commit be ignored after a commit switch.
223 231
    fn update(&mut self, event: TerminalEvent) -> Result<Update, Error> {
224 232
        match event {
225 233
            TerminalEvent::Input(event) => {
234 +
                self.error = None;
226 235
                let event = event?;
227 236
                let resize = if matches!(event, Event::Resize(_)) {
228 237
                    Resize::Changed
229 238
                } else {
230 239
                    Resize::Stable
410 419
        let Some(patch) = loaded.hunk_patches.get(&hunk).cloned() else {
411 420
            return Ok(());
412 421
        };
413 422
        let accepted = loaded.review.is_accepted(hunk);
414 423
        if accepted {
415 -
            self.brain.reverse_patch(&patch)?;
424 +
            self.reject_hunks(BTreeSet::from([(self.current, hunk)]))?;
416 425
        } else {
417 -
            self.brain.apply_patch(&patch)?;
426 +
            self.brain.apply_patches([patch.as_str()])?;
418 427
        }
419 428
        self.reconcile_reviews()?;
420 429
        if !accepted {
421 430
            self.current()?.viewer.apply(DiffAction::NextHunk, area);
422 431
        }
434 443
        let Some(file) = loaded.files.iter().find(|candidate| candidate.id == file) else {
435 444
            return Ok(());
436 445
        };
437 446
        let hunk_ids = file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>();
438 447
        let accepted = loaded.review.accepts_all(hunk_ids.iter().copied());
439 -
        let mut patches = hunk_ids
440 -
            .into_iter()
448 +
        let patches = hunk_ids
449 +
            .iter()
450 +
            .copied()
441 451
            .filter(|hunk| loaded.review.is_accepted(*hunk) == accepted)
442 452
            .filter_map(|hunk| loaded.hunk_patches.get(&hunk).cloned())
443 453
            .collect::<Vec<_>>();
444 454
        if accepted {
445 -
            patches.reverse();
446 -
            for patch in patches {
447 -
                self.brain.reverse_patch(&patch)?;
448 -
            }
455 +
            let rejected = hunk_ids
456 +
                .into_iter()
457 +
                .map(|hunk| (self.current, hunk))
458 +
                .collect();
459 +
            self.reject_hunks(rejected)?;
449 460
        } else {
450 -
            for patch in patches {
451 -
                self.brain.apply_patch(&patch)?;
452 -
            }
461 +
            self.brain
462 +
                .apply_patches(patches.iter().map(String::as_str))?;
453 463
        }
454 464
        self.reconcile_reviews()?;
455 465
        Ok(())
456 466
    }
457 467
468 +
    /// Rebuilds accepted state without the selected hunks.
469 +
    fn reject_hunks(
470 +
        &mut self,
471 +
        rejected: BTreeSet<(usize, rustik_diff::HunkId)>,
472 +
    ) -> Result<(), Error> {
473 +
        for index in 0..self.commits.len() {
474 +
            self.load(index)?;
475 +
        }
476 +
        self.reconcile_reviews()?;
477 +
        let mut patches = Vec::new();
478 +
        for (index, slot) in self.commits.iter().enumerate() {
479 +
            let Some(loaded) = &slot.loaded else {
480 +
                continue;
481 +
            };
482 +
            for file in &loaded.files {
483 +
                let hunks = file
484 +
                    .hunks
485 +
                    .iter()
486 +
                    .filter(|hunk| {
487 +
                        loaded.review.is_accepted(hunk.id) && !rejected.contains(&(index, hunk.id))
488 +
                    })
489 +
                    .cloned()
490 +
                    .collect::<Vec<_>>();
491 +
                if !hunks.is_empty() {
492 +
                    patches.push(DiffDocument::for_hunks(file, hunks).to_unified_string()?);
493 +
                }
494 +
            }
495 +
        }
496 +
        self.brain
497 +
            .replace_patches(patches.iter().map(String::as_str))
498 +
    }
499 +
458 500
    /// Opens the hunk view for the focused hunk to author a comment.
459 501
    fn enter_hunk_view(&mut self, area: Rect) -> Result<(), Error> {
460 502
        if !matches!(
461 503
            self.current()?.viewer.state().focus,
462 504
            Some(DiffFocus::Hunk(_))
970 1012
                summary: slot.commit.summary.clone(),
971 1013
                progress,
972 1014
                stats,
973 1015
                palette: self.options.diff_palette,
974 1016
                visibility: self.visibility,
1017 +
                error: self.error.clone(),
975 1018
            },
976 1019
            actions: self.action_context(),
977 1020
        }
978 1021
    }
979 1022
crates/brain/src/session/status.rs +36 -0
118 118
    pub(super) stats: DiffStat,
119 119
    /// Diff palette used for stat and review colors.
120 120
    pub(super) palette: DiffPalette,
121 121
    /// Session-wide accepted-hunk visibility.
122 122
    pub(super) visibility: Visibility,
123 +
    /// Most recent recoverable session error.
124 +
    pub(super) error: Option<String>,
123 125
}
124 126
125 127
impl Widget for Status {
126 128
    fn size(&self, parent: Constraint) -> Size {
127 129
        Size::new(parent.max.cols, STATUS_ROWS).constrain(parent)
142 144
        Line::new(Label::space().bg(FOOTER_BG)).padded(cols)
143 145
    }
144 146
145 147
    /// Returns the bottom status row content.
146 148
    fn bar(&self, cols: usize) -> HStack<'_> {
149 +
        if let Some(error) = &self.error {
150 +
            return HStack::default().child(
151 +
                Line::new(Label::new(error).fg(self.palette.negative_fg))
152 +
                    .truncated(cols, FOOTER_ELLIPSIS),
153 +
            );
154 +
        }
147 155
        let right = self.right_status();
148 156
        let left_width = cols.saturating_sub(right.width()).saturating_sub(1);
149 157
150 158
        HStack::default()
151 159
            .child(self.left_status().truncated(left_width, FOOTER_ELLIPSIS))
460 468
                .iter()
461 469
                .any(|(_, label)| *label == "save")
462 470
        );
463 471
    }
464 472
473 +
    #[test]
474 +
    fn status_renders_recoverable_error() {
475 +
        let palette = DiffPalette::default();
476 +
        let mut status = Status {
477 +
            mode: "commit",
478 +
            short: "1234567".to_owned(),
479 +
            summary: "summary".to_owned(),
480 +
            progress: ReviewProgress::default(),
481 +
            stats: DiffStat::default(),
482 +
            palette,
483 +
            visibility: Visibility::default(),
484 +
            error: Some("patch does not apply".to_owned()),
485 +
        };
486 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 40, 1));
487 +
488 +
        status.render(buffer.area(), &mut buffer);
489 +
490 +
        let text = (0..buffer.area().cols)
491 +
            .filter_map(|x| buffer.get(x, 0))
492 +
            .map(|cell| cell.glyph())
493 +
            .collect::<String>();
494 +
        assert!(text.contains("patch does not apply"));
495 +
        assert_eq!(
496 +
            buffer.get(0, 0).unwrap().style().fg_color(),
497 +
            palette.negative_fg
498 +
        );
499 +
    }
500 +
465 501
    #[test]
466 502
    fn comment_card_lines_render_a_bordered_comment_card() {
467 503
        let comment = Comment {
468 504
            id: 1.into(),
469 505
            author: "alice".to_owned(),
crates/repo/src/git.rs +46 -74
27 27
/// Maximum bytes read from a file head for shebang-style inference.
28 28
const HEAD_BYTES: usize = 64;
29 29
/// Pathspec separator that ends Git's option list.
30 30
const PATHSPEC_SEPARATOR: &str = "--";
31 31
32 -
/// Direction used when applying a patch to an isolated tree.
33 -
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34 -
enum PatchDirection {
35 -
    /// Apply the patch as written.
36 -
    Forward,
37 -
    /// Apply the patch in reverse.
38 -
    Reverse,
39 -
}
40 -
41 32
/// Git repository command context.
42 33
#[derive(Clone, Debug)]
43 34
pub struct Repository {
44 35
    /// Working directory for worktree-aware invocations.
45 36
    cwd: PathBuf,
608 599
    ///
609 600
    /// The temporary index is seeded from `base`, patched with
610 601
    /// `git apply --cached`, then written with `git write-tree`. This keeps
611 602
    /// acceptance updates isolated from the user's working tree and real index.
612 603
    fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError> {
613 -
        self.apply_patch_to_tree_with_direction(base, patch, PatchDirection::Forward)
614 -
    }
604 +
        if patch.trim().is_empty() {
605 +
            return self.tree_id(base);
606 +
        }
607 +
        let index = TempIndex::new()?;
608 +
        let index_path = index.path();
609 +
        let base = base.to_string();
615 610
616 -
    /// Applies the reverse of a Git-format patch to a temporary index.
617 -
    fn reverse_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError> {
618 -
        self.apply_patch_to_tree_with_direction(base, patch, PatchDirection::Reverse)
611 +
        // `read-tree` initializes the temporary index to the exact tree being
612 +
        // updated; subsequent Git commands use only `GIT_INDEX_FILE`.
613 +
        let output = self.run(
614 +
            "read-tree",
615 +
            &[&base],
616 +
            Opts {
617 +
                index: Some(index_path),
618 +
                ..Opts::default()
619 +
            },
620 +
        )?;
621 +
        if !output.status.success() {
622 +
            return Err(RepoError::git(&output));
623 +
        }
624 +
        // `--recount` lets single-hunk patches keep working after context
625 +
        // filtering changes hunk line counts.
626 +
        let output = self.run(
627 +
            "apply",
628 +
            &["--cached", "--recount", "--whitespace=nowarn", "--binary"],
629 +
            Opts {
630 +
                index: Some(index_path),
631 +
                stdin: Some(patch.as_bytes()),
632 +
                ..Opts::default()
633 +
            },
634 +
        )?;
635 +
        if !output.status.success() {
636 +
            return Err(RepoError::git(&output));
637 +
        }
638 +
        let output = self.run(
639 +
            "write-tree",
640 +
            &[],
641 +
            Opts {
642 +
                index: Some(index_path),
643 +
                ..Opts::default()
644 +
            },
645 +
        )?;
646 +
        if !output.status.success() {
647 +
            return Err(RepoError::git(&output));
648 +
        }
649 +
        Oid::try_from(output.stdout.as_slice())
650 +
            .map_err(|_| RepoError::Git("invalid oid from write-tree".to_owned()))
619 651
    }
620 652
621 653
    /// Creates a commit with `tree` and `parent`.
622 654
    fn commit(
623 655
        &self,
690 722
            .unwrap_or_else(|| name.trim())
691 723
            .to_owned();
692 724
693 725
        Ok((!name.is_empty()).then_some(name))
694 726
    }
695 -
696 -
    /// Applies or reverses a Git-format patch against an isolated tree.
697 -
    fn apply_patch_to_tree_with_direction(
698 -
        &self,
699 -
        base: Oid,
700 -
        patch: &str,
701 -
        direction: PatchDirection,
702 -
    ) -> Result<Oid, RepoError> {
703 -
        if patch.trim().is_empty() {
704 -
            return self.tree_id(base);
705 -
        }
706 -
        let index = TempIndex::new()?;
707 -
        let index_path = index.path();
708 -
        let base = base.to_string();
709 -
710 -
        // `read-tree` initializes the temporary index to the exact tree being
711 -
        // updated; subsequent Git commands use only `GIT_INDEX_FILE`.
712 -
        let output = self.run(
713 -
            "read-tree",
714 -
            &[&base],
715 -
            Opts {
716 -
                index: Some(index_path),
717 -
                ..Opts::default()
718 -
            },
719 -
        )?;
720 -
        if !output.status.success() {
721 -
            return Err(RepoError::git(&output));
722 -
        }
723 -
        // `--recount` lets single-hunk patches keep working after context
724 -
        // filtering changes hunk line counts.
725 -
        let mut args = vec!["--cached", "--recount", "--whitespace=nowarn", "--binary"];
726 -
        if direction == PatchDirection::Reverse {
727 -
            args.push("--reverse");
728 -
        }
729 -
        let output = self.run(
730 -
            "apply",
731 -
            &args,
732 -
            Opts {
733 -
                index: Some(index_path),
734 -
                stdin: Some(patch.as_bytes()),
735 -
                ..Opts::default()
736 -
            },
737 -
        )?;
738 -
        if !output.status.success() {
739 -
            return Err(RepoError::git(&output));
740 -
        }
741 -
        let output = self.run(
742 -
            "write-tree",
743 -
            &[],
744 -
            Opts {
745 -
                index: Some(index_path),
746 -
                ..Opts::default()
747 -
            },
748 -
        )?;
749 -
        if !output.status.success() {
750 -
            return Err(RepoError::git(&output));
751 -
        }
752 -
        Oid::try_from(output.stdout.as_slice())
753 -
            .map_err(|_| RepoError::Git("invalid oid from write-tree".to_owned()))
754 -
    }
755 727
}
756 728
757 729
impl DiffRepository for Repository {
758 730
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError> {
759 731
        let context = OsString::from(format!("-U{context_lines}"));
crates/repo/src/lib.rs +0 -3
236 236
    fn write_blob(&self, bytes: &[u8]) -> Result<Oid, RepoError>;
237 237
238 238
    /// Applies a Git-format patch to a temporary index and returns its tree id.
239 239
    fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError>;
240 240
241 -
    /// Applies the reverse of a Git-format patch to a temporary index.
242 -
    fn reverse_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError>;
243 -
244 241
    /// Creates a commit with `tree` and `parent`.
245 242
    fn commit(
246 243
        &self,
247 244
        tree: Oid,
248 245
        parent: Oid,