brain: Show global history progress

1e59964a803a9e7eb9e968b0c72ad9fee54d8c21
Compute accepted progress from commit patches and diff the accepted projection
against the target for exact remaining statistics.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 173b9efb
crates/brain/src/backend.rs +200 -71
29 29
30 30
/// Directory marking a Jujutsu workspace.
31 31
const JJ_DIR: &str = ".jj";
32 32
/// Commit message used for synthetic brain state commits.
33 33
const SYNTHETIC_BRAIN_MESSAGE: &str = "brain state";
34 -
/// Commit-message section holding exact accepted-hunk state.
35 -
const ACCEPTED_SECTION: &str = "accepted-v1";
34 +
/// Commit-message section for accepted-hunk state.
35 +
const STATE_SECTION: &str = "brain-v1";
36 36
/// Hidden Git ref category holding all review state.
37 37
const BRAIN_REF_CATEGORY: &str = "brain";
38 38
/// Namespace under the brain category for acceptance state commits.
39 39
const STATE_REF_NAMESPACE: &str = "state";
40 40
/// Namespace under the brain category for comment blobs.
103 103
    pub commit: Oid,
104 104
    /// Stable identity of the hunk's change.
105 105
    pub patch_id: PatchId,
106 106
    /// Occurrence of this patch id within the commit.
107 107
    pub ordinal: u32,
108 -
    /// Total number of hunks in the commit.
109 -
    pub commit_hunks: u32,
108 +
    /// Number of changed lines in this hunk.
109 +
    pub lines: u32,
110 +
    /// Total number of changed lines in the commit.
111 +
    pub commit_lines: u32,
