brain: Preserve split added-file projections

8c3092aa158f2627a78a893ca1942cae9fac490e
Rebuild accepted content from grouped file patches so split hunks of a
new file retain one creation header and project every accepted region.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent f69f4172
crates/brain/src/backend.rs +41 -11
11 11
use std::ffi::OsString;
12 12
use std::path::Path;
13 13
use std::str::FromStr as _;
14 14
15 15
use rustik_diff::{
16 -
    CommitHeader, Decode as _, DiffDocument, Encode as _, FileDiff, Hunk, HunkId, ReviewProgress,
16 +
    CommitHeader, Decode as _, DiffDocument, DiffLineKind, Encode as _, FileDiff, FileKind, Hunk,
17 +
    HunkHeader, HunkId, ReviewProgress,
17 18
};
18 19
use rustik_repo::{
19 20
    AheadBehind, CommitTime, DiffStat, MergeStatus, Oid, PatchId, ReadRepository, Rev,
20 21
    WriteRepository,
21 22
    git::{
212 213
    pub fn new(file: &FileDiff, hunks: Vec<Hunk>) -> Result<Self, Error> {
213 214
        let individual = hunks
214 215
            .iter()
215 216
            .map(|hunk| DiffDocument::for_hunks(file, [hunk.clone()]).to_unified_string())
216 217
            .collect::<Result<Vec<_>, _>>()?;
218 +
        let combined = if file.header.kind == FileKind::Added && hunks.len() > 1 {
219 +
            let mut hunks = hunks.into_iter();
220 +
            let Some(mut combined) = hunks.next() else {
221 +
                return Err(Error::Git("added-file projection has no hunks".to_owned()));
222 +
            };
223 +
            for hunk in hunks {
224 +
                combined.lines.extend(hunk.lines);
225 +
            }
226 +
            for line in &mut combined.lines {
227 +
                if line.kind == DiffLineKind::Context {
228 +
                    line.kind = DiffLineKind::Addition;
229 +
                }
230 +
            }
231 +
            combined.header = HunkHeader {
232 +
                old_line_no: 0,
233 +
                old_size: 0,
234 +
                new_line_no: 1,
235 +
                new_size: combined.lines.iter().map(|line| line.kind.new_len()).sum(),
236 +
                text: String::new(),
237 +
            };
238 +
            vec![combined]
239 +
        } else {
240 +
            hunks
241 +
        };
217 242
218 243
        Ok(Self {
219 -
            combined: DiffDocument::for_hunks(file, hunks).to_unified_string()?,
244 +
            combined: DiffDocument::for_hunks(file, combined).to_unified_string()?,
220 245
            hunks: individual,
221 246
        })
222 247
    }
223 248
}
224 249
1145 1170
    }
1146 1171
1147 1172
    /// Marks hunks accepted and updates the derived tree.
1148 1173
    pub fn accept(
1149 1174
        &mut self,
1150 -
        hunks: impl IntoIterator<Item = (AcceptedHunk, String)>,
1175 +
        hunks: impl IntoIterator<Item = AcceptedHunk>,
1176 +
        files: impl IntoIterator<Item = FilePatches>,
1151 1177
    ) -> Result<(), Error> {
1152 -
        let mut tree = self.repository.tree_id(self.commit)?;
1153 1178
        let mut accepted = self.accepted.clone();
1154 -
        for (identity, patch) in hunks {
1155 -
            accepted.insert(identity);
1156 -
            tree = self.project(tree, &patch)?;
1179 +
        accepted.extend(hunks);
1180 +
        let mut tree = self.repository.tree_id(self.base)?;
1181 +
        for file in files {
1182 +
            tree = self.project_file(tree, &file)?;
1157 1183
        }
1158 1184
        self.persist(tree, accepted)
1159 1185
    }
1160 1186
1161 1187
    /// Marks exact hunks unaccepted and rebuilds the derived tree.
1556 1582
                .current_dir(&self.path)
1557 1583
                .status()
1558 1584
                .unwrap();
1559 1585
            assert!(status.success());
1560 1586
        }
1587 +
1588 +
        /// Returns the fixture working tree.
1589 +
        fn path(&self) -> &std::path::Path {
1590 +
            &self.path
1591 +
        }
1561 1592
    }