110 112
}
111 113
112 114
impl AcceptedHunk {
113 115
    /// Remaps stored identities onto identities in the current range.
114 116
    ///
219 221
    pub hunks: Option<&'a BTreeMap<HunkId, AcceptedHunk>>,
220 222
}
221 223
222 224
/// Review state of one commit projected from the accepted set.
223 225
pub struct Reconciled {
224 -
    /// Accepted-hunk progress for the commit.
226 +
    /// Accepted-line progress for the commit.
225 227
    pub progress: ReviewProgress,
226 228
    /// Accepted hunks, for commits whose hunk patch ids were supplied.
227 229
    pub accepted: BTreeSet<HunkId>,
228 230
}
229 231
230 232
impl Reconciled {
231 233
    /// Projects exact accepted identities onto commit-local hunk ids.
232 234
    fn for_commits(accepted_state: &Accepted, commits: &[CommitHunks<'_>]) -> Vec<Self> {
233 -
        // Accepted count and total hunk count per commit, so undecoded commits
235 +
        // Accepted and total line counts per commit let undecoded commits
234 236
        // retain their progress from persisted totals.
235 237
        let mut totals = BTreeMap::<Oid, (usize, u32)>::new();
236 238
        for identity in accepted_state {
237 239
            let entry = totals
238 240
                .entry(identity.commit)
239 -
                .or_insert((0, identity.commit_hunks));
240 -
            entry.0 += 1;
241 +
                .or_insert((0, identity.commit_lines));
242 +
            entry.0 += identity.lines as usize;
241 243
        }
242 244
243 245
        let mut reconciled = Vec::with_capacity(commits.len());
244 246
        for commit in commits {
245 247
            let (progress, accepted) = match commit.hunks {
249 251
                        .filter(|(_, identity)| accepted_state.contains(identity))
250 252
                        .map(|(id, _)| *id)
251 253
                        .collect::<BTreeSet<_>>();
252 254
                    (
253 255
                        ReviewProgress {
254 -
                            accepted: accepted.len(),
255 -
                            total: hunks.len(),
256 +
                            accepted: accepted
257 +
                                .iter()
258 +
                                .filter_map(|id| hunks.get(id))
259 +
                                .map(|identity| identity.lines as usize)
260 +
                                .sum(),
261 +
                            total: hunks.values().map(|identity| identity.lines as usize).sum(),
256 262
                        },
257 263
                        accepted,
258 264
                    )
259 265
                }
260 266
                None => {
272 278
        }
273 279
        reconciled
274 280
    }
275 281
}
276 282
283 +
/// Global and per-commit review status for the history view.
284 +
#[derive(Clone, Debug, Default)]
285 +
pub struct HistoryStatus {
286 +
    /// Accepted-line progress across the review.
287 +
    pub progress: ReviewProgress,
288 +
    /// Remaining diff from the accepted projection to the target.
289 +
    pub stats: DiffStat,
290 +
    /// Remaining review status keyed by commit.
291 +
    pub commits: BTreeMap<Oid, CommitStatus>,
292 +
}
293 +
294 +
/// Remaining review status for one commit.
295 +
#[derive(Clone, Debug, Default)]
296 +
pub struct CommitStatus {
297 +
    /// Accepted-line progress for the commit.
298 +
    pub progress: ReviewProgress,
299 +
    /// Diff statistics from hunks that remain unaccepted.
300 +
    pub stats: DiffStat,
301 +
    /// Exact accepted-state identity per hunk.
302 +
    pub identities: BTreeMap<HunkId, AcceptedHunk>,
303 +
}
277 304
/// Stored status for one review identity.
278 305
#[derive(Clone, Debug, Eq, PartialEq)]
279 306
pub struct BrainStatus {
280 307
    /// Head name displayed to the user.
281 308
    pub head: String,
283 310
    pub head_kind: BrainStatusHead,
284 311
    /// Brain state status for the review.
285 312
    pub state: BrainStatusState,
286 313
    /// Whether the stored base matches the current review base.
287 314
    pub base_state: BrainStatusBaseState,
288 -
    /// Accepted-hunk progress across the review.
315 +
    /// Accepted-line progress across the review.
289 316
    pub progress: ReviewProgress,
290 317
    /// Ahead and behind counts relative to the trunk branch.
291 318
    pub relation: AheadBehind,
292 319
    /// Merge status relative to the trunk branch.
293 320
    pub merge: MergeStatus,
341 368
struct StoredReview {
342 369
    /// Base commit recorded by the review state.
343 370
    base: Oid,
344 371
    /// Current resolution of the base selector, for staleness checks.
345 372
    current_base: Oid,
346 -
    /// Accepted-hunk progress across the review.
373 +
    /// Accepted-line progress across the review.
347 374
    progress: ReviewProgress,
348 375
    /// Comment storage status for this review.
349 376
    comments: CommentStatus,
350 377
    /// Head commit timestamp used to order status rows.
351 378
    recency: CommitTime,
389 416
    }
390 417
}
391 418
392 419
/// Encodes exact accepted-hunk state in a synthetic commit message.
393 420
fn encode_state(accepted: &Accepted) -> String {
394 -
    let mut message = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n");
421 +
    let mut message = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n");
395 422
    for hunk in accepted {
396 423
        message.push_str(&format!(
397 -
            "{} {} {} {}\n",
398 -
            hunk.commit, hunk.patch_id, hunk.ordinal, hunk.commit_hunks
424 +
            "{} {} {} {} {}\n",
425 +
            hunk.commit, hunk.patch_id, hunk.ordinal, hunk.lines, hunk.commit_lines
399 426
        ));
400 427
    }
401 428
    message
402 429
}
403 430
404 431
/// Decodes exact accepted-hunk state from a synthetic commit message.
405 432
///
406 433
/// Returns `None` for malformed state.
407 434
fn decode_state(message: &str) -> Option<Accepted> {
408 -
    let header = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n");
435 +
    let header = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n");
409 436
    let body = message.strip_prefix(&header)?;
410 437
    let mut accepted = BTreeSet::new();
411 -
    let mut commit_hunks = BTreeMap::new();
438 +
    let mut commit_totals = BTreeMap::new();
412 439
413 440
    for line in body.lines().filter(|line| !line.trim().is_empty()) {
414 441
        let mut fields = line.split_whitespace();
442 +
        let commit = fields.next()?.parse().ok()?;
443 +
        let patch_id = fields.next()?;
444 +
        let ordinal = fields.next()?;
445 +
        let lines = fields.next()?;
446 +
        let commit_lines = fields.next()?;
447 +
        let patch_id = PatchId::from_str(patch_id).ok()?;
448 +
        let ordinal = ordinal.parse().ok()?;
449 +
        let (lines, commit_lines) = (lines.parse().ok()?, commit_lines.parse().ok()?);
415 450
        let hunk = AcceptedHunk {
416 -
            commit: fields.next()?.parse().ok()?,
417 -
            patch_id: PatchId::from_str(fields.next()?).ok()?,
418 -
            ordinal: fields.next()?.parse().ok()?,
419 -
            commit_hunks: fields.next()?.parse().ok()?,
451 +
            commit,
452 +
            patch_id,
453 +
            ordinal,
454 +
            lines,
455 +
            commit_lines,
420 456
        };
421 -
        if fields.next().is_some() || hunk.commit_hunks == 0 {
457 +
        if fields.next().is_some() || hunk.lines == 0 || hunk.commit_lines < hunk.lines {
422 458
            return None;
423 459
        }
424 -
        match commit_hunks.entry(hunk.commit) {
460 +
        match commit_totals.entry(hunk.commit) {
425 461
            std::collections::btree_map::Entry::Vacant(entry) => {
426 -
                entry.insert(hunk.commit_hunks);
462 +
                entry.insert(hunk.commit_lines);
427 463
            }
428 464
            std::collections::btree_map::Entry::Occupied(entry)
429 -
                if *entry.get() != hunk.commit_hunks =>
465 +
                if *entry.get() != hunk.commit_lines =>
430 466
            {
431 467
                return None;
432 468
            }
433 469
            std::collections::btree_map::Entry::Occupied(_) => {}
434 470
        }
463 499
/// The base and target revisions are resolved and stored when the backend is
464 500
/// constructed, so listing commits needs no further arguments.
465 501
pub trait Backend {
466 502
    /// Returns the user-facing revision range under review.
467 503
    fn range_label(&self) -> String;
468 -
    /// Returns the base-to-target diff statistics for the reviewed range.
469 -
    fn range_stats(&self) -> Result<DiffStat, Error>;
470 -
471 504
    /// Returns the reviewed commits in `base..target`, oldest first.
472 505
    fn commits(&self) -> Result<Vec<Commit>, Error>;
473 506
507 +
    /// Resolves the target commit of the reviewed range.
508 +
    fn target(&self) -> Result<Oid, Error>;
509 +
510 +
    /// Returns global and per-commit progress and remaining statistics.
511 +
    fn history_status(
512 +
        &self,
513 +
        brain: &Brain,
514 +
        commits: &[Oid],
515 +
        documents: &[&DiffDocument],
516 +
    ) -> Result<HistoryStatus, Error> {
517 +
        let statuses = brain.commit_statuses(commits, documents)?;
518 +
        let progress = statuses
519 +
            .values()
520 +
            .fold(ReviewProgress::default(), |mut progress, status| {
521 +
                progress.accepted += status.progress.accepted;
522 +
                progress.total += status.progress.total;
523 +
                progress
524 +
            });
525 +
        Ok(HistoryStatus {
526 +
            progress,
527 +
            stats: brain.remaining_stats(self.target()?)?,
528 +
            commits: statuses,
529 +
        })
530 +
    }
531 +
474 532
    /// Returns `commit`'s header.
475 533
    fn commit_header(&self, commit: Oid) -> Result<CommitHeader, Error>;
476 534
477 535
    /// Returns `commit`'s file diffs against its parent.
478 536
    fn file_diffs(&self, commit: Oid) -> Result<Vec<FileDiff>, Error>;
747 805
            Err(_) => CommentStatus::Invalid,
748 806
        };
749 807
        Ok(status)
750 808
    }
751 809
752 -
    /// Returns the target commit and accepted-hunk progress for this review.
810 +
    /// Returns the target commit and accepted-line progress for this review.
753 811
    ///
754 -
    /// Progress is counted from exact accepted-hunk identities.
812 +
    /// Progress is counted from changed lines in exact accepted-hunk identities.
755 813
    fn summary(&self, identity: &ReviewIdentity) -> Result<(Oid, ReviewProgress), Error> {
756 814
        let base = Rev::from(self.base);
757 815
        let target = &identity.target;
758 816
        let head = self.repository.commit_id(target)?;
759 817
        let commits = self.summary_commits(&base, target)?;
763 821
                commit: summary.commit.id,
764 822
                hunks: Some(&summary.identities),
765 823
            })
766 824
            .collect::<Vec<_>>();
767 825
        let reconciled = self.reconcile(&hunks);
768 -
        let accepted = reconciled.iter().map(|state| state.accepted.len()).sum();
769 -
        let total = hunks
770 -
            .iter()
771 -
            .filter_map(|commit| commit.hunks)
772 -
            .map(BTreeMap::len)
773 -
            .sum();
826 +
        let accepted = reconciled.iter().map(|state| state.progress.accepted).sum();
827 +
        let total = reconciled.iter().map(|state| state.progress.total).sum();
774 828
775 829
        Ok((head, ReviewProgress { accepted, total }))
776 830
    }
777 831
778 832
    /// Returns commits and exact hunk identities for status progress.
799 853
        }
800 854
801 855
        Ok(summaries)
802 856
    }
803 857
858 +
    /// Returns accepted-hunk progress for decoded commit documents.
859 +
    fn review_progress(
860 +
        &self,
861 +
        commits: &[Oid],
862 +
        documents: &[&DiffDocument],
863 +
    ) -> Result<BTreeMap<Oid, CommitStatus>, Error> {
864 +
        let identities = commits
865 +
            .iter()
866 +
            .zip(documents)
867 +
            .map(|(commit, document)| self.hunk_identities(document, commit.id))
868 +
            .collect::<Result<Vec<_>, _>>()?;
869 +
        let hunks = commits
870 +
            .iter()
871 +
            .zip(&identities)
872 +
            .map(|(commit, identities)| CommitHunks {
873 +
                commit: commit.id,
874 +
                hunks: Some(identities),
875 +
            })
876 +
            .collect::<Vec<_>>();
877 +
        let reconciled = self.reconcile(&hunks);
878 +
        let mut statuses = BTreeMap::new();
879 +
        for (((commit, document), reconciled), identities) in commits
880 +
            .iter()
881 +
            .zip(documents)
882 +
            .zip(reconciled)
883 +
            .zip(identities)
884 +
        {
885 +
            let mut stats = DiffStat::default();
886 +
            for file in &document.files {
887 +
                let mut remaining = false;
888 +
                for hunk in &file.hunks {
889 +
                    if reconciled.accepted.contains(&hunk.id) {
890 +
                        continue;
891 +
                    }
892 +
                    remaining = true;
893 +
                    let hunk = hunk.stats();
894 +
                    stats.insertions += hunk.additions;
895 +
                    stats.deletions += hunk.deletions;
896 +
                }
897 +
                stats.files_changed += usize::from(remaining);
898 +
            }
899 +
            statuses.insert(
900 +
                *commit,
901 +
                CommitStatus {
902 +
                    progress: reconciled.progress,
903 +
                    stats,
904 +
                    identities,
905 +
                },
906 +
            );
907 +
        }
908 +
        Ok(statuses)
909 +
    }
910 +
911 +
    /// Returns the diff statistics still needed to reach `target`.
912 +
    fn remaining_stats(&self, target: Oid) -> Result<DiffStat, Error> {
913 +
        let document = DiffDocument::decode_str(&self.repository.diff(self.commit, target)?)?;
914 +
        let stats = document.stats();
915 +
        Ok(DiffStat {
916 +
            files_changed: stats.files_changed,
917 +
            insertions: stats.insertions,
918 +
            deletions: stats.deletions,
919 +
        })
920 +
    }
921 +
804 922
    /// Returns exact accepted-state identities in document order.
805 923
    ///
806 924
    /// `document` must be `commit`'s own split-hunk diff: the identities carry
807 925
    /// `commit` verbatim and count its hunks, so passing a document from any
808 926
    /// other commit yields identities that silently name the wrong change.
809 927
    pub fn hunk_identities(
810 928
        &self,
811 929
        document: &DiffDocument,
812 930
        commit: Oid,
813 931
    ) -> Result<BTreeMap<HunkId, AcceptedHunk>, Error> {
932 +
        let hunks = document
933 +
            .files
934 +
            .iter()
935 +
            .flat_map(|file| &file.hunks)
936 +
            .map(|hunk| (hunk.id, hunk.stats()))
937 +
            .collect::<BTreeMap<_, _>>();
938 +
        let commit_lines = hunks.values().try_fold(0u32, |total, stats| {
939 +
            let lines = u32::try_from(stats.additions + stats.deletions)
940 +
                .map_err(|_| Error::Git("hunk contains too many changed lines".to_owned()))?;
941 +
            total
942 +
                .checked_add(lines)
943 +
                .ok_or_else(|| Error::Git("commit contains too many changed lines".to_owned()))
944 +
        })?;
814 945
        let (ids, patches): (Vec<_>, Vec<_>) = hunk_identity_patches(document)?.into_iter().unzip();
815 -
        let commit_hunks = u32::try_from(ids.len())
816 -
            .map_err(|_| Error::Git("commit contains too many review hunks".to_owned()))?;
817 946
        let patch_ids = self.repository.patch_ids(&patches)?;
818 947
        let mut seen = BTreeMap::<PatchId, u32>::new();
819 948
        let mut identities = BTreeMap::new();
820 949
821 950
        for (id, patch_id) in ids.into_iter().zip(patch_ids) {
822 951
            let ordinal = seen.entry(patch_id.clone()).or_default();
952 +
            let stats = hunks
953 +
                .get(&id)
954 +
                .ok_or_else(|| Error::Git(format!("hunk {id:?} has no diff statistics")))?;
955 +
            let lines = u32::try_from(stats.additions + stats.deletions)
956 +
                .map_err(|_| Error::Git("hunk contains too many changed lines".to_owned()))?;
823 957
            let identity = AcceptedHunk {
824 958
                commit,
825 959
                patch_id,
826 960
                ordinal: *ordinal,
827 -
                commit_hunks,
961 +
                lines,
962 +
                commit_lines,
828 963
            };
829 964
            *ordinal += 1;
830 965
            identities.insert(id, identity);
831 966
        }
832 967
        Ok(identities)
1192 1327
            "{} .. {}",
1193 1328
            self.review.base.as_str(),
1194 1329
            self.review.target.as_str()
1195 1330
        )
1196 1331
    }
1197 -
    fn range_stats(&self) -> Result<DiffStat, Error> {
1198 -
        let base = self.repository.commit_id(&self.review.base)?;
1199 -
        let target = self.repository.commit_id(&self.review.target)?;
1200 -
        let document = DiffDocument::decode_str(&self.repository.diff(base, target)?)?;
1201 -
        let stats = document.stats();
1202 -
        Ok(DiffStat {
1203 -
            files_changed: stats.files_changed,
1204 -
            insertions: stats.insertions,
1205 -
            deletions: stats.deletions,
1206 -
        })
1332 +
1333 +
    fn target(&self) -> Result<Oid, Error> {
1334 +
        Ok(self.repository.commit_id(&self.review.target)?)
1207 1335
    }
1208 1336
1209 1337
    fn commits(&self) -> Result<Vec<Commit>, Error> {
1210 1338
        let pairs = self
1211 1339
            .repository
1291 1419
            "{} .. {}",
1292 1420
            self.review.base.as_str(),
1293 1421
            self.review.target.as_str()
1294 1422
        )
1295 1423
    }
1296 -
    fn range_stats(&self) -> Result<DiffStat, Error> {
1297 -
        let base = self.jj.resolve(&self.review.base)?;
1298 -
        let target = self.jj.resolve(&self.review.target)?;
1299 -
        let document = DiffDocument::decode_str(&self.repository.diff(base, target)?)?;
1300 -
        let stats = document.stats();
1301 -
        Ok(DiffStat {
1302 -
            files_changed: stats.files_changed,
1303 -
            insertions: stats.insertions,
1304 -
            deletions: stats.deletions,
1305 -
        })
1424 +
1425 +
    fn target(&self) -> Result<Oid, Error> {
1426 +
        Ok(self.jj.resolve(&self.review.target)?)
1306 1427
    }
1307 1428
1308 1429
    fn commits(&self) -> Result<Vec<Commit>, Error> {
1309 1430
        let commits = self.jj.commits(&self.review.base, &self.review.target)?;
1310 1431
        let bookmarks = self.jj.bookmarks()?;
1363 1484
    fn accepted_hunk(commit: &str, patch: &str, ordinal: u32, total: u32) -> AcceptedHunk {
1364 1485
        AcceptedHunk {
1365 1486
            commit: commit.parse().unwrap(),
1366 1487
            patch_id: PatchId::from(patch.to_owned()),
1367 1488
            ordinal,
1368 -
            commit_hunks: total,
1489 +
            lines: 1,
1490 +
            commit_lines: total,
1369 1491
        }
1370 1492
    }
1371 1493
1372 1494
    #[test]
1373 1495
    fn accepted_state_roundtrips_through_commit_message() {
1389 1511
        // Git terminates `%B` output with its own newline.
1390 1512
        assert_eq!(decode_state(&format!("{message}\n")), Some(Accepted::new()));
1391 1513
    }
1392 1514
1393 1515
    #[test]
1394 -
    fn accepted_state_rejects_inconsistent_hunk_totals() {
1516 +
    fn accepted_state_rejects_inconsistent_line_totals() {
1395 1517
        let commit = "1111111111111111111111111111111111111111";
1396 1518
        let inconsistent = format!(
1397 -
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n{commit} alpha 0 2\n{commit} beta 0 3\n"
1519 +
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{commit} alpha 0 1 2\n{commit} beta 0 1 3\n"
1398 1520
        );
1399 -
        let zero = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n{commit} alpha 0 0\n");
1521 +
        let zero = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{commit} alpha 0 0 1\n");
1400 1522
        let duplicate = format!(
1401 -
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n{commit} alpha 0 1\n{commit} alpha 0 1\n"
1523 +
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{commit} alpha 0 1 1\n{commit} alpha 0 1 1\n"
1402 1524
        );
1403 1525
1404 1526
        assert_eq!(decode_state(&inconsistent), None);
1405 1527
        assert_eq!(decode_state(&zero), None);
1406 1528
        assert_eq!(decode_state(&duplicate), None);
1407 1529
    }
1408 1530
1409 1531
    #[test]
1410 1532
    fn accepted_state_rejects_malformed_payload() {
1411 1533
        let message = format!(
1412 -
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n{} alpha 0 1 extra\n",
1534 +
            "{SYNTHETIC_BRAIN_MESSAGE}\n\n{STATE_SECTION}\n{} alpha 0 1 1 extra\n",
1413 1535
            "1111111111111111111111111111111111111111"
1414 1536
        );
1415 1537
1416 1538
        assert_eq!(decode_state(&message), None);
1417 1539
    }
1446 1568
        assert_eq!(remaining[1].accepted, BTreeSet::from([HunkId::new(0)]));
1447 1569
        assert!(remaining[1].progress.is_complete());
1448 1570
    }
1449 1571
1450 1572
    #[test]
1451 -
    fn reconciliation_marks_undecoded_commits_from_persisted_totals() {
1452 -
        let first = accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 2);
1453 -
        let second = accepted_hunk("1111111111111111111111111111111111111111", "beta", 0, 2);
1573 +
    fn reconciliation_weights_undecoded_progress_by_changed_lines() {
1574 +
        let first = AcceptedHunk {
1575 +
            lines: 3,
1576 +
            commit_lines: 4,
1577 +
            ..accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 4)
1578 +
        };
1579 +
        let second = AcceptedHunk {
1580 +
            commit_lines: 4,
1581 +
            ..accepted_hunk("1111111111111111111111111111111111111111", "beta", 0, 4)
1582 +
        };
1454 1583
        let commits = [CommitHunks {
1455 1584
            commit: first.commit,
1456 1585
            hunks: None,
1457 1586
        }];
1458 1587
1459 1588
        let partial = Reconciled::for_commits(&Accepted::from([first.clone()]), &commits);
1460 1589
        assert_eq!(
1461 1590
            partial[0].progress,
1462 1591
            ReviewProgress {
1463 -
                accepted: 1,
1464 -
                total: 2,
1592 +
                accepted: 3,
1593 +
                total: 4,
1465 1594
            }
1466 1595
        );
1467 1596
        assert!(partial[0].accepted.is_empty());
1468 1597
1469 1598
        let full = Reconciled::for_commits(&Accepted::from([first, second]), &commits);
1478 1607
        // longer matches exactly.
1479 1608
        let kept = accepted_hunk("2222222222222222222222222222222222222222", "same", 0, 1);
1480 1609
        let stored = Accepted::from([kept.clone()]);
1481 1610
        let elsewhere = accepted_hunk("3333333333333333333333333333333333333333", "same", 0, 1);
1482 1611
        let same_commit = AcceptedHunk {
1483 -
            commit_hunks: 2,
1612 +
            commit_lines: 2,
1484 1613
            ..kept
1485 1614
        };
1486 1615
        let current = [elsewhere, same_commit.clone()];
1487 1616
1488 1617
        let remapped = AcceptedHunk::remap(&stored, &current);
f +0 -0
crates/brain/src/decorate.rs +8 -2
79 79
        let hunks = self.file_hunks.get(&file).map_or(&[][..], Vec::as_slice);
80 80
        let progress = (!hunks.is_empty()).then(|| ReviewProgress {
81 81
            accepted: hunks
82 82
                .iter()
83 83
                .filter(|hunk| self.accepted.contains(hunk))
84 -
                .count(),
85 -
            total: hunks.len(),
84 +
                .filter_map(|hunk| self.hunk_stats.get(hunk))
85 +
                .map(|stats| stats.additions + stats.deletions)
86 +
                .sum(),
87 +
            total: hunks
88 +
                .iter()
89 +
                .filter_map(|hunk| self.hunk_stats.get(hunk))
90 +
                .map(|stats| stats.additions + stats.deletions)
91 +
                .sum(),
86 92
        });
87 93
        let comment_count = hunks
88 94
            .iter()
89 95
            .filter_map(|hunk| self.comments.get(hunk))
90 96
            .sum::<usize>();
crates/brain/src/main.rs +3 -5
242 242
        file_tree_root: root,
243 243
        hunk_focus: HunkFocus::DimUnfocused,
244 244
        ..DiffOptions::default()
245 245
    };
246 246
247 -
    // Commit diffs are decoded lazily when first displayed; only the commit
248 -
    // list and its stats are fetched up front. Commits that introduce no
249 -
    // changes are skipped.
250 -
    let mut commits = backend.commits()?;
251 -
    commits.retain(|commit| commit.stats.files_changed > 0);
247 +
    // Multi-commit history decodes each patch once to select reviewable rows
248 +
    // and calculate exact progress. A single commit stays lazy until displayed.
249 +
    let commits = backend.commits()?;
252 250
    if commits.is_empty() {
253 251
        return Err(Error::Empty);
254 252
    }
255 253
256 254
    let mut terminal = match terminal {
crates/brain/src/session.rs +113 -32
110 110
    let Events {
111 111
        tx: events_tx,
112 112
        rx: events_rx,
113 113
    } = events;
114 114
115 -
    let (mode, range_stats) = if commits.len() > 1 {
116 -
        (Mode::Commits, Some(backend.range_stats()?))
117 -
    } else {
118 -
        (Mode::Diff, None)
119 -
    };
120 -
121 115
    let range = backend.range_label();
122 -
123 -
    let mut session = Session {
124 -
        terminal,
125 -
        commits: commits
116 +
    let (mut slots, history_status) = if commits.len() > 1 {
117 +
        let mut reviewed = Vec::with_capacity(commits.len());
118 +
        for commit in commits {
119 +
            let document = backend.diff_document(commit.id)?.split_hunks();
120 +
            if document.files.iter().any(|file| !file.hunks.is_empty()) {
121 +
                reviewed.push((commit, document));
122 +
            }
123 +
        }
124 +
        if reviewed.is_empty() {
125 +
            return Err(Error::Empty);
126 +
        }
127 +
        let commit_ids = reviewed
128 +
            .iter()
129 +
            .map(|(commit, _)| commit.id)
130 +
            .collect::<Vec<_>>();
131 +
        let documents = reviewed
132 +
            .iter()
133 +
            .map(|(_, document)| document)
134 +
            .collect::<Vec<_>>();
135 +
        let mut history = backend.history_status(&brain, &commit_ids, &documents)?;
136 +
        let slots = reviewed
137 +
            .into_iter()
138 +
            .map(|(commit, document)| {
139 +
                let status = history.commits.entry(commit.id).or_default();
140 +
                let progress = status.progress;
141 +
                let remaining_stats = status.stats;
142 +
                let identities = mem::take(&mut status.identities);
143 +
                CommitSlot {
144 +
                    commit,
145 +
                    progress,
146 +
                    remaining_stats,
147 +
                    document: Some(document),
148 +
                    identities: Some(identities),
149 +
                    loaded: None,
150 +
                }
151 +
            })
152 +
            .collect::<Vec<_>>();
153 +
        (slots, Some(history))
154 +
    } else {
155 +
        let slots = commits
126 156
            .into_iter()
127 -
            .rev()
128 157
            .map(|commit| CommitSlot {
158 +
                remaining_stats: commit.stats,
129 159
                commit,
130 160
                progress: ReviewProgress::default(),
161 +
                document: None,
162 +
                identities: None,
131 163
                loaded: None,
132 164
            })
133 -
            .collect(),
134 -
        range_stats,
165 +
            .collect::<Vec<_>>();
166 +
        (slots, None)
167 +
    };
168 +
    slots.reverse();
169 +
    let mode = if slots.len() > 1 {
170 +
        Mode::Commits
171 +
    } else {
172 +
        Mode::Diff
173 +
    };
174 +
175 +
    let mut session = Session {
176 +
        terminal,
177 +
        commits: slots,
135 178
        range,
179 +
        history_status,
136 180
        current: 0,
137 181
        visibility: Visibility::default(),
138 182
        mode,
139 183
        parked: None,
140 184
        list: ListState::new(),
146 190
        generation: 0,
147 191
        highlighter: None,
148 192
        context_fetch: ContextFetch::default(),
149 193
        error: None,
150 194
    };
195 +
151 196
    if !matches!(session.mode, Mode::Commits) {
152 197
        session.current()?;
153 -
    }
154 -
    session.reconcile_state();
155 -
    if !matches!(session.mode, Mode::Commits) {
198 +
        session.reconcile_state();
156 199
        session.activate()?;
157 200
    }
158 201
    session.redraw()?;
159 202
160 203
    while let Ok(event) = events_rx.recv() {
187 230
    terminal: &'a mut BrainTerminal,
188 231
    /// Per-commit review slots, newest first.
189 232
    commits: Vec<CommitSlot>,
190 233
    /// User-facing revision range under review.
191 234
    range: String,
192 -
    /// Lazily cached base-to-target statistics for the reviewed range.
193 -
    range_stats: Option<DiffStat>,
235 +
    /// Lazily cached global progress and remaining statistics for history.
236 +
    history_status: Option<(ReviewProgress, DiffStat)>,
194 237
    /// Index of the commit currently displayed.
195 238
    current: usize,
196 239
    /// Session-wide accepted-hunk visibility.
197 240
    visibility: Visibility,
198 241
    /// Active view: the commit list, the diff, or a hunk's comment box.
231 274
    fn load(&mut self, index: usize) -> Result<&mut CommitReview, Error> {
232 275
        let slot = &mut self.commits[index];
233 276
        let loaded = match slot.loaded.take() {
234 277
            Some(loaded) => loaded,
235 278
            None => {
236 -
                let document = self.backend.diff_document(slot.commit.id)?;
279 +
                let document = match slot.document.take() {
280 +
                    Some(document) => document,
281 +
                    None => self.backend.diff_document(slot.commit.id)?.split_hunks(),
282 +
                };
283 +
                if !document.files.iter().any(|file| !file.hunks.is_empty()) {
284 +
                    return Err(Error::Empty);
285 +
                }
237 286
                CommitReview::load(
238 287
                    &slot.commit,
239 288
                    document,
289 +
                    slot.identities.take(),
240 290
                    self.options.clone(),
241 291
                    &self.brain,
242 292
                    &self.comments,
243 293
                )?
244 294
            }
572 622
        self.restart_highlighter()?;
573 623
574 624
        Ok(())
575 625
    }
576 626
577 -
    /// Loads and caches the base-to-target statistics used by history.
578 -
    fn ensure_range_stats(&mut self) -> Result<(), Error> {
579 -
        if self.range_stats.is_none() {
580 -
            self.range_stats = Some(self.backend.range_stats()?);
627 +
    /// Loads and caches global progress and remaining statistics for history.
628 +
    fn ensure_history_status(&mut self) -> Result<(), Error> {
629 +
        if self.history_status.is_none() {
630 +
            let commits = self
631 +
                .commits
632 +
                .iter()
633 +
                .map(|slot| slot.commit.id)
634 +
                .collect::<Vec<_>>();
635 +
            let documents = self
636 +
                .commits
637 +
                .iter()
638 +
                .map(|slot| {
639 +
                    slot.loaded
640 +
                        .as_ref()
641 +
                        .map(|loaded| loaded.viewer.document())
642 +
                        .ok_or_else(|| Error::Git("history commit was not decoded".to_owned()))
643 +
                })
644 +
                .collect::<Result<Vec<_>, _>>()?;
645 +
            let status = self
646 +
                .backend
647 +
                .history_status(&self.brain, &commits, &documents)?;
648 +
            for slot in &mut self.commits {
649 +
                if let Some(commit) = status.commits.get(&slot.commit.id) {
650 +
                    slot.progress = commit.progress;
651 +
                    slot.remaining_stats = commit.stats;
652 +
                }
653 +
            }
654 +
            self.history_status = Some(status);
581 655
        }
582 656
        Ok(())
583 657
    }
584 658
585 659
    /// Switches to the next review tab, parking any open hunk view.
586 660
    fn next_tab(&mut self) -> Result<(), Error> {
587 661
        let opens_history = matches!(&self.mode, Mode::Hunk(_))
588 662
            || matches!(&self.mode, Mode::Diff) && self.parked.is_none();
589 663
        if opens_history {
590 -
            self.ensure_range_stats()?;
664 +
            self.ensure_history_status()?;
591 665
            self.stop_highlighter();
592 666
        }
593 667
        match mem::replace(&mut self.mode, Mode::Diff) {
594 668
            Mode::Commits => {
595 669
                self.select_commit(self.list.selected())?;
876 950
    }
877 951
878 952
    /// Reconciles review state and refreshes the active viewer when needed.
879 953
    fn reconcile_reviews(&mut self) -> Result<(), Error> {
880 954
        self.reconcile_state();
955 +
        self.history_status = None;
881 956
        if !self.visibility.show_accepted && !matches!(self.mode, Mode::Commits) {
882 957
            self.refresh_visibility()?;
883 958
        }
884 959
        Ok(())
885 960
    }
1079 1154
    }
1080 1155
1081 1156
    /// Returns the footer chrome for the current session mode.
1082 1157
    fn chrome(&self) -> Chrome {
1083 1158
        let (context, progress, stats) = if matches!(self.mode, Mode::Commits) {
1084 -
            let stats = self.range_stats.unwrap_or_default();
1085 -
            (
1086 -
                StatusContext::Range(self.range.clone()),
1087 -
                ReviewProgress::default(),
1088 -
                stats,
1089 -
            )
1159 +
            let (progress, stats) = self.history_status.unwrap_or_default();
1160 +
            (StatusContext::Range(self.range.clone()), progress, stats)
1090 1161
        } else {
1091 1162
            let slot = &self.commits[self.current];
1092 1163
            let progress = slot
1093 1164
                .loaded
1094 1165
                .as_ref()
1095 1166
                .map_or(slot.progress, |loaded| ReviewProgress {
1096 -
                    accepted: loaded.review.accepted().len(),
1097 -
                    total: loaded.file_hunks.values().map(Vec::len).sum(),
1167 +
                    accepted: loaded
1168 +
                        .review
1169 +
                        .accepted()
1170 +
                        .iter()
1171 +
                        .filter_map(|hunk| loaded.hunk_stats.get(hunk))
1172 +
                        .map(|stats| stats.additions + stats.deletions)
1173 +
                        .sum(),
1174 +
                    total: loaded
1175 +
                        .hunk_stats
1176 +
                        .values()
1177 +
                        .map(|stats| stats.additions + stats.deletions)
1178 +
                        .sum(),
1098 1179
                });
1099 1180
            let stats = slot.loaded.as_ref().map_or_else(
1100 1181
                || {
1101 1182
                    if slot.progress.is_complete() {
1102 1183
                        DiffStat::default()
crates/brain/src/session/commit.rs +14 -5
17 17
18 18
/// One commit in the reviewed range: header data plus lazily decoded state.
19 19
pub(super) struct CommitSlot {
20 20
    /// Commit under review.
21 21
    pub(super) commit: Commit,
22 -
    /// Accepted-hunk progress for this commit.
22 +
    /// Accepted-line progress for this commit.
23 23
    ///
24 -
    /// Persisted hunk totals provide progress before the diff is decoded.
24 +
    /// Persisted line totals provide progress before the diff is decoded.
25 25
    pub(super) progress: ReviewProgress,
26 +
    /// Remaining diff statistics for this commit.
27 +
    pub(super) remaining_stats: DiffStat,
28 +
    /// Split diff document retained from history progress calculation.
29 +
    pub(super) document: Option<DiffDocument>,
30 +
    /// Exact hunk identities retained from history progress calculation.
31 +
    pub(super) identities: Option<BTreeMap<HunkId, AcceptedHunk>>,
26 32
    /// Decoded diff state, populated when the commit is first displayed.
27 33
    pub(super) loaded: Option<CommitReview>,
28 34
}
29 35
30 36
/// Decoded review state for one commit: its viewer, accepted hunks, and the
72 78
            total.files_changed += usize::from(remaining);
73 79
        }
74 80
        total
75 81
    }
76 82
77 -
    /// Decodes one commit's review state from its diff document.
83 +
    /// Builds one commit's review state from its split diff document.
78 84
    ///
79 85
    /// Single-hunk patches and their patch ids are computed here, once, so
80 86
    /// later reconciliations only hash residual hunks and comment lookups can
81 87
    /// match on stable ids.
82 88
    pub(super) fn load(
83 89
        commit: &Commit,
84 90
        document: DiffDocument,
91 +
        identities: Option<BTreeMap<HunkId, AcceptedHunk>>,
85 92
        options: DiffOptions,
86 93
        brain: &Brain,
87 94
        store: &ReviewComments,
88 95
    ) -> Result<Self, Error> {
89 -
        let document = document.split_hunks();
90 96
        let mut viewer = DiffViewer::new(document, options);
91 97
        viewer.load_file_sources(|oid| brain.read_blob(oid))?;
92 98
        let files = viewer.document().files.clone();
93 -
        let identities = brain.hunk_identities(viewer.document(), commit.id)?;
99 +
        let identities = match identities {
100 +
            Some(identities) => identities,
101 +
            None => brain.hunk_identities(viewer.document(), commit.id)?,
102 +
        };
94 103
        let heading = format!("{} {}", commit.id.short(), commit.summary);
95 104
        let mut hunk_patches = BTreeMap::new();
96 105
        let review = Review::new();
97 106
        let mut targets = BTreeMap::new();
98 107
        let mut file_hunks = BTreeMap::new();
a.rs +0 -0
crates/brain/src/session/status.rs +4 -1
128 128
pub(super) struct Status {
129 129
    /// Active review mode name.
130 130
    pub(super) mode: &'static str,
131 131
    /// Review context displayed for the active mode.
132 132
    pub(super) context: StatusContext,
133 -
    /// Accepted-hunk progress for the active review context.
133 +
    /// Accepted-line progress for the active review context.
134 134
    pub(super) progress: ReviewProgress,
135 135
    /// Aggregated diff size for the active review context.
136 136
    pub(super) stats: DiffStat,
137 137
    /// Diff palette used for stat and review colors.
138 138
    pub(super) palette: DiffPalette,
645 645
            },
646 646
            progress: ReviewProgress {
647 647
                accepted: 1,
648 648
                total: 1,
649 649
            },
650 +
            remaining_stats: stats,
651 +
            document: None,
652 +
            identities: None,
650 653
            loaded: None,
651 654
        };
652 655
1: ) -> [Line; 10] {
653 656
    let [
654 657
        graph, id, insertions, deletions, files, status, progress, branches, _, age, summary,
crates/diff/src/decorate.rs +4 -4
48 48
    pub progress: Option<ReviewProgress>,
49 49
    /// Replacement for the computed addition and deletion counts, when set.
50 50
    pub stats: Option<FileStats>,
51 51
}
52 52
53 -
/// Review progress over a fixed set of hunks.
53 +
/// Review progress over a fixed number of changed lines.
54 54
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
55 55
pub struct ReviewProgress {
56 -
    /// Number of accepted hunks.
56 +
    /// Number of accepted changed lines.
57 57
    pub accepted: usize,
58 -
    /// Total number of reviewable hunks.
58 +
    /// Total number of reviewable changed lines.
59 59
    pub total: usize,
60 60
}
61 61
62 62
impl ReviewProgress {
63 -
    /// Returns whether all reviewable hunks have been accepted.
63 +
    /// Returns whether all reviewable changed lines have been accepted.
64 64
    pub fn is_complete(self) -> bool {
65 65
        self.total > 0 && self.accepted >= self.total
66 66
    }
67 67
68 68
    /// Returns the filled cell count for a progress bar of the given width.
crates/repo/src/git.rs +60 -16
26 26
const LC_ALL: &str = "LC_ALL";
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 +
/// Hexadecimal width of a SHA-1 object identifier.
32 +
const SHA1_HEX_LEN: usize = 40;
33 +
/// Hexadecimal width of a SHA-256 object identifier.
34 +
const SHA256_HEX_LEN: usize = 64;
31 35
32 36
/// Git repository command context.
33 37
#[derive(Clone, Debug)]
34 38
pub struct Repository {
35 39
    /// Working directory for worktree-aware invocations.
36 40
    cwd: PathBuf,
37 41
    /// Git repository directory used for plumbing invocations.
38 42
    git_dir: PathBuf,
43 +
    /// Hexadecimal width of object identifiers in this repository.
44 +
    object_id_width: usize,
39 45
    /// Revision and option arguments forwarded during context refetches.
40 46
    selector_args: Vec<OsString>,
41 47
}
42 48
43 49
impl Repository {
50 56
        let selector_args = repository.diff_selector_args(diff_args.into())?;
51 57
        Ok(repository.with_selector_args(selector_args))
52 58
    }
53 59
54 60
    /// Creates a repository command context with an explicit repository directory.
55 -
    pub fn from_git_dir(cwd: PathBuf, git_dir: PathBuf) -> Self {
56 -
        Self {
61 +
    pub fn from_git_dir(cwd: PathBuf, git_dir: PathBuf) -> Result<Self, RepoError> {
62 +
        let output = Command::new("git")
63 +
            .arg("--git-dir")
64 +
            .arg(&git_dir)
65 +
            .args(["rev-parse", "--show-object-format"])
66 +
            .current_dir(&cwd)
67 +
            .env(NO_COLOR, "1")
68 +
            .env(LC_ALL, "C")
69 +
            .output()?;
70 +
        if !output.status.success() {
71 +
            return Err(RepoError::git(&output));
72 +
        }
73 +
        let format = utf8(output.stdout)?;
74 +
        let object_id_width = object_id_width(format.trim())?;
75 +
76 +
        Ok(Self {
57 77
            cwd,
58 78
            git_dir,
79 +
            object_id_width,
59 80
            selector_args: Vec::new(),
60 -
        }
81 +
        })
61 82
    }
62 83
63 84
    /// Creates a repository command context by resolving the repository for `cwd`.
64 85
    pub fn discover(cwd: PathBuf) -> Result<Self, RepoError> {
65 86
        let output = Command::new("git")
66 87
            .arg("rev-parse")
67 -
            .args(["--absolute-git-dir"])
88 +
            .args(["--absolute-git-dir", "--show-object-format"])
68 89
            .current_dir(&cwd)
69 90
            .env(NO_COLOR, "1")
70 91
            .env(LC_ALL, "C")
71 92
            .output()?;
72 93
        if !output.status.success() {
73 94
            return Err(RepoError::git(&output));
74 95
        }
75 96
        let text = utf8(output.stdout)?;
76 -
        let git_dir = PathBuf::from(text.trim());
77 -
        if git_dir.as_os_str().is_empty() {
97 +
        let mut lines = text.lines();
98 +
        let git_dir = PathBuf::from(lines.next().unwrap_or_default());
99 +
        let object_id_width = object_id_width(lines.next().unwrap_or_default())?;
100 +
        if git_dir.as_os_str().is_empty() || lines.next().is_some() {
78 101
            return Err(RepoError::Git(
79 -
                "git rev-parse --absolute-git-dir returned an empty path".to_owned(),
102 +
                "git rev-parse returned invalid repository metadata".to_owned(),
80 103
            ));
81 104
        }
82 105
        Ok(Self {
83 106
            cwd,
84 107
            git_dir,
108 +
            object_id_width,
85 109
            selector_args: Vec::new(),
86 110
        })
87 111
    }
88 112
89 113
    /// Returns the absolute working-tree root, which diff paths are relative to.
105 129
    /// Returns a copy with `selector_args` used for diff context refetches.
106 130
    pub fn with_selector_args(&self, selector_args: impl Into<Vec<OsString>>) -> Self {
107 131
        Self {
108 132
            cwd: self.cwd.clone(),
109 133
            git_dir: self.git_dir.clone(),
134 +
            object_id_width: self.object_id_width,
110 135
            selector_args: selector_args.into(),
111 136
        }
112 137
    }
113 138
114 139
    /// Runs `git diff` with raw command-line arguments.
560 585
561 586
    /// Computes stable Git patch ids for many patches in one invocation.
562 587
    ///
563 588
    /// The patches are streamed to a single `git patch-id` process, separated
564 589
    /// by synthetic `commit` headers whose ids map output rows back to input
565 -
    /// positions. Patches with no content report the default patch id.
590 +
    /// positions. Every input patch must produce one output row.
566 591
    fn patch_ids(&self, patches: &[String]) -> Result<Vec<PatchId>, RepoError> {
567 592
        if patches.is_empty() {
568 593
            return Ok(Vec::new());
569 594
        }
595 +
        let width = self.object_id_width;
570 596
        let mut stream = String::new();
571 597
        for (index, patch) in patches.iter().enumerate() {
572 -
            stream.push_str(&format!("commit {index:040x}\n"));
598 +
            stream.push_str(&format!("commit {index:0width$x}\n"));
573 599
            stream.push_str(patch);
574 600
            if !patch.ends_with('\n') {
575 601
                stream.push('\n');
576 602
            }
577 603
        }
591 617
        for line in stdout.lines() {
592 618
            if let Some((id, commit)) = line.split_once(' ') {
593 619
                by_commit.insert(commit.trim().to_owned(), PatchId(id.to_owned()));
594 620
            }
595 621
        }
596 -
        Ok((0..patches.len())
597 -
            .map(|index| {
598 -
                by_commit
599 -
                    .remove(&format!("{index:040x}"))
600 -
                    .unwrap_or_default()
601 -
            })
602 -
            .collect())
622 +
        let mut ids = Vec::with_capacity(patches.len());
623 +
        for index in 0..patches.len() {
624 +
            let commit = format!("{index:0width$x}");
625 +
            let id = by_commit.remove(&commit).ok_or_else(|| {
626 +
                RepoError::Git(format!("git patch-id returned no id for patch {index}"))
627 +
            })?;
628 +
            ids.push(id);
629 +
        }
630 +
        Ok(ids)
603 631
    }
604 632
605 633
    /// Computes a three-way merge tree and returns the resulting tree id.
606 634
    fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result<Oid, RepoError> {
607 635
        let merge_base = merge_base.to_string();
876 904
    fn drop(&mut self) {
877 905
        let _ = fs::remove_dir_all(&self.dir);
878 906
    }
879 907
}
880 908
909 +
/// Returns the hexadecimal object identifier width for a Git object format.
910 +
fn object_id_width(format: &str) -> Result<usize, RepoError> {
911 +
    match format {
912 +
        "sha1" => Ok(SHA1_HEX_LEN),
913 +
        "sha256" => Ok(SHA256_HEX_LEN),
914 +
        format => Err(RepoError::Git(format!(
915 +
            "unsupported Git object format: {format}"
916 +
        ))),
917 +
    }
918 +
}
919 +
881 920
/// Converts bytes to a UTF-8 string.
882 921
fn utf8(bytes: Vec<u8>) -> Result<String, RepoError> {
883 922
    String::from_utf8(bytes).map_err(|e| RepoError::Git(e.to_string()))
884 923
}
885 924
938 977
        assert_eq!(
939 978
            error.to_string(),
940 979
            "malformed commit metadata line from git log"
941 980
        );
942 981
    }
982 +
983 +
    #[test]
984 +
    fn patch_ids_map_sha1_and_sha256_streams() {
985 +
        let patches = [
986 +
            "
a\n--- a/a\n+++ b/a\n@@ -1 +1 @@\n-old\n+new\n".to_owned(), +0 -0
b\n--- a/b\n+++ b/b\n@@ -0,0 +1 @@\n+line\n".to_owned(), +0 -0
crates/repo/src/jj.rs +1 -1
79 79
    }
80 80
81 81
    /// Returns a [`git::Repository`] for the embedded Git repository in this workspace.
82 82
    pub fn git_repository(&self) -> Result<git::Repository, RepoError> {
83 83
        let root = self.git_root()?;
84 -
        Ok(git::Repository::from_git_dir(self.cwd.clone(), root))
84 +
        git::Repository::from_git_dir(self.cwd.clone(), root)
85 85
    }
86 86
87 87
    /// Resolves `revision` to a full commit hash.
88 88
    pub fn resolve(&self, revision: &Rev) -> Result<Oid, RepoError> {
89 89
        let text = self.jj_text(&[
crates/repo/src/lib.rs +1 -1
215 215
    fn diff(&self, from: Oid, to: Oid) -> Result<String, RepoError>;
216 216
217 217
    /// Computes a stable Git patch id for `patch` text.
218 218
    fn patch_id(&self, patch: &str) -> Result<PatchId, RepoError>;
219 219
220 -
    /// Computes stable Git patch ids for many patches in one invocation.
220 +
    /// Computes stable Git patch ids for patches that each produce an id.
221 221
    fn patch_ids(&self, patches: &[String]) -> Result<Vec<PatchId>, RepoError>;
222 222
223 223
    /// Computes a three-way merge tree and returns the resulting tree id.
224 224
    fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result<Oid, RepoError>;
225 225