1562 1593
1563 1594
    impl Drop for TestRepository {
1564 1595
        fn drop(&mut self) {
1565 1596
            fs::remove_dir_all(&self.path).unwrap();
1587 1618
            .hunk_identities(&first_document, first.id)
1588 1619
            .unwrap()
1589 1620
            .into_values()
1590 1621
            .next()
1591 1622
            .unwrap();
1592 -
        let first_patch =
1593 -
            hunk_identity_patch(&first_document.files[0], &first_document.files[0].hunks[0])
1594 -
                .unwrap();
1595 -
        brain.accept([(first_identity, first_patch)]).unwrap();
1623 +
        let first_file = &first_document.files[0];
1624 +
        let first_patches = FilePatches::new(first_file, first_file.hunks.clone()).unwrap();
1625 +
        brain.accept([first_identity], [first_patches]).unwrap();
1596 1626
1597 1627
        repository.git(&["commit", "-q", "--amend", "-m", "T2"]);
1598 1628
        let second = backend.commits().unwrap().pop().unwrap();
1599 1629
        let second_document = backend.diff_document(second.id).unwrap().split_hunks();
1600 1630
        let second_identity = brain
f +0 -0
new.rs +0 -0
image.png +0 -0
new.txt +0 -0
crates/brain/src/session.rs +52 -19
514 514
            // No hunk is focused yet: move focus to the first hunk so the next
515 515
            // toggle has an unambiguous target.
516 516
            loaded.viewer.apply(DiffAction::NextHunk, area);
517 517
            return Ok(());
518 518
        };
519 -
        let Some(patch) = loaded.hunk_patches.get(&hunk).cloned() else {
519 +
        if !loaded.identities.contains_key(&hunk) {
520 520
            return Ok(());
521 -
        };
522 -
        let Some(identity) = loaded.identities.get(&hunk).cloned() else {
523 -
            return Ok(());
524 -
        };
521 +
        }
525 522
        let accepted = loaded.review.is_accepted(hunk);
526 523
        if accepted {
527 524
            self.reject_hunks(BTreeSet::from([(self.current, hunk)]))?;
528 525
            self.accepted_hunks
529 526
                .retain(|accepted| *accepted != (self.current, hunk));
530 527
        } else {
531 -
            self.brain.accept([(identity, patch)])?;
528 +
            self.accept_hunks(BTreeSet::from([(self.current, hunk)]))?;
532 529
            self.accepted_hunks.push((self.current, hunk));
533 530
        }
534 531
        self.reconcile_reviews()?;
535 532
        if !accepted && !self.show_accepted {
536 533
            self.current()?.viewer.apply(DiffAction::NextHunk, area);
567 564
        else {
568 565
            return Ok(());
569 566
        };
570 567
        let hunk_ids = file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>();
571 568
        let accepted = loaded.review.accepts_all(hunk_ids.iter().copied());
572 -
        let mut newly_accepted = Vec::new();
573 569
        let hunks = hunk_ids
574 570
            .iter()
575 571
            .copied()
576 572
            .filter(|hunk| loaded.review.is_accepted(*hunk) == accepted)
577 -
            .filter_map(|hunk| {
578 -
                let identity = loaded.identities.get(&hunk)?.clone();
579 -
                let patch = loaded.hunk_patches.get(&hunk)?.clone();
580 -
                if !accepted {
581 -
                    newly_accepted.push((current, hunk));
582 -
                }
583 -
                Some((identity, patch))
584 -
            })
585 -
            .collect::<Vec<_>>();
573 +
            .filter(|hunk| loaded.identities.contains_key(hunk))
574 +
            .map(|hunk| (current, hunk))
575 +
            .collect::<BTreeSet<_>>();
586 576
        if accepted {
587 577
            let rejected = hunk_ids
588 578
                .into_iter()
589 -
                .map(|hunk| (self.current, hunk))
579 +
                .map(|hunk| (current, hunk))
590 580
                .collect::<BTreeSet<_>>();
591 581
            self.reject_hunks(rejected.clone())?;
592 582
            self.accepted_hunks
593 583
                .retain(|accepted| !rejected.contains(accepted));
594 584
        } else {
595 -
            self.brain.accept(hunks)?;
596 -
            self.accepted_hunks.extend(newly_accepted);
585 +
            self.accept_hunks(hunks.clone())?;
586 +
            self.accepted_hunks.extend(hunks);
597 587
        }
598 588
        self.reconcile_reviews()?;
599 589
        Ok(())
600 590
    }
601 591
592 +
    /// Rebuilds accepted state including the selected hunks.
593 +
    fn accept_hunks(
594 +
        &mut self,
595 +
        newly_accepted: BTreeSet<(usize, rustik_diff::HunkId)>,
596 +
    ) -> Result<(), Error> {
597 +
        for index in 0..self.commits.len() {
598 +
            self.load(index)?;
599 +
        }
600 +
        self.reconcile_reviews()?;
601 +
        let identities = newly_accepted
602 +
            .iter()
603 +
            .filter_map(|(index, hunk)| {
604 +
                self.commits[*index]
605 +
                    .loaded
606 +
                    .as_ref()?
607 +
                    .identities
608 +
                    .get(hunk)
609 +
                    .cloned()
610 +
            })
611 +
            .collect::<Vec<_>>();
612 +
        let mut patches = Vec::new();
613 +
        for (index, slot) in self.commits.iter().enumerate() {
614 +
            let Some(loaded) = &slot.loaded else {
615 +
                continue;
616 +
            };
617 +
            for file in &loaded.document.files {
618 +
                let hunks = file
619 +
                    .hunks
620 +
                    .iter()
621 +
                    .filter(|hunk| {
622 +
                        loaded.review.is_accepted(hunk.id)
623 +
                            || newly_accepted.contains(&(index, hunk.id))
624 +
                    })
625 +
                    .cloned()
626 +
                    .collect::<Vec<_>>();
627 +
                if !hunks.is_empty() {
628 +
                    patches.push(FilePatches::new(file, hunks)?);
629 +
                }
630 +
            }
631 +
        }
632 +
        self.brain.accept(identities, patches)
633 +
    }
634 +
602 635
    /// Rebuilds accepted state without the selected hunks.
603 636
    fn reject_hunks(
604 637
        &mut self,
605 638
        rejected: BTreeSet<(usize, rustik_diff::HunkId)>,
606 639
    ) -> Result<(), Error> {
a.rs +0 -0
crates/brain/src/session/commit.rs +5 -14
1 1
//! Per-commit review state for the session.
2 2
3 3
use std::collections::BTreeMap;
4 4
5 5
use rustik_diff::{
6 -
    ContextUpdate, DiffDocument, DiffOptions, DiffViewer, Encode as _, FileId, FileStats, HunkId,
7 -
    ReviewProgress,
6 +
    ContextUpdate, DiffDocument, DiffOptions, DiffViewer, FileId, FileStats, HunkId, ReviewProgress,
8 7
};
9 8
use rustik_repo::DiffStat;
10 9
use rustik_tui::Rect;
11 10
12 11
use crate::backend::{AcceptedHunk, Brain, Commit, commit_remaining_stats};
61 60
    pub(super) viewer: DiffViewer,
62 61
    /// Accepted-hunk state projected from exact persisted identities.
63 62
    pub(super) review: Review,
64 63
    /// Per-hunk comment view for this commit.
65 64
    pub(super) comments: Comments,
66 -
    /// Single-hunk patch text keyed by hunk id.
67 -
    pub(super) hunk_patches: BTreeMap<HunkId, String>,
68 -
    /// Exact accepted-state identity of each original hunk.
65 +
    /// Exact accepted-state identity, including patch id, of each original hunk.
69 66
    pub(super) identities: BTreeMap<HunkId, AcceptedHunk>,
70 67
    /// Full, unfiltered diff document used to restore hidden hunks.
71 68
    pub(super) document: DiffDocument,
72 69
    /// Original hunk ids per file, used for decoration snapshots.
73 70
    pub(super) file_hunks: BTreeMap<FileId, Vec<HunkId>>,
86 83
        self.viewer.is_full_file()
87 84
    }
88 85
89 86
    /// Builds one commit's review state from its split diff document.
90 87
    ///
91 -
    /// Single-hunk patches and their patch ids are computed here, once, so
92 -
    /// later reconciliations only hash residual hunks and comment lookups can
93 -
    /// match on stable ids.
88 +
    /// Hunk identities are computed here once, so later reconciliations only
89 +
    /// hash residual hunks and comment lookups can match on stable patch ids.
94 90
    pub(super) fn load(
95 91
        commit: &Commit,
96 92
        document: DiffDocument,
97 93
        identities: Option<BTreeMap<HunkId, AcceptedHunk>>,
98 94
        options: DiffOptions,
104 100
        let identities = match identities {
105 101
            Some(identities) => identities,
106 102
            None => brain.hunk_identities(&document, commit.id)?,
107 103
        };
108 104
        let heading = format!("{} {}", commit.id.short(), commit.summary);
109 -
        let mut hunk_patches = BTreeMap::new();
110 105
        let review = Review::new();
111 106
        let mut targets = BTreeMap::new();
112 107
        let mut file_hunks = BTreeMap::new();
113 108
        let mut hunk_stats = BTreeMap::new();
114 109
118 113
                file.id,
119 114
                file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>(),
120 115
            );
121 116
            for hunk in &file.hunks {
122 117
                hunk_stats.insert(hunk.id, hunk.stats());
123 -
                let patch = DiffDocument::for_hunks(file, [hunk.clone()]).to_unified_string()?;
124 118
                // `hunk_identities` covers every hunk of the same document, so
125 119
                // a miss is a bug: the hunk could never be accepted or
126 120
                // commented on, which is worse left silent.
127 121
                let identity = identities
128 122
                    .get(&hunk.id)
129 123
                    .ok_or_else(|| Error::Git(format!("hunk {:?} has no identity", hunk.id)))?;
130 -
                let patch_id = identity.patch_id.clone();
131 124
                targets.insert(
132 125
                    hunk.id,
133 126
                    CommentTarget {
134 127
                        heading: heading.clone(),
135 128
                        path: path.clone(),
136 -
                        patch_id: patch_id.clone(),
129 +
                        patch_id: identity.patch_id.clone(),
137 130
                    },
138 131
                );
139 -
                hunk_patches.insert(hunk.id, patch);
140 132
            }
141 133
        }
142 134
        let comments = Comments::new(store, targets);
143 135
        let mut loaded = Self {
144 136
            viewer,
145 137
            review,
146 138
            comments,
147 -
            hunk_patches,
148 139
            identities,
149 140
            document,
150 141
            file_hunks,
151 142
            hunk_stats,
152 143
        };
a.rs +0 -0