crates/brain/src/backend.rs 104.7 KiB raw
1
//! Revision backend abstraction for loading the commits under review.
2
//!
3
//! `brain` reviews the commits between a `base` and a `target` revision, one
4
//! commit at a time. The commit list and each commit's diff (against its
5
//! parent) come from either Git or Jujutsu; the backend is auto-detected from
6
//! the working directory. Jujutsu repositories are supported whether or not
7
//! they are colocated with Git, since `jj` produces the patches directly.
8
9
use std::cmp::Ordering;
10
use std::collections::{BTreeMap, BTreeSet};
11
use std::ffi::OsString;
12
use std::path::Path;
13
use std::str::FromStr as _;
14
15
use rustik_diff::{
16
    CommitHeader, Decode as _, DiffDocument, DiffLineKind, Encode as _, FileDiff, FileKind, Hunk,
17
    HunkHeader, HunkId, ReviewProgress,
18
};
19
use rustik_repo::{
20
    AheadBehind, Branch, CommitTime, DiffStat, MergeStatus, Oid, PatchId, ReadRepository, Rev,
21
    WriteRepository,
22
    git::{
23
        self,
24
        refs::{Component, Qualified, RefString},
25
    },
26
    jj,
27
};
28
29
use crate::comments::ReviewComments;
30
use crate::error::Error;
31
32
/// Directory marking a Jujutsu workspace.
33
const JJ_DIR: &str = ".jj";
34
/// Number of hexadecimal digits shown for a review target in a state commit summary.
35
const REVIEW_TARGET_ABBREVIATION_LEN: usize = 7;
36
/// Commit-message section for accepted-hunk state and its resolved target.
37
const STATE_SECTION: &str = "brain-v1";
38
/// Hidden Git ref category holding all review state.
39
const BRAIN_REF_CATEGORY: &str = "brain";
40
/// Namespace under the brain category for acceptance state commits.
41
const STATE_REF_NAMESPACE: &str = "state";
42
/// Namespace under the brain category for comment blobs.
43
const COMMENTS_REF_NAMESPACE: &str = "comments";
44
45
/// One commit in the reviewed range, identified by its Git hash.
46
#[derive(Clone, Debug, Eq, PartialEq)]
47
pub struct Commit {
48
    /// Full Git commit hash.
49
    pub id: Oid,
50
    /// First line of the commit message.
51
    pub summary: String,
52
    /// Author name without an email address.
53
    pub author: String,
54
    /// Local branches whose tips point to this commit.
55
    pub branches: Vec<String>,
56
    /// Newest author or committer timestamp.
57
    pub recency: CommitTime,
58
    /// Aggregated diff size, shown in the commit list.
59
    pub stats: DiffStat,
60
}
61
62
impl Commit {
63
    /// Returns Git revision selectors for this commit's parent diff.
64
    fn selectors(&self) -> [OsString; 2] {
65
        [
66
            OsString::from(format!("{}^", self.id)),
67
            OsString::from(self.id.to_string()),
68
        ]
69
    }
70
71
    /// Joins commit metadata with bulk-fetched diff stats and recency.
72
    fn with_stats(
73
        repository: &git::Repository,
74
        commits: Vec<(Oid, String)>,
75
        pointers: impl IntoIterator<Item = (Oid, String)>,
76
    ) -> Result<Vec<Self>, Error> {
77
        let ids = commits.iter().map(|(id, _)| *id).collect::<Vec<_>>();
78
        let stats = repository.commit_stats(&ids)?;
79
        let metadata = repository.commit_metadata(&ids)?;
80
        let mut branches = BTreeMap::<Oid, Vec<String>>::new();
81
        for (head, name) in pointers {
82
            branches.entry(head).or_default().push(name);
83
        }
84
85
        Ok(commits
86
            .into_iter()
87
            .zip(stats)
88
            .zip(metadata)
89
            .map(|(((id, summary), stats), (author, recency))| Self {
90
                id,
91
                summary,
92
                author,
93
                branches: branches.remove(&id).unwrap_or_default(),
94
                recency,
95
                stats,
96
            })
97
            .collect())
98
    }
99
}
100
101
/// Exact identity of one accepted hunk.
102
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
103
pub struct AcceptedHunk {
104
    /// Commit containing the hunk.
105
    pub commit: Oid,
106
    /// Stable identity of the hunk's change.
107
    pub patch_id: PatchId,
108
    /// Occurrence of this patch id within the commit.
109
    pub ordinal: u32,
110
    /// Number of changed lines in this hunk.
111
    pub lines: u32,
112
    /// Total number of changed lines in the commit.
113
    pub commit_lines: u32,
114
}
115
116
impl AcceptedHunk {
117
    /// Remaps stored identities onto identities in the current range.
118
    ///
119
    /// Matching runs in three passes, each consuming stored acceptances the
120
    /// earlier passes left unmatched:
121
    ///
122
    /// 1. exact identity, for commits the move left untouched;
123
    /// 2. same commit and patch id, for commits whose hunk count changed;
124
    /// 3. patch id alone, which is what carries acceptance across a rebase,
125
    ///    since a rewritten commit has a new id.
126
    ///
127
    /// The last pass is deliberately fuzzy: a change that moved between
128
    /// commits keeps its acceptance. Restricting it to the patch id keeps
129
    /// unrelated content from inheriting acceptance, but two commits carrying
130
    /// the identical change are indistinguishable here, so the earlier passes
131
    /// exist to claim the unambiguous matches first.
132
    fn remap<'a>(
133
        stored: &Accepted,
134
        current: impl IntoIterator<Item = &'a AcceptedHunk>,
135
        commits: &BTreeMap<Oid, Oid>,
136
    ) -> Accepted {
137
        let stored = stored
138
            .iter()
139
            .cloned()
140
            .map(|mut identity| {
141
                if let Some(commit) = commits.get(&identity.commit) {
142
                    identity.commit = *commit;
143
                }
144
                identity
145
            })
146
            .collect::<Accepted>();
147
        let current = current.into_iter().cloned().collect::<Vec<_>>();
148
        let live = current.iter().collect::<BTreeSet<_>>();
149
        let mut accepted = Accepted::new();
150
        let mut remaining = Vec::new();
151
        for identity in &stored {
152
            if live.contains(identity) {
153
                accepted.insert(identity.clone());
154
            } else {
155
                remaining.push(identity.clone());
156
            }
157
        }
158
        Self::claim(&mut remaining, &current, &mut accepted, |identity| {
159
            (identity.commit, identity.patch_id.clone())
160
        });
161
        Self::claim(&mut remaining, &current, &mut accepted, |identity| {
162
            identity.patch_id.clone()
163
        });
164
165
        accepted
166
    }
167
168
    /// Matches still-unaccepted current identities against `remaining` by `key`.
169
    ///
170
    /// Each stored acceptance grants one match for its key, consumed by current
171
    /// identities in range order; consumed acceptances leave `remaining` so a
172
    /// later, fuzzier pass cannot spend them a second time.
173
    fn claim<K: Ord>(
174
        remaining: &mut Vec<Self>,
175
        current: &[Self],
176
        accepted: &mut Accepted,
177
        key: impl Fn(&Self) -> K,
178
    ) {
179
        let mut budget = BTreeMap::<K, Vec<usize>>::new();
180
        for (index, identity) in remaining.iter().enumerate() {
181
            budget.entry(key(identity)).or_default().push(index);
182
        }
183
        let mut consumed = BTreeSet::new();
184
        for identity in current {
185
            if accepted.contains(identity) {
186
                continue;
187
            }
188
            let Some(index) = budget.get_mut(&key(identity)).and_then(Vec::pop) else {
189
                continue;
190
            };
191
            accepted.insert(identity.clone());
192
            consumed.insert(index);
193
        }
194
        let mut index = 0;
195
        remaining.retain(|_| {
196
            let keep = !consumed.contains(&index);
197
            index += 1;
198
            keep
199
        });
200
    }
201
}
202
203
/// Stable identity of a commit-level review decision.
204
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
205
struct CommitDecision {
206
    /// Stable identity of the commit's complete change.
207
    patch_id: PatchId,
208
    /// Occurrence of this patch id within the reviewed range.
209
    ordinal: u32,
210
}
211
212
impl CommitDecision {
213
    /// Decodes a commit id and decision identity from one state row.
214
    fn decode(row: &str) -> Option<(Oid, Self)> {
215
        let mut fields = row.split_whitespace();
216
        let commit = fields.next()?.parse().ok()?;
217
        let patch_id = PatchId::from_str(fields.next()?).ok()?;
218
        let ordinal = fields.next()?.parse().ok()?;
219
        if fields.next().is_some() {
220
            return None;
221
        }
222
        Some((commit, Self { patch_id, ordinal }))
223
    }
224
}
225
226
/// Authoritative accepted-hunk state for one review.
227
pub(crate) type Accepted = BTreeSet<AcceptedHunk>;
228
/// Authoritative rejected-commit state keyed by commit id.
229
type Rejected = BTreeMap<Oid, CommitDecision>;
230
/// Authoritative dropped-commit state keyed by commit id.
231
type Dropped = BTreeMap<Oid, CommitDecision>;
232
233
/// Persisted state for one resolved target of a selector-keyed review.
234
#[derive(Clone, Debug, Eq, PartialEq)]
235
struct PersistedState {
236
    /// Target commit whose hunks the accepted identities describe.
237
    target: Oid,
238
    /// Exact hunks accepted by the reviewer.
239
    accepted: Accepted,
240
    /// Commits rejected by the reviewer.
241
    rejected: Rejected,
242
    /// Commits dropped by the reviewer.
243
    dropped: Dropped,
244
}
245
246
impl PersistedState {
247
    /// Creates empty decisions for `target`.
248
    fn empty(target: Oid) -> Self {
249
        Self {
250
            target,
251
            accepted: Accepted::new(),
252
            rejected: Rejected::new(),
253
            dropped: Dropped::new(),
254
        }
255
    }
256
}
257
258
/// Accepted hunks of one file, ready to apply to the projected tree.
259
pub struct FilePatches {
260
    /// Every hunk of the file in one patch.
261
    pub combined: String,
262
    /// The same hunks as individual patches, used when `combined` fails.
263
    pub hunks: Vec<String>,
264
}
265
266
impl FilePatches {
267
    /// Builds combined and per-hunk patches for `hunks` of `file`.
268
    pub fn new(file: &FileDiff, hunks: Vec<Hunk>) -> Result<Self, Error> {
269
        if file.header.kind == FileKind::Binary {
270
            let patch = DiffDocument::for_hunks(file, []).to_unified_string()?;
271
            return Ok(Self {
272
                combined: patch.clone(),
273
                hunks: vec![patch],
274
            });
275
        }
276
        let individual = hunks
277
            .iter()
278
            .map(|hunk| DiffDocument::for_hunks(file, [hunk.clone()]).to_unified_string())
279
            .collect::<Result<Vec<_>, _>>()?;
280
        let combined = if file.header.kind == FileKind::Added && hunks.len() > 1 {
281
            let mut hunks = hunks.into_iter();
282
            let Some(mut combined) = hunks.next() else {
283
                return Err(Error::Git("added-file projection has no hunks".to_owned()));
284
            };
285
            for hunk in hunks {
286
                combined.lines.extend(hunk.lines);
287
            }
288
            for line in &mut combined.lines {
289
                if line.kind == DiffLineKind::Context {
290
                    line.kind = DiffLineKind::Addition;
291
                }
292
            }
293
            combined.header = HunkHeader {
294
                old_line_no: 0,
295
                old_size: 0,
296
                new_line_no: 1,
297
                new_size: combined.lines.iter().map(|line| line.kind.new_len()).sum(),
298
                text: String::new(),
299
            };
300
            vec![combined]
301
        } else {
302
            hunks
303
        };
304
305
        Ok(Self {
306
            combined: DiffDocument::for_hunks(file, combined).to_unified_string()?,
307
            hunks: individual,
308
        })
309
    }
310
}
311
312
/// Hunk identity data for one commit during acceptance reconciliation.
313
pub struct CommitHunks<'a> {
314
    /// Commit whose hunks are being reconciled.
315
    pub commit: Oid,
316
    /// Exact identity per decoded hunk, when the commit's diff is loaded.
317
    pub hunks: Option<&'a BTreeMap<HunkId, AcceptedHunk>>,
318
}
319
320
/// Final review state of one commit.
321
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
322
pub enum CommitReviewState {
323
    /// The commit still needs a final decision.
324
    #[default]
325
    Pending,
326
    /// Every reviewable change in the commit is accepted.
327
    Accepted,
328
    /// The reviewer rejected the commit.
329
    Rejected,
330
    /// The reviewer dropped the commit.
331
    Dropped,
332
}
333
334
/// Review state of one commit projected from the accepted set.
335
pub struct Reconciled {
336
    /// Accepted-line progress for the commit.
337
    pub progress: ReviewProgress,
338
    /// Final review state of the commit.
339
    pub state: CommitReviewState,
340
    /// Accepted hunks, for commits whose hunk patch ids were supplied.
341
    pub accepted: BTreeSet<HunkId>,
342
}
343
344
impl Reconciled {
345
    /// Projects persisted decisions onto commit-local hunk ids.
346
    fn for_commits(
347
        accepted_state: &Accepted,
348
        rejected_state: &Rejected,
349
        dropped_state: &Dropped,
350
        commits: &[CommitHunks<'_>],
351
    ) -> Vec<Self> {
352
        // Accepted and total line counts per commit let undecoded commits
353
        // retain their progress from persisted totals.
354
        let mut totals = BTreeMap::<Oid, (usize, u32)>::new();
355
        for identity in accepted_state {
356
            let entry = totals
357
                .entry(identity.commit)
358
                .or_insert((0, identity.commit_lines));
359
            entry.0 += identity.lines as usize;
360
        }
361
362
        let mut reconciled = Vec::with_capacity(commits.len());
363
        for commit in commits {
364
            let (progress, accepted) = match commit.hunks {
365
                Some(hunks) if hunks.is_empty() => (
366
                    // A hunkless binary or metadata-only change has no
367
                    // acceptance action, so its sole review unit is done.
368
                    ReviewProgress {
369
                        accepted: 1,
370
                        total: 1,
371
                    },
372
                    BTreeSet::new(),
373
                ),
374
                Some(hunks) => {
375
                    let mut progress = ReviewProgress::default();
376
                    let mut accepted = BTreeSet::new();
377
                    for (id, identity) in hunks {
378
                        let lines = identity.lines as usize;
379
                        progress.total += lines;
380
                        if accepted_state.contains(identity) {
381
                            progress.accepted += lines;
382
                            accepted.insert(*id);
383
                        }
384
                    }
385
                    (progress, accepted)
386
                }
387
                None => {
388
                    let progress = totals.get(&commit.commit).map_or_else(
389
                        ReviewProgress::default,
390
                        |(accepted, total)| ReviewProgress {
391
                            accepted: *accepted,
392
                            total: *total as usize,
393
                        },
394
                    );
395
                    (progress, BTreeSet::new())
396
                }
397
            };
398
            let state = if dropped_state.contains_key(&commit.commit) {
399
                CommitReviewState::Dropped
400
            } else if rejected_state.contains_key(&commit.commit) {
401
                CommitReviewState::Rejected
402
            } else if progress.is_complete() {
403
                CommitReviewState::Accepted
404
            } else {
405
                CommitReviewState::Pending
406
            };
407
            reconciled.push(Self {
408
                progress,
409
                state,
410
                accepted,
411
            });
412
        }
413
        reconciled
414
    }
415
}
416
417
/// Global and per-commit review status for the history view.
418
#[derive(Debug, Default)]
419
pub struct HistoryStatus {
420
    /// Accepted-line progress across the review.
421
    pub progress: ReviewProgress,
422
    /// Remaining diff from the accepted projection to the target.
423
    pub stats: DiffStat,
424
    /// Remaining review status keyed by commit.
425
    pub commits: BTreeMap<Oid, CommitStatus>,
426
}
427
428
/// Remaining review status for one commit.
429
#[derive(Debug, Default)]
430
pub struct CommitStatus {
431
    /// Accepted-line progress for the commit.
432
    pub progress: ReviewProgress,
433
    /// Final review state of the commit.
434
    pub state: CommitReviewState,
435
    /// Diff statistics from hunks that remain unaccepted.
436
    pub stats: DiffStat,
437
    /// Number of accepted hunks in the commit.
438
    pub accepted_hunks: usize,
439
    /// Total number of hunks in the commit.
440
    pub total_hunks: usize,
441
}
442
443
impl HistoryStatus {
444
    /// Calculates history status from identities cached by the session.
445
    pub(crate) fn for_commits(
446
        brain: &Brain,
447
        commits: &[(Oid, &DiffDocument, &BTreeMap<HunkId, AcceptedHunk>)],
448
    ) -> Self {
449
        let statuses = brain.commit_statuses(commits);
450
        let mut progress = ReviewProgress::default();
451
        let mut stats = DiffStat::default();
452
        for status in statuses.values() {
453
            if matches!(status.state, CommitReviewState::Dropped) {
454
                continue;
455
            }
456
            progress.accepted += status.progress.accepted;
457
            progress.total += status.progress.total;
458
            stats.files_changed += status.stats.files_changed;
459
            stats.insertions += status.stats.insertions;
460
            stats.deletions += status.stats.deletions;
461
        }
462
        Self {
463
            progress,
464
            stats,
465
            commits: statuses,
466
        }
467
    }
468
}
469
470
/// Stored status for one review identity.
471
#[derive(Clone, Debug, Eq, PartialEq)]
472
pub struct BrainStatus {
473
    /// Head name displayed to the user.
474
    pub head: String,
475
    /// Kind of review identity displayed in the head column.
476
    pub head_kind: BrainStatusHead,
477
    /// Brain state status for the review.
478
    pub state: BrainStatusState,
479
    /// Whether the stored base matches the current review base.
480
    pub base_state: BrainStatusBaseState,
481
    /// Accepted-line progress across the review.
482
    pub progress: ReviewProgress,
483
    /// Ahead and behind counts relative to the trunk branch.
484
    pub relation: AheadBehind,
485
    /// Merge status relative to the trunk branch.
486
    pub merge: MergeStatus,
487
    /// Comment storage status for this review.
488
    pub comments: CommentStatus,
489
    /// Head commit timestamp used to order status rows.
490
    pub recency: CommitTime,
491
}
492
493
/// Stored-base status for one review row.
494
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
495
pub enum BrainStatusBaseState {
496
    /// Stored state matches the current review base.
497
    Ok,
498
    /// Stored state was recorded on a different base and needs reset.
499
    Stale,
500
}
501
502
impl BrainStatusBaseState {
503
    /// Returns stored-base status relative to the current review base.
504
    fn from_base(stored: Oid, current: Oid) -> Self {
505
        if stored == current {
506
            Self::Ok
507
        } else {
508
            Self::Stale
509
        }
510
    }
511
}
512
513
/// Kind of review identity displayed in one status row.
514
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
515
pub enum BrainStatusHead {
516
    /// The review identity is a local branch name.
517
    Branch,
518
    /// The review identity is stored brain state that is not a local branch.
519
    Stored,
520
}
521
522
/// Brain state status for one review row.
523
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
524
pub enum BrainStatusState {
525
    /// Stored review state exists and all hunks are accepted.
526
    Approved,
527
    /// Stored review state exists but some hunks are not accepted.
528
    InReview,
529
    /// No stored review state exists.
530
    NoState,
531
}
532
533
/// Stored review state before it is joined to local branch rows.
534
struct StoredReview {
535
    /// Base commit recorded by the review state.
536
    base: Oid,
537
    /// Current base selector resolution, or stored base for an unresolved selector.
538
    current_base: Oid,
539
    /// Current target selector resolution, or stored target for an unresolved selector.
540
    current_target: Oid,
541
    /// Accepted-line progress across the review.
542
    progress: ReviewProgress,
543
    /// Comment storage status for this review.
544
    comments: CommentStatus,
545
    /// Head commit timestamp used to order status rows.
546
    recency: CommitTime,
547
    /// State commit timestamp used to choose between matching reviews.
548
    updated: CommitTime,
549
}
550
551
/// Persistent identity for one review, keyed by its range selectors.
552
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
553
struct ReviewIdentity {
554
    /// Base revision selector for the reviewed range.
555
    base: Rev,
556
    /// Target revision selector for the reviewed range.
557
    target: Rev,
558
}
559
560
impl ReviewIdentity {
561
    /// Creates an identity for a `base..target` review range.
562
    fn new(base: Rev, target: Rev) -> Self {
563
        Self { base, target }
564
    }
565
566
    /// Returns the table label for this review identity.
567
    fn label(&self) -> String {
568
        format!("{}..{}", self.base.as_str(), self.target.as_str())
569
    }
570
571
    /// Decodes a stored review identity from a state ref.
572
    ///
573
    /// Returns `None` for refs outside the `range/<base>/<target>` layout.
574
    fn from_ref(prefix: &Qualified<'_>, reference: &Qualified<'_>) -> Option<Self> {
575
        let review = reference.strip_prefix(prefix)?;
576
        let (base, target) = review.as_str().strip_prefix("range/")?.split_once('/')?;
577
        if base.is_empty() || target.is_empty() || target.contains('/') {
578
            return None;
579
        }
580
        let base = Rev::try_from(crate::comments::decode_component(base).as_str()).ok()?;
581
        let target = Rev::try_from(crate::comments::decode_component(target).as_str()).ok()?;
582
583
        Some(Self::new(base, target))
584
    }
585
}
586
587
/// Returns the user-facing label for `review`.
588
fn range_label(review: &ReviewIdentity) -> String {
589
    format!("{} .. {}", review.base.as_str(), review.target.as_str())
590
}
591
592
/// Encodes resolved-target metadata, accepted hunks, and rejected commits.
593
fn encode_state(state: &PersistedState) -> String {
594
    let target = state.target.to_string();
595
    let target = &target[..REVIEW_TARGET_ABBREVIATION_LEN];
596
    let mut message = format!(
597
        "Brain review {target}\n\n{STATE_SECTION}\ntarget {}\n",
598
        state.target
599
    );
600
    for (commit, decision) in &state.rejected {
601
        message.push_str(&format!(
602
            "reject {commit} {} {}\n",
603
            decision.patch_id, decision.ordinal
604
        ));
605
    }
606
    for (commit, decision) in &state.dropped {
607
        message.push_str(&format!(
608
            "drop {commit} {} {}\n",
609
            decision.patch_id, decision.ordinal
610
        ));
611
    }
612
    for hunk in &state.accepted {
613
        message.push_str(&format!(
614
            "{} {} {} {} {}\n",
615
            hunk.commit, hunk.patch_id, hunk.ordinal, hunk.lines, hunk.commit_lines
616
        ));
617
    }
618
    message
619
}
620
621
/// Decodes resolved-target metadata, accepted hunks, and rejected commits.
622
fn decode_state(message: &str) -> Option<PersistedState> {
623
    let (_, body) = message.split_once("\n\n")?;
624
    let mut body = body.strip_prefix(&format!("{STATE_SECTION}\n"))?.lines();
625
    let mut metadata = body.next()?.split_whitespace();
626
    if metadata.next()? != "target" {
627
        return None;
628
    }
629
    let target = metadata.next()?.parse().ok()?;
630
    if metadata.next().is_some() {
631
        return None;
632
    }
633
    let mut accepted = BTreeSet::new();
634
    let mut rejected = BTreeMap::new();
635
    let mut dropped = BTreeMap::new();
636
    let mut commit_totals = BTreeMap::new();
637
638
    for line in body.filter(|line| !line.trim().is_empty()) {
639
        if let Some(decision) = line.strip_prefix("reject ") {
640
            let (commit, decision) = CommitDecision::decode(decision)?;
641
            if rejected.insert(commit, decision).is_some() || dropped.contains_key(&commit) {
642
                return None;
643
            }
644
            continue;
645
        }
646
        if let Some(decision) = line.strip_prefix("drop ") {
647
            let (commit, decision) = CommitDecision::decode(decision)?;
648
            if dropped.insert(commit, decision).is_some() || rejected.contains_key(&commit) {
649
                return None;
650
            }
651
            continue;
652
        }
653
        let mut fields = line.split_whitespace();
654
        let commit = fields.next()?.parse().ok()?;
655
        let patch_id = fields.next()?;
656
        let ordinal = fields.next()?;
657
        let lines = fields.next()?;
658
        let commit_lines = fields.next()?;
659
        let patch_id = PatchId::from_str(patch_id).ok()?;
660
        let ordinal = ordinal.parse().ok()?;
661
        let (lines, commit_lines) = (lines.parse().ok()?, commit_lines.parse().ok()?);
662
        let hunk = AcceptedHunk {
663
            commit,
664
            patch_id,
665
            ordinal,
666
            lines,
667
            commit_lines,
668
        };
669
        if fields.next().is_some() || hunk.lines == 0 || hunk.commit_lines < hunk.lines {
670
            return None;
671
        }
672
        match commit_totals.entry(hunk.commit) {
673
            std::collections::btree_map::Entry::Vacant(entry) => {
674
                entry.insert(hunk.commit_lines);
675
            }
676
            std::collections::btree_map::Entry::Occupied(entry)
677
                if *entry.get() != hunk.commit_lines =>
678
            {
679
                return None;
680
            }
681
            std::collections::btree_map::Entry::Occupied(_) => {}
682
        }
683
        if !accepted.insert(hunk) {
684
            return None;
685
        }
686
    }
687
    Some(PersistedState {
688
        target,
689
        accepted,
690
        rejected,
691
        dropped,
692
    })
693
}
694
695
/// Commit hunk identity data used to summarize stored review progress.
696
struct SummaryCommit {
697
    /// Commit being summarized.
698
    commit: Commit,
699
    /// Exact accepted-state identity per hunk in the commit.
700
    identities: BTreeMap<HunkId, AcceptedHunk>,
701
}
702
703
/// Stored comment status for one review identity.
704
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
705
pub enum CommentStatus {
706
    /// No comment blob exists.
707
    None,
708
    /// Comment blob exists and contains this many rows.
709
    Count(usize),
710
    /// Comment blob exists but does not parse.
711
    Invalid,
712
}
713
714
/// A revision backend that lists the reviewed commits and their diffs.
715
///
716
/// The base and target revisions are resolved and stored when the backend is
717
/// constructed, so listing commits needs no further arguments.
718
pub trait Backend: Send {
719
    /// Returns the user-facing revision range under review.
720
    fn range_label(&self) -> String;
721
    /// Returns the reviewed commits in `base..target`, oldest first.
722
    fn commits(&self) -> Result<Vec<Commit>, Error>;
723
724
    /// Returns `commit`'s header.
725
    fn commit_header(&self, commit: Oid) -> Result<CommitHeader, Error>;
726
727
    /// Returns `commit`'s file diffs against its parent.
728
    fn file_diffs(&self, commit: Oid) -> Result<Vec<FileDiff>, Error>;
729
730
    /// Returns `commit`'s header and file diffs as one document.
731
    fn diff_document(&self, commit: Oid) -> Result<DiffDocument, Error> {
732
        Ok(DiffDocument {
733
            commit: Some(self.commit_header(commit)?),
734
            files: self.file_diffs(commit)?,
735
        })
736
    }
737
738
    /// Loads the hidden review state for this backend.
739
    fn brain(&self) -> Result<Brain, Error>;
740
741
    /// Resets and loads the hidden review state for this backend.
742
    fn reset_brain(&self) -> Result<Brain, Error>;
743
744
    /// Rebases and loads the hidden review state for this backend.
745
    fn rebase_brain(&self) -> Result<Brain, Error>;
746
747
    /// Returns a repo handle for widening `commit`'s hunk context.
748
    fn repo(&self, commit: &Commit) -> git::Repository;
749
}
750
751
impl dyn Backend {
752
    /// Returns a backend for `cwd` bound to the `base..target` range.
753
    ///
754
    /// A [`JJ_DIR`] directory in `cwd` or an ancestor selects the Jujutsu
755
    /// backend; otherwise Git is used.
756
    pub fn from_path(cwd: &Path, base: Rev, target: Rev) -> Result<Box<dyn Backend>, Error> {
757
        if is_jj_workspace(cwd) {
758
            let backend = JjBackend::new(cwd, base, target)?;
759
            Ok(Box::new(backend))
760
        } else {
761
            let backend = GitBackend::new(cwd, base, target)?;
762
            Ok(Box::new(backend))
763
        }
764
    }
765
}
766
767
/// Returns the branch point for the branch containing `target`.
768
pub fn branch_base(cwd: &Path, target: &Rev) -> Result<Rev, Error> {
769
    if is_jj_workspace(cwd) {
770
        let base = jj::Repository::new(cwd).branch_base(target)?;
771
        return Ok(Rev::from(base));
772
    }
773
    let repository = open_repository(cwd)?;
774
    let base = repository.branch_base(target)?.ok_or_else(|| {
775
        Error::Git(
776
            "could not infer a base for the target; supply an explicit base revision".to_owned(),
777
        )
778
    })?;
779
    Ok(Rev::from(base))
780
}
781
782
/// Returns stored review statuses for the repository containing `cwd`.
783
pub fn statuses(cwd: &Path) -> Result<Vec<BrainStatus>, Error> {
784
    if is_jj_workspace(cwd) {
785
        let jj = jj::Repository::new(cwd);
786
        let repository = jj.git_repository()?;
787
        let branches = jj
788
            .bookmarks()?
789
            .into_iter()
790
            .map(|(head, name)| {
791
                let time = repository.commit_time(head)?;
792
                Ok(Branch { name, head, time })
793
            })
794
            .collect::<Result<Vec<_>, Error>>()?;
795
        return Brain::statuses_for_branches(&repository, branches);
796
    }
797
    let repository = git::Repository::discover(cwd.to_path_buf())?;
798
    Brain::statuses(&repository)
799
}
800
801
/// Opens the Git repository backing the workspace containing `cwd`.
802
fn open_repository(cwd: &Path) -> Result<git::Repository, Error> {
803
    if is_jj_workspace(cwd) {
804
        Ok(jj::Repository::new(cwd).git_repository()?)
805
    } else {
806
        Ok(git::Repository::discover(cwd.to_path_buf())?)
807
    }
808
}
809
810
/// Returns whether `cwd` is inside a Jujutsu workspace.
811
fn is_jj_workspace(cwd: &Path) -> bool {
812
    cwd.ancestors().any(|path| path.join(JJ_DIR).is_dir())
813
}
814
815
/// Hidden Git state holding one review's decisions and comments.
816
///
817
/// Exact accepted-hunk identities and rejected commits are stored in the state
818
/// commit message. The commit tree is a best-effort content projection.
819
/// Comments are stored as a JSONL blob under a sibling ref. All state lives
820
/// inside the Git object store.
821
#[derive(Clone, Debug)]
822
pub struct Brain {
823
    /// Git command context.
824
    repository: git::Repository,
825
    /// Hidden ref storing the synthetic acceptance state commit.
826
    state_ref: Qualified<'static>,
827
    /// Hidden ref storing the review's comments blob.
828
    comments_ref: Qualified<'static>,
829
    /// Base commit used as the parent of synthetic state commits.
830
    base: Oid,
831
    /// Target commit whose hunks the accepted identities describe.
832
    target: Oid,
833
    /// Current synthetic state commit.
834
    commit: Oid,
835
    /// Exact hunks accepted by the reviewer.
836
    pub(crate) accepted: Accepted,
837
    /// Commits rejected by the reviewer.
838
    rejected: Rejected,
839
    /// Commits dropped by the reviewer.
840
    dropped: Dropped,
841
}
842
843
impl Brain {
844
    /// Creates a review state handle.
845
    fn new(
846
        repository: git::Repository,
847
        state_ref: Qualified<'static>,
848
        comments_ref: Qualified<'static>,
849
        base: Oid,
850
        commit: Oid,
851
        state: PersistedState,
852
    ) -> Self {
853
        let PersistedState {
854
            target,
855
            accepted,
856
            rejected,
857
            dropped,
858
        } = state;
859
        Self {
860
            repository,
861
            state_ref,
862
            comments_ref,
863
            base,
864
            target,
865
            commit,
866
            accepted,
867
            rejected,
868
            dropped,
869
        }
870
    }
871
872
    /// Returns the hidden Git ref prefix for `namespace`.
873
    fn prefix_for(namespace: &'static str) -> Result<Qualified<'static>, Error> {
874
        let category = component(BRAIN_REF_CATEGORY)?;
875
        let namespace = component(namespace)?;
876
877
        Ok(Qualified::from_components(category, namespace, []))
878
    }
879
880
    /// Returns the hidden Git ref for `identity` under `namespace`.
881
    fn ref_for_identity(
882
        namespace: &'static str,
883
        identity: &ReviewIdentity,
884
    ) -> Result<Qualified<'static>, Error> {
885
        let prefix = Brain::prefix_for(namespace)?;
886
        let range = component("range")?;
887
        let base = component(crate::comments::encode_component(identity.base.as_str()))?;
888
        let target = component(crate::comments::encode_component(identity.target.as_str()))?;
889
890
        Ok(prefix.join(range).join(base).join(target))
891
    }
892
893
    /// Returns stored review statuses for the repository's local branches.
894
    fn statuses(repository: &git::Repository) -> Result<Vec<BrainStatus>, Error> {
895
        let branches = repository.branches()?;
896
        Self::statuses_for_branches(repository, branches)
897
    }
898
899
    /// Returns stored review statuses joined to `branches`.
900
    fn statuses_for_branches(
901
        repository: &git::Repository,
902
        branches: Vec<Branch>,
903
    ) -> Result<Vec<BrainStatus>, Error> {
904
        if branches.is_empty() {
905
            return Ok(Vec::new());
906
        }
907
908
        let trunk = repository
909
            .trunk(&branches)?
910
            .ok_or_else(|| Error::Git("no trunk or master branch found".to_owned()))?;
911
        let trunk_rev = Rev::from(trunk.head);
912
        let mut stored = Brain::stored_reviews(repository)?;
913
        let mut statuses = Vec::new();
914
915
        for branch in &branches {
916
            let (relation, merge) = if branch.name == trunk.name {
917
                (AheadBehind::default(), MergeStatus::Clean)
918
            } else {
919
                relation_to_trunk(repository, &trunk_rev, &Rev::from(branch.head))?
920
            };
921
922
            let matched = stored
923
                .iter()
924
                .filter(|(_, stored)| {
925
                    stored.current_target == branch.head && stored.current_base == trunk.head
926
                })
927
                .max_by_key(|(_, stored)| stored.updated)
928
                .map(|(review, _)| review.clone());
929
930
            if let Some(review) = matched.and_then(|review| stored.remove(&review)) {
931
                statuses.push(Brain::status_for_stored(
932
                    branch.name.clone(),
933
                    BrainStatusHead::Branch,
934
                    trunk.head,
935
                    relation,
936
                    merge,
937
                    review,
938
                ));
939
            } else {
940
                statuses.push(BrainStatus {
941
                    head: branch.name.clone(),
942
                    head_kind: BrainStatusHead::Branch,
943
                    state: BrainStatusState::NoState,
944
                    base_state: BrainStatusBaseState::Ok,
945
                    progress: ReviewProgress::default(),
946
                    relation,
947
                    merge,
948
                    comments: CommentStatus::None,
949
                    recency: branch.time,
950
                });
951
            }
952
        }
953
954
        for (identity, stored) in stored {
955
            let target = Rev::from(stored.current_target);
956
            let (relation, merge) = relation_to_trunk(repository, &trunk_rev, &target)?;
957
            statuses.push(Brain::status_for_stored(
958
                identity.label(),
959
                BrainStatusHead::Stored,
960
                stored.current_base,
961
                relation,
962
                merge,
963
                stored,
964
            ));
965
        }
966
        statuses.sort_by(status_order);
967
968
        Ok(statuses)
969
    }
970
971
    /// Returns stored review state keyed by decoded review identity.
972
    fn stored_reviews(
973
        repository: &git::Repository,
974
    ) -> Result<BTreeMap<ReviewIdentity, StoredReview>, Error> {
975
        let prefix = Brain::prefix_for(STATE_REF_NAMESPACE)?;
976
        let mut reviews = BTreeMap::new();
977
978
        for (reference, state) in repository.refs(&prefix)? {
979
            let Some(identity) = ReviewIdentity::from_ref(&prefix, &reference) else {
980
                continue;
981
            };
982
            let base = repository.parent(state)?;
983
            let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, &identity)?;
984
            let message = repository.commit_message(state)?;
985
            let Some(persisted) = decode_state(&message) else {
986
                continue;
987
            };
988
            // Resolved selectors preserve moving-range semantics. When a selector
989
            // disappears, use the immutable range only while its target commit exists.
990
            let current_base = repository.commit_id(&identity.base).unwrap_or(base);
991
            let Ok(current_target) = repository
992
                .commit_id(&identity.target)
993
                .or_else(|_| repository.commit_id(&Rev::from(persisted.target)))
994
            else {
995
                continue;
996
            };
997
            let brain = Brain::new(
998
                repository.clone(),
999
                reference,
1000
                comments_ref,
1001
                base,
1002
                state,
1003
                persisted,
1004
            );
1005
            let comments = brain.comment_status()?;
1006
            let target = Rev::from(current_target);
1007
            let progress = brain.summary(&target)?.1;
1008
            let recency = repository.commit_time(current_target)?;
1009
            let updated = repository.commit_time(state)?;
1010
1011
            reviews.insert(
1012
                identity,
1013
                StoredReview {
1014
                    base,
1015
                    current_base,
1016
                    current_target,
1017
                    progress,
1018
                    comments,
1019
                    recency,
1020
                    updated,
1021
                },
1022
            );
1023
        }
1024
        Ok(reviews)
1025
    }
1026
1027
    /// Returns status for one stored review and branch relation.
1028
    fn status_for_stored(
1029
        head: String,
1030
        head_kind: BrainStatusHead,
1031
        current_base: Oid,
1032
        relation: AheadBehind,
1033
        merge: MergeStatus,
1034
        stored: StoredReview,
1035
    ) -> BrainStatus {
1036
        BrainStatus {
1037
            head,
1038
            head_kind,
1039
            state: brain_status_state(stored.progress),
1040
            base_state: BrainStatusBaseState::from_base(stored.base, current_base),
1041
            progress: stored.progress,
1042
            relation,
1043
            merge,
1044
            comments: stored.comments,
1045
            recency: stored.recency,
1046
        }
1047
    }
1048
1049
    /// Returns stored comment status for this review.
1050
    fn comment_status(&self) -> Result<CommentStatus, Error> {
1051
        let Some(text) = self.read_comments()? else {
1052
            return Ok(CommentStatus::None);
1053
        };
1054
        let status = match crate::comments::ReviewComments::parse(&text) {
1055
            Ok(comments) => CommentStatus::Count(comments.len()),
1056
            Err(_) => CommentStatus::Invalid,
1057
        };
1058
        Ok(status)
1059
    }
1060
1061
    /// Returns the target commit and accepted-line progress for this review.
1062
    ///
1063
    /// Progress is counted from changed lines in exact accepted-hunk identities.
1064
    fn summary(&self, target: &Rev) -> Result<(Oid, ReviewProgress), Error> {
1065
        let base = Rev::from(self.base);
1066
        let head = self.repository.commit_id(target)?;
1067
        let commits = self.summary_commits(&base, target)?;
1068
        let hunks = commits
1069
            .iter()
1070
            .map(|summary| CommitHunks {
1071
                commit: summary.commit.id,
1072
                hunks: Some(&summary.identities),
1073
            })
1074
            .collect::<Vec<_>>();
1075
        let reconciled = self.reconcile(&hunks);
1076
        let accepted = reconciled.iter().map(|state| state.progress.accepted).sum();
1077
        let total = reconciled.iter().map(|state| state.progress.total).sum();
1078
1079
        Ok((head, ReviewProgress { accepted, total }))
1080
    }
1081
1082
    /// Returns commits and exact hunk identities for status progress.
1083
    fn summary_commits(&self, base: &Rev, target: &Rev) -> Result<Vec<SummaryCommit>, Error> {
1084
        let commits = self
1085
            .repository
1086
            .commits(base, target)?
1087
            .into_iter()
1088
            .map(|(id, summary)| Commit {
1089
                id,
1090
                summary,
1091
                author: String::new(),
1092
                branches: Vec::new(),
1093
                recency: CommitTime::default(),
1094
                stats: DiffStat::default(),
1095
            });
1096
        let mut summaries = Vec::with_capacity(commits.len());
1097
1098
        for commit in commits {
1099
            let bytes = self.repository.commit_diff(commit.id)?;
1100
            let document = DiffDocument::decode_bytes(&bytes)?.split_hunks();
1101
            let identities = self.hunk_identities(&document, commit.id)?;
1102
            summaries.push(SummaryCommit { commit, identities });
1103
        }
1104
1105
        Ok(summaries)
1106
    }
1107
    /// Returns review progress and remaining statistics for cached commit identities.
1108
    fn commit_statuses(
1109
        &self,
1110
        commits: &[(Oid, &DiffDocument, &BTreeMap<HunkId, AcceptedHunk>)],
1111
    ) -> BTreeMap<Oid, CommitStatus> {
1112
        let hunks = commits
1113
            .iter()
1114
            .map(|(commit, _, identities)| CommitHunks {
1115
                commit: *commit,
1116
                hunks: Some(identities),
1117
            })
1118
            .collect::<Vec<_>>();
1119
        let reconciled = self.reconcile(&hunks);
1120
        commits
1121
            .iter()
1122
            .zip(reconciled)
1123
            .map(|((commit, document, identities), reconciled)| {
1124
                (
1125
                    *commit,
1126
                    CommitStatus {
1127
                        progress: reconciled.progress,
1128
                        state: reconciled.state,
1129
                        stats: commit_remaining_stats(document, &reconciled.accepted),
1130
                        accepted_hunks: reconciled.accepted.len(),
1131
                        total_hunks: identities.len(),
1132
                    },
1133
                )
1134
            })
1135
            .collect()
1136
    }
1137
1138
    /// Returns exact accepted-state identities in document order.
1139
    ///
1140
    /// `document` must be `commit`'s own split-hunk diff: the identities carry
1141
    /// `commit` verbatim and count its hunks, so passing a document from any
1142
    /// other commit yields identities that silently name the wrong change.
1143
    pub fn hunk_identities(
1144
        &self,
1145
        document: &DiffDocument,
1146
        commit: Oid,
1147
    ) -> Result<BTreeMap<HunkId, AcceptedHunk>, Error> {
1148
        let mut hunks = BTreeMap::new();
1149
        let mut commit_lines = 0u32;
1150
        for file in &document.files {
1151
            for hunk in &file.hunks {
1152
                let stats = hunk.stats();
1153
                let changed = stats.additions + stats.deletions;
1154
                let changed = usize::from(file.header.kind == FileKind::Binary).max(changed);
1155
                let lines = u32::try_from(changed)
1156
                    .map_err(|_| Error::Git("hunk contains too many changed lines".to_owned()))?;
1157
                commit_lines = commit_lines.checked_add(lines).ok_or_else(|| {
1158
                    Error::Git("commit contains too many changed lines".to_owned())
1159
                })?;
1160
                hunks.insert(hunk.id, lines);
1161
            }
1162
        }
1163
        let (ids, patches): (Vec<_>, Vec<_>) = hunk_identity_patches(document)?.into_iter().unzip();
1164
        let patch_ids = self.repository.patch_ids(&patches)?;
1165
        let mut seen = BTreeMap::<PatchId, u32>::new();
1166
        let mut identities = BTreeMap::new();
1167
1168
        for (id, patch_id) in ids.into_iter().zip(patch_ids) {
1169
            let ordinal = seen.entry(patch_id.clone()).or_default();
1170
            let lines = hunks
1171
                .get(&id)
1172
                .copied()
1173
                .ok_or_else(|| Error::Git(format!("hunk {id:?} has no diff statistics")))?;
1174
            let identity = AcceptedHunk {
1175
                commit,
1176
                patch_id,
1177
                ordinal: *ordinal,
1178
                lines,
1179
                commit_lines,
1180
            };
1181
            *ordinal += 1;
1182
            identities.insert(id, identity);
1183
        }
1184
        Ok(identities)
1185
    }
1186
1187
    /// Loads or initializes the hidden review state for one review.
1188
    fn load(
1189
        repository: git::Repository,
1190
        base: Oid,
1191
        target: Oid,
1192
        identity: &ReviewIdentity,
1193
    ) -> Result<Self, Error> {
1194
        let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?;
1195
        let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?;
1196
        let (commit, persisted) = match repository.optional_ref(&state_ref)? {
1197
            Some(existing) => {
1198
                let parent = repository.parent(existing)?;
1199
                if parent != base {
1200
                    return Err(Error::StaleReviewState);
1201
                }
1202
                let message = repository.commit_message(existing)?;
1203
                let persisted = decode_state(&message).ok_or(Error::InvalidReviewState)?;
1204
                if persisted.target != target {
1205
                    return Err(Error::StaleReviewState);
1206
                }
1207
                (existing, persisted)
1208
            }
1209
            None => {
1210
                let commit = Brain::fresh_state_commit(&repository, base, target)?;
1211
                repository.update_ref(&state_ref, commit)?;
1212
                let persisted = PersistedState::empty(target);
1213
                (commit, persisted)
1214
            }
1215
        };
1216
        Ok(Self::new(
1217
            repository,
1218
            state_ref,
1219
            comments_ref,
1220
            base,
1221
            commit,
1222
            persisted,
1223
        ))
1224
    }
1225
1226
    /// Replaces the hidden review state for one review and returns it.
1227
    fn reset(
1228
        repository: git::Repository,
1229
        base: Oid,
1230
        target: Oid,
1231
        identity: &ReviewIdentity,
1232
    ) -> Result<Self, Error> {
1233
        let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?;
1234
        let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?;
1235
        let commit = Brain::fresh_state_commit(&repository, base, target)?;
1236
        repository.update_ref_and_delete(&state_ref, commit, &comments_ref)?;
1237
1238
        Ok(Self::new(
1239
            repository,
1240
            state_ref,
1241
            comments_ref,
1242
            base,
1243
            commit,
1244
            PersistedState::empty(target),
1245
        ))
1246
    }
1247
1248
    /// Carries accepted hunks from stored state onto the current review range.
1249
    fn rebase(
1250
        repository: git::Repository,
1251
        base: Oid,
1252
        target: Oid,
1253
        identity: &ReviewIdentity,
1254
        commits: &[Commit],
1255
        documents: &[DiffDocument],
1256
    ) -> Result<Self, Error> {
1257
        let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?;
1258
        let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?;
1259
        let (stored, old_base) = match repository.optional_ref(&state_ref)? {
1260
            Some(existing) => {
1261
                let parent = repository.parent(existing)?;
1262
                let message = repository.commit_message(existing)?;
1263
                let persisted = decode_state(&message).ok_or(Error::InvalidReviewState)?;
1264
                if parent == base && persisted.target == target {
1265
                    return Ok(Self::new(
1266
                        repository,
1267
                        state_ref,
1268
                        comments_ref,
1269
                        base,
1270
                        existing,
1271
                        persisted,
1272
                    ));
1273
                }
1274
                (persisted, parent)
1275
            }
1276
            None => (PersistedState::empty(target), base),
1277
        };
1278
        let commit_map = repository.range_diff(old_base, stored.target, base, target)?;
1279
        let commit = Brain::fresh_state_commit(&repository, base, target)?;
1280
        repository.update_ref(&state_ref, commit)?;
1281
        let mut brain = Self::new(
1282
            repository,
1283
            state_ref,
1284
            comments_ref,
1285
            base,
1286
            commit,
1287
            PersistedState::empty(target),
1288
        );
1289
        brain.remap(
1290
            commits,
1291
            documents,
1292
            &stored.accepted,
1293
            &stored.rejected,
1294
            &stored.dropped,
1295
            &commit_map,
1296
        )?;
1297
        if let Some(text) = brain.read_comments()? {
1298
            let mut comments = ReviewComments::parse(&text)?;
1299
            comments.remap_commits(&commit_map);
1300
            brain.write_comments(&comments.encode())?;
1301
        }
1302
1303
        Ok(brain)
1304
    }
1305
1306
    /// Creates an empty accepted-state commit for one resolved review range.
1307
    fn fresh_state_commit(
1308
        repository: &git::Repository,
1309
        base: Oid,
1310
        target: Oid,
1311
    ) -> Result<Oid, Error> {
1312
        let tree = repository.tree_id(base)?;
1313
        let state = PersistedState::empty(target);
1314
        let fresh = repository.commit(
1315
            tree,
1316
            base,
1317
            "brain",
1318
            "brain@example.invalid",
1319
            &encode_state(&state),
1320
        )?;
1321
1322
        Ok(fresh)
1323
    }
1324
1325
    /// Computes the stable Git patch id for `patch` text.
1326
    pub fn patch_id(&self, patch: &str) -> Result<PatchId, Error> {
1327
        let patch_id = self.repository.patch_id(patch)?;
1328
        Ok(patch_id)
1329
    }
1330
1331
    /// Computes the stable Git patch id for one hunk of `file`.
1332
    pub fn hunk_patch_id(&self, file: &FileDiff, hunk: &Hunk) -> Result<PatchId, Error> {
1333
        let patch = hunk_identity_patch(file, hunk)?;
1334
        self.patch_id(&patch)
1335
    }
1336
1337
    /// Reads one source blob for file metadata derived from complete contents.
1338
    pub fn read_blob(&self, oid: Oid) -> Result<Vec<u8>, Error> {
1339
        Ok(self.repository.cat_blob(oid)?)
1340
    }
1341
1342
    /// Reads the review's persisted comments blob, if any.
1343
    pub fn read_comments(&self) -> Result<Option<String>, Error> {
1344
        let Some(blob) = self.repository.optional_ref(&self.comments_ref)? else {
1345
            return Ok(None);
1346
        };
1347
        let bytes = self.repository.cat_blob(blob)?;
1348
        Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
1349
    }
1350
1351
    /// Persists the review's comments blob.
1352
    pub fn write_comments(&self, text: &str) -> Result<(), Error> {
1353
        let blob = self.repository.write_blob(text.as_bytes())?;
1354
        self.repository.update_ref(&self.comments_ref, blob)?;
1355
        Ok(())
1356
    }
1357
1358
    /// Rolls back accepted-hunk state without writing it to the repository.
1359
    pub(crate) fn rollback(&mut self, accepted: Accepted) {
1360
        self.accepted = accepted;
1361
    }
1362
1363
    /// Marks hunks accepted and updates the derived tree.
1364
    pub fn accept(
1365
        &mut self,
1366
        hunks: impl IntoIterator<Item = AcceptedHunk>,
1367
        files: impl IntoIterator<Item = FilePatches>,
1368
    ) -> Result<(), Error> {
1369
        let mut accepted = self.accepted.clone();
1370
        let mut rejected = self.rejected.clone();
1371
        let mut dropped = self.dropped.clone();
1372
        for hunk in hunks {
1373
            rejected.remove(&hunk.commit);
1374
            dropped.remove(&hunk.commit);
1375
            accepted.insert(hunk);
1376
        }
1377
        let mut tree = self.repository.tree_id(self.base)?;
1378
        for file in files {
1379
            tree = self.project_file(tree, &file)?;
1380
        }
1381
        self.persist(tree, accepted, rejected, dropped)
1382
    }
1383
1384
    /// Marks exact hunks unaccepted and rebuilds the derived tree.
1385
    pub fn reject(
1386
        &mut self,
1387
        rejected: &BTreeSet<AcceptedHunk>,
1388
        files: impl IntoIterator<Item = FilePatches>,
1389
    ) -> Result<(), Error> {
1390
        let mut accepted = self.accepted.clone();
1391
        accepted.retain(|hunk| !rejected.contains(hunk));
1392
        let mut tree = self.repository.tree_id(self.base)?;
1393
        for file in files {
1394
            tree = self.project_file(tree, &file)?;
1395
        }
1396
        self.persist(tree, accepted, self.rejected.clone(), self.dropped.clone())
1397
    }
1398
1399
    /// Toggles the rejected state of one commit.
1400
    pub fn toggle_commit_rejected(&mut self, commit: Oid) -> Result<(), Error> {
1401
        let mut rejected = self.rejected.clone();
1402
        let mut dropped = self.dropped.clone();
1403
        if rejected.remove(&commit).is_none() {
1404
            let decision = self.commit_decision(commit)?;
1405
            rejected.insert(commit, decision);
1406
            dropped.remove(&commit);
1407
        }
1408
        let tree = self.repository.tree_id(self.commit)?;
1409
        self.persist(tree, self.accepted.clone(), rejected, dropped)
1410
    }
1411
1412
    /// Toggles the dropped state of one commit.
1413
    pub fn toggle_commit_dropped(&mut self, commit: Oid) -> Result<(), Error> {
1414
        let mut rejected = self.rejected.clone();
1415
        let mut dropped = self.dropped.clone();
1416
        if dropped.remove(&commit).is_none() {
1417
            let decision = self.commit_decision(commit)?;
1418
            dropped.insert(commit, decision);
1419
            rejected.remove(&commit);
1420
        }
1421
        let tree = self.repository.tree_id(self.commit)?;
1422
        self.persist(tree, self.accepted.clone(), rejected, dropped)
1423
    }
1424
1425
    /// Applies `patch` to `tree`, keeping `tree` when it does not apply.
1426
    ///
1427
    /// The tree is only a content projection of the accepted set, so a hunk
1428
    /// that depends on an unaccepted one is skipped instead of failing the
1429
    /// update. Every other Git failure is real and propagates.
1430
    fn project(&self, tree: Oid, patch: &str) -> Result<Oid, Error> {
1431
        match self.repository.apply_patch_to_tree(tree, patch) {
1432
            Ok(next) => Ok(next),
1433
            Err(rustik_repo::RepoError::PatchApply(_)) => Ok(tree),
1434
            Err(error) => Err(error.into()),
1435
        }
1436
    }
1437
1438
    /// Computes the stable patch id for a commit's complete change.
1439
    fn commit_patch_id(&self, commit: Oid) -> Result<PatchId, Error> {
1440
        let diff = self.repository.commit_diff(commit)?;
1441
        let document = DiffDocument::decode_bytes(&diff)?;
1442
        self.repository
1443
            .patch_id(&document.to_unified_string()?)
1444
            .map_err(Error::from)
1445
    }
1446
1447
    /// Computes the stable decision identity for one commit in this range.
1448
    fn commit_decision(&self, commit: Oid) -> Result<CommitDecision, Error> {
1449
        let patch_id = self.commit_patch_id(commit)?;
1450
        let commits = self
1451
            .repository
1452
            .commits(&Rev::from(self.base), &Rev::from(self.target))?;
1453
        let mut ordinal = 0;
1454
        for (candidate, _) in commits {
1455
            if candidate == commit {
1456
                return Ok(CommitDecision { patch_id, ordinal });
1457
            }
1458
            if self.commit_patch_id(candidate)? == patch_id {
1459
                ordinal += 1;
1460
            }
1461
        }
1462
        Err(Error::Git(format!(
1463
            "commit {commit} is outside the reviewed range"
1464
        )))
1465
    }
1466
1467
    /// Applies one file's accepted hunks to `tree`.
1468
    ///
1469
    /// The combined patch is tried first so a file costs one `git apply`; only
1470
    /// when it fails are the hunks replayed individually, so one hunk that no
1471
    /// longer applies cannot drop the rest of its file from the projection.
1472
    fn project_file(&self, tree: Oid, file: &FilePatches) -> Result<Oid, Error> {
1473
        match self.repository.apply_patch_to_tree(tree, &file.combined) {
1474
            Ok(next) => return Ok(next),
1475
            Err(rustik_repo::RepoError::PatchApply(_)) => {}
1476
            Err(error) => return Err(error.into()),
1477
        }
1478
        let mut tree = tree;
1479
        for patch in &file.hunks {
1480
            tree = self.project(tree, patch)?;
1481
        }
1482
        Ok(tree)
1483
    }
1484
1485
    /// Remaps commit-level decisions by exact id, then stable decision identity.
1486
    fn remap_commit_decisions(
1487
        &self,
1488
        commits: &[Commit],
1489
        documents: &[DiffDocument],
1490
        stored_rejected: &Rejected,
1491
        stored_dropped: &Dropped,
1492
    ) -> Result<(Rejected, Dropped), Error> {
1493
        let current = commits
1494
            .iter()
1495
            .map(|commit| commit.id)
1496
            .collect::<BTreeSet<_>>();
1497
        let rejected_identities = stored_rejected
1498
            .iter()
1499
            .filter(|(commit, _)| !current.contains(commit))
1500
            .map(|(_, decision)| decision.clone())
1501
            .collect::<BTreeSet<_>>();
1502
        let dropped_identities = stored_dropped
1503
            .iter()
1504
            .filter(|(commit, _)| !current.contains(commit))
1505
            .map(|(_, decision)| decision.clone())
1506
            .collect::<BTreeSet<_>>();
1507
        let mut rejected = Rejected::new();
1508
        let mut dropped = Dropped::new();
1509
        let mut seen = BTreeMap::<PatchId, u32>::new();
1510
        for (commit, document) in commits.iter().zip(documents) {
1511
            let patch_id = self.repository.patch_id(&document.to_unified_string()?)?;
1512
            let ordinal = seen.entry(patch_id.clone()).or_default();
1513
            let identity = CommitDecision {
1514
                patch_id,
1515
                ordinal: *ordinal,
1516
            };
1517
            *ordinal += 1;
1518
            if stored_rejected.contains_key(&commit.id) || rejected_identities.contains(&identity) {
1519
                rejected.insert(commit.id, identity);
1520
            } else if stored_dropped.contains_key(&commit.id)
1521
                || dropped_identities.contains(&identity)
1522
            {
1523
                dropped.insert(commit.id, identity);
1524
            }
1525
        }
1526
        Ok((rejected, dropped))
1527
    }
1528
1529
    /// Remaps accepted and commit-level decisions onto a moved range.
1530
    fn remap(
1531
        &mut self,
1532
        commits: &[Commit],
1533
        documents: &[DiffDocument],
1534
        stored: &Accepted,
1535
        stored_rejected: &Rejected,
1536
        stored_dropped: &Dropped,
1537
        commit_map: &BTreeMap<Oid, Oid>,
1538
    ) -> Result<(), Error> {
1539
        debug_assert_eq!(commits.len(), documents.len(), "one document per commit");
1540
1541
        // Hunks of the moved range in range order, grouped by file so the
1542
        // projection can apply a whole file at once.
1543
        let mut current = Vec::new();
1544
        for (commit, document) in commits.iter().zip(documents) {
1545
            let identities = self.hunk_identities(document, commit.id)?;
1546
            for file in &document.files {
1547
                let hunks = file
1548
                    .hunks
1549
                    .iter()
1550
                    .filter_map(|hunk| Some((identities.get(&hunk.id)?.clone(), hunk.clone())))
1551
                    .collect::<Vec<_>>();
1552
                current.push((file, hunks));
1553
            }
1554
        }
1555
1556
        let identities = current
1557
            .iter()
1558
            .flat_map(|(_, hunks)| hunks.iter().map(|(identity, _)| identity));
1559
        let accepted = AcceptedHunk::remap(stored, identities, commit_map);
1560
1561
        let mut tree = self.repository.tree_id(self.base)?;
1562
        for (file, hunks) in current {
1563
            let hunks = hunks
1564
                .into_iter()
1565
                .filter(|(identity, _)| accepted.contains(identity))
1566
                .map(|(_, hunk)| hunk)
1567
                .collect::<Vec<_>>();
1568
            if hunks.is_empty() {
1569
                continue;
1570
            }
1571
            tree = self.project_file(tree, &FilePatches::new(file, hunks)?)?;
1572
        }
1573
        let (rejected, dropped) =
1574
            self.remap_commit_decisions(commits, documents, stored_rejected, stored_dropped)?;
1575
        self.persist(tree, accepted, rejected, dropped)
1576
    }
1577
1578
    /// Persists review decisions and the derived tree in one commit.
1579
    fn persist(
1580
        &mut self,
1581
        tree: Oid,
1582
        accepted: Accepted,
1583
        rejected: Rejected,
1584
        dropped: Dropped,
1585
    ) -> Result<(), Error> {
1586
        let state = PersistedState {
1587
            target: self.target,
1588
            accepted,
1589
            rejected,
1590
            dropped,
1591
        };
1592
        let message = encode_state(&state);
1593
        let commit =
1594
            self.repository
1595
                .commit(tree, self.base, "brain", "brain@example.invalid", &message)?;
1596
        self.repository.update_ref(&self.state_ref, commit)?;
1597
        self.commit = commit;
1598
        self.accepted = state.accepted;
1599
        self.rejected = state.rejected;
1600
        self.dropped = state.dropped;
1601
1602
        Ok(())
1603
    }
1604
1605
    /// Projects exact acceptance onto the current commit list.
1606
    pub fn reconcile(&self, commits: &[CommitHunks<'_>]) -> Vec<Reconciled> {
1607
        Reconciled::for_commits(&self.accepted, &self.rejected, &self.dropped, commits)
1608
    }
1609
}
1610
1611
/// Returns statistics for the unaccepted hunks in `document`.
1612
pub fn commit_remaining_stats(document: &DiffDocument, accepted: &BTreeSet<HunkId>) -> DiffStat {
1613
    let mut stats = DiffStat::default();
1614
    for file in &document.files {
1615
        let mut remaining = false;
1616
        for hunk in &file.hunks {
1617
            if accepted.contains(&hunk.id) {
1618
                continue;
1619
            }
1620
            remaining = true;
1621
            let hunk = hunk.stats();
1622
            stats.insertions += hunk.additions;
1623
            stats.deletions += hunk.deletions;
1624
        }
1625
        stats.files_changed += usize::from(remaining);
1626
    }
1627
    stats
1628
}
1629
1630
/// Returns the patch text used to identify `hunk` across base movement.
1631
fn hunk_identity_patch(file: &FileDiff, hunk: &Hunk) -> Result<String, Error> {
1632
    let hunks = (file.header.kind != FileKind::Binary).then(|| hunk.identity());
1633
    Ok(DiffDocument::for_hunks(file, hunks).to_unified_string()?)
1634
}
1635
1636
/// Returns each hunk's id and identity patch text, in document order.
1637
fn hunk_identity_patches(document: &DiffDocument) -> Result<Vec<(HunkId, String)>, Error> {
1638
    let mut patches = Vec::new();
1639
    for file in &document.files {
1640
        for hunk in &file.hunks {
1641
            patches.push((hunk.id, hunk_identity_patch(file, hunk)?));
1642
        }
1643
    }
1644
    Ok(patches)
1645
}
1646
1647
/// Returns trunk relation and merge status for `target`.
1648
///
1649
/// A branch that is only ahead or only behind merges trivially, so the merge
1650
/// check only runs for diverged branches.
1651
fn relation_to_trunk(
1652
    repository: &git::Repository,
1653
    trunk_rev: &Rev,
1654
    target: &Rev,
1655
) -> Result<(AheadBehind, MergeStatus), Error> {
1656
    let relation = repository.ahead_behind(trunk_rev, target)?;
1657
    let merge = if relation.ahead > 0 && relation.behind > 0 {
1658
        repository.merge_status(trunk_rev, target)?
1659
    } else {
1660
        MergeStatus::Clean
1661
    };
1662
1663
    Ok((relation, merge))
1664
}
1665
1666
/// Orders status rows by review progress, comments, recency, and name.
1667
fn status_order(left: &BrainStatus, right: &BrainStatus) -> Ordering {
1668
    left.progress
1669
        .cmp(&right.progress)
1670
        .then_with(|| right.comments.cmp(&left.comments))
1671
        .then_with(|| right.recency.cmp(&left.recency))
1672
        .then_with(|| left.head.cmp(&right.head))
1673
}
1674
1675
/// Returns the row status for stored review progress.
1676
fn brain_status_state(progress: ReviewProgress) -> BrainStatusState {
1677
    if progress.is_complete() {
1678
        BrainStatusState::Approved
1679
    } else {
1680
        BrainStatusState::InReview
1681
    }
1682
}
1683
1684
/// Converts `input` to a slash-free refname component.
1685
fn component(input: impl Into<String>) -> Result<Component<'static>, Error> {
1686
    let refname = RefString::try_from(input.into())
1687
        .map_err(|error| Error::Git(format!("invalid brain ref component: {error}")))?;
1688
    Component::from_refstr(refname)
1689
        .ok_or_else(|| Error::Git("invalid brain ref component: contains slash".to_owned()))
1690
}
1691
1692
/// A [`Backend`] backed by the `git` command.
1693
pub struct GitBackend {
1694
    /// Git repository operations.
1695
    repository: git::Repository,
1696
    /// Reviewed range identity.
1697
    review: ReviewIdentity,
1698
}
1699
1700
impl GitBackend {
1701
    /// Creates a Git backend reviewing `base..target` in `cwd`.
1702
    fn new(cwd: &Path, base: Rev, target: Rev) -> Result<Self, Error> {
1703
        let repository = git::Repository::discover(cwd.to_path_buf())?;
1704
        Ok(Self {
1705
            repository,
1706
            review: ReviewIdentity::new(base, target),
1707
        })
1708
    }
1709
}
1710
1711
impl Backend for GitBackend {
1712
    fn range_label(&self) -> String {
1713
        range_label(&self.review)
1714
    }
1715
1716
    fn commits(&self) -> Result<Vec<Commit>, Error> {
1717
        let pairs = self
1718
            .repository
1719
            .commits(&self.review.base, &self.review.target)?;
1720
        let branches = self
1721
            .repository
1722
            .branches()?
1723
            .into_iter()
1724
            .map(|branch| (branch.head, branch.name));
1725
        Commit::with_stats(&self.repository, pairs, branches)
1726
    }
1727
1728
    fn commit_header(&self, commit: Oid) -> Result<CommitHeader, Error> {
1729
        let bytes = self.repository.commit_header(commit)?;
1730
        let document = DiffDocument::decode_bytes(&bytes)?;
1731
        document
1732
            .commit
1733
            .ok_or_else(|| Error::Git(format!("commit {commit} has no header")))
1734
    }
1735
1736
    fn file_diffs(&self, commit: Oid) -> Result<Vec<FileDiff>, Error> {
1737
        let bytes = self.repository.commit_diff(commit)?;
1738
        Ok(DiffDocument::decode_bytes(&bytes)?.files)
1739
    }
1740
1741
    fn brain(&self) -> Result<Brain, Error> {
1742
        let base = self.repository.commit_id(&self.review.base)?;
1743
        let target = self.repository.commit_id(&self.review.target)?;
1744
        Brain::load(self.repository.clone(), base, target, &self.review)
1745
    }
1746
1747
    fn reset_brain(&self) -> Result<Brain, Error> {
1748
        let base = self.repository.commit_id(&self.review.base)?;
1749
        let target = self.repository.commit_id(&self.review.target)?;
1750
        Brain::reset(self.repository.clone(), base, target, &self.review)
1751
    }
1752
1753
    fn rebase_brain(&self) -> Result<Brain, Error> {
1754
        let base = self.repository.commit_id(&self.review.base)?;
1755
        let target = self.repository.commit_id(&self.review.target)?;
1756
        let commits = self.commits()?;
1757
        let documents = commits
1758
            .iter()
1759
            .map(|commit| Ok(self.diff_document(commit.id)?.split_hunks()))
1760
            .collect::<Result<Vec<_>, Error>>()?;
1761
        Brain::rebase(
1762
            self.repository.clone(),
1763
            base,
1764
            target,
1765
            &self.review,
1766
            &commits,
1767
            &documents,
1768
        )
1769
    }
1770
1771
    fn repo(&self, commit: &Commit) -> git::Repository {
1772
        self.repository.with_selector_args(commit.selectors())
1773
    }
1774
}
1775
1776
/// A [`Backend`] backed by the `jj` command.
1777
pub struct JjBackend {
1778
    /// Jujutsu workspace handle.
1779
    jj: jj::Repository,
1780
    /// Embedded Git repository, used for stats and review state.
1781
    repository: git::Repository,
1782
    /// Reviewed range identity.
1783
    review: ReviewIdentity,
1784
}
1785
1786
impl JjBackend {
1787
    /// Creates a Jujutsu backend reviewing `base..target` in `cwd`.
1788
    fn new(cwd: &Path, base: Rev, target: Rev) -> Result<Self, Error> {
1789
        let jj = jj::Repository::new(cwd);
1790
        let repository = jj.git_repository()?;
1791
        Ok(Self {
1792
            jj,
1793
            repository,
1794
            review: ReviewIdentity::new(base, target),
1795
        })
1796
    }
1797
1798
    /// Resolves either a Jujutsu revset or a Git revision.
1799
    fn resolve(&self, revision: &Rev) -> Result<Oid, Error> {
1800
        match self.jj.resolve(revision) {
1801
            Ok(commit) => Ok(commit),
1802
            Err(_) => Ok(self.repository.commit_id(revision)?),
1803
        }
1804
    }
1805
}
1806
1807
impl Backend for JjBackend {
1808
    fn range_label(&self) -> String {
1809
        range_label(&self.review)
1810
    }
1811
1812
    fn commits(&self) -> Result<Vec<Commit>, Error> {
1813
        let base = Rev::from(self.resolve(&self.review.base)?);
1814
        let target = Rev::from(self.resolve(&self.review.target)?);
1815
        let commits = self.jj.commits(&base, &target)?;
1816
        let bookmarks = self.jj.bookmarks()?;
1817
        Commit::with_stats(&self.repository, commits, bookmarks)
1818
    }
1819
1820
    fn commit_header(&self, commit: Oid) -> Result<CommitHeader, Error> {
1821
        let bytes = self.repository.commit_header(commit)?;
1822
        let document = DiffDocument::decode_bytes(&bytes)?;
1823
        document
1824
            .commit
1825
            .ok_or_else(|| Error::Git(format!("commit {commit} has no header")))
1826
    }
1827
1828
    fn file_diffs(&self, commit: Oid) -> Result<Vec<FileDiff>, Error> {
1829
        let bytes = self.jj.commit_diff(commit)?;
1830
        Ok(DiffDocument::decode_bytes(&bytes)?.files)
1831
    }
1832
1833
    fn brain(&self) -> Result<Brain, Error> {
1834
        let base = self.resolve(&self.review.base)?;
1835
        let target = self.resolve(&self.review.target)?;
1836
        Brain::load(self.repository.clone(), base, target, &self.review)
1837
    }
1838
1839
    fn reset_brain(&self) -> Result<Brain, Error> {
1840
        let base = self.resolve(&self.review.base)?;
1841
        let target = self.resolve(&self.review.target)?;
1842
        Brain::reset(self.repository.clone(), base, target, &self.review)
1843
    }
1844
1845
    fn rebase_brain(&self) -> Result<Brain, Error> {
1846
        let base = self.resolve(&self.review.base)?;
1847
        let target = self.resolve(&self.review.target)?;
1848
        let commits = self.commits()?;
1849
        let documents = commits
1850
            .iter()
1851
            .map(|commit| Ok(self.diff_document(commit.id)?.split_hunks()))
1852
            .collect::<Result<Vec<_>, Error>>()?;
1853
        Brain::rebase(
1854
            self.repository.clone(),
1855
            base,
1856
            target,
1857
            &self.review,
1858
            &commits,
1859
            &documents,
1860
        )
1861
    }
1862
1863
    fn repo(&self, commit: &Commit) -> git::Repository {
1864
        self.repository.with_selector_args(commit.selectors())
1865
    }
1866
}
1867
1868
#[cfg(test)]
1869
mod tests {
1870
    use super::*;
1871
    use std::fs;
1872
    use std::process::Command;
1873
    use std::time::{SystemTime, UNIX_EPOCH};
1874
1875
    /// Temporary Git repository removed when its test finishes.
1876
    struct TestRepository {
1877
        /// Repository working tree.
1878
        path: std::path::PathBuf,
1879
    }
1880
1881
    impl TestRepository {
1882
        /// Creates a repository with `main` as its initial branch.
1883
        fn new() -> Self {
1884
            let nonce = SystemTime::now()
1885
                .duration_since(UNIX_EPOCH)
1886
                .unwrap()
1887
                .as_nanos();
1888
1889
            let path = std::env::temp_dir().join(format!(
1890
                "rustik-brain-rebase-{}-{nonce}",
1891
                std::process::id()
1892
            ));
1893
            fs::create_dir(&path).unwrap();
1894
            let repository = Self { path };
1895
            repository.git(&["init", "-q", "-b", "main"]);
1896
            repository.git(&["config", "user.name", "Rustik Test"]);
1897
            repository.git(&["config", "user.email", "rustik@example.invalid"]);
1898
            repository
1899
        }
1900
1901
        /// Creates a topic containing the same patch before and after a revert.
1902
        fn with_duplicate_patch_commits() -> Self {
1903
            let repository = Self::new();
1904
            let reviewed = repository.path.join("reviewed.txt");
1905
            fs::write(&reviewed, "base\n").unwrap();
1906
            repository.git(&["add", "reviewed.txt"]);
1907
            repository.git(&["commit", "-q", "-m", "base"]);
1908
            repository.git(&["switch", "-q", "-c", "topic"]);
1909
            fs::write(&reviewed, "decision\n").unwrap();
1910
            repository.git(&["commit", "-q", "-am", "first"]);
1911
            repository.git(&["revert", "--no-edit", "HEAD"]);
1912
            fs::write(&reviewed, "decision\n").unwrap();
1913
            repository.git(&["commit", "-q", "-am", "second"]);
1914
            repository
1915
        }
1916
1917
        /// Runs a Git command and requires success.
1918
        fn git(&self, args: &[&str]) {
1919
            let status = Command::new("git")
1920
                .args(args)
1921
                .current_dir(&self.path)
1922
                .status()
1923
                .unwrap();
1924
            assert!(status.success());
1925
        }
1926
        /// Runs a Git command and returns its standard output.
1927
        fn git_output(&self, args: &[&str]) -> Vec<u8> {
1928
            let output = Command::new("git")
1929
                .args(args)
1930
                .current_dir(&self.path)
1931
                .output()
1932
                .unwrap();
1933
            assert!(output.status.success());
1934
            output.stdout
1935
        }
1936
        /// Runs a Jujutsu command and requires success.
1937
        fn jj(&self, args: &[&str]) {
1938
            let status = Command::new("jj")
1939
                .args(args)
1940
                .current_dir(&self.path)
1941
                .status()
1942
                .unwrap();
1943
            assert!(status.success());
1944
        }
1945
1946
        /// Returns the fixture working tree.
1947
        fn path(&self) -> &std::path::Path {
1948
            &self.path
1949
        }
1950
    }
1951
1952
    impl Drop for TestRepository {
1953
        fn drop(&mut self) {
1954
            fs::remove_dir_all(&self.path).unwrap();
1955
        }
1956
    }
1957
1958
    #[test]
1959
    fn reset_clears_persisted_comments() {
1960
        let repository = TestRepository::new();
1961
        repository.git(&["commit", "-q", "--allow-empty", "-m", "base"]);
1962
        repository.git(&["switch", "-q", "-c", "topic"]);
1963
        repository.git(&["commit", "-q", "--allow-empty", "-m", "target"]);
1964
        let base = Rev::try_from("main").unwrap();
1965
        let target = Rev::try_from("topic").unwrap();
1966
        let backend = GitBackend::new(repository.path(), base, target).unwrap();
1967
        let comments = r#"{"id":1,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","body":"comment"}"#;
1968
        let brain = backend.reset_brain().unwrap();
1969
        brain.write_comments(comments).unwrap();
1970
1971
        let loaded = backend.brain().unwrap();
1972
        assert_eq!(loaded.read_comments().unwrap().as_deref(), Some(comments));
1973
1974
        let rebased = backend.rebase_brain().unwrap();
1975
        assert_eq!(rebased.read_comments().unwrap().as_deref(), Some(comments));
1976
1977
        let reset = backend.reset_brain().unwrap();
1978
        assert_eq!(reset.read_comments().unwrap(), None);
1979
    }
1980
    #[test]
1981
    fn rebase_remaps_persisted_comment_commit() {
1982
        let repository = TestRepository::new();
1983
        fs::write(repository.path.join("reviewed"), "base\n").unwrap();
1984
        repository.git(&["add", "reviewed"]);
1985
        repository.git(&["commit", "-q", "-m", "base"]);
1986
        repository.git(&["switch", "-q", "-c", "topic"]);
1987
        fs::write(repository.path.join("reviewed"), "base\nchange\n").unwrap();
1988
        repository.git(&["commit", "-q", "-am", "change"]);
1989
        let base = Rev::try_from("main").unwrap();
1990
        let target = Rev::try_from("topic").unwrap();
1991
        let backend = GitBackend::new(repository.path(), base, target).unwrap();
1992
        let old_target = backend
1993
            .repository
1994
            .commit_id(&backend.review.target)
1995
            .unwrap();
1996
        let brain = backend.reset_brain().unwrap();
1997
        brain
1998
            .write_comments(&format!(
1999
                r#"{{"commit":"{old_target}","id":1,"author":"A","timestamp":1,"heading":"change","path":"reviewed","patch_id":"p","ordinal":0,"body":"retained"}}"#
2000
            ))
2001
            .unwrap();
2002
        repository.git(&["switch", "-q", "main"]);
2003
        fs::write(repository.path.join("upstream"), "upstream\n").unwrap();
2004
        repository.git(&["add", "upstream"]);
2005
        repository.git(&["commit", "-q", "-m", "upstream"]);
2006
        repository.git(&["switch", "-q", "topic"]);
2007
        repository.git(&["rebase", "main"]);
2008
        let new_target = backend
2009
            .repository
2010
            .commit_id(&backend.review.target)
2011
            .unwrap();
2012
2013
        let rebased = backend.rebase_brain().unwrap();
2014
        let comments = rebased.read_comments().unwrap().unwrap();
2015
2016
        assert!(comments.contains(&new_target.to_string()));
2017
        assert!(!comments.contains(&old_target.to_string()));
2018
    }
2019
2020
    #[test]
2021
    fn reset_ref_update_is_atomic_when_comment_ref_is_locked() {
2022
        let repository = TestRepository::new();
2023
        repository.git(&["commit", "-q", "--allow-empty", "-m", "base"]);
2024
        repository.git(&["switch", "-q", "-c", "topic"]);
2025
        repository.git(&["commit", "-q", "--allow-empty", "-m", "target"]);
2026
        let base = Rev::try_from("main").unwrap();
2027
        let target = Rev::try_from("topic").unwrap();
2028
        let backend = GitBackend::new(repository.path(), base, target).unwrap();
2029
        let brain = backend.reset_brain().unwrap();
2030
        brain.write_comments("comment").unwrap();
2031
        let state = brain
2032
            .repository
2033
            .optional_ref(&brain.state_ref)
2034
            .unwrap()
2035
            .unwrap();
2036
        let comments = brain
2037
            .repository
2038
            .optional_ref(&brain.comments_ref)
2039
            .unwrap()
2040
            .unwrap();
2041
        repository.git(&["commit", "-q", "--allow-empty", "-m", "moved target"]);
2042
        let lock = repository
2043
            .path
2044
            .join(".git")
2045
            .join(format!("{}.lock", brain.comments_ref.as_str()));
2046
        fs::write(lock, "").unwrap();
2047
2048
        assert!(backend.reset_brain().is_err());
2049
        assert_eq!(
2050
            brain.repository.optional_ref(&brain.state_ref).unwrap(),
2051
            Some(state)
2052
        );
2053
        assert_eq!(
2054
            brain.repository.optional_ref(&brain.comments_ref).unwrap(),
2055
            Some(comments)
2056
        );
2057
    }
2058
2059
    #[test]
2060
    fn commit_decisions_persist_toggle_and_are_exclusive() {
2061
        let repository = TestRepository::new();
2062
        let reviewed = repository.path.join("reviewed.txt");
2063
        fs::write(&reviewed, "base\n").unwrap();
2064
        repository.git(&["add", "reviewed.txt"]);
2065
        repository.git(&["commit", "-q", "-m", "base"]);
2066
        repository.git(&["switch", "-q", "-c", "topic"]);
2067
        fs::write(&reviewed, "change\n").unwrap();
2068
        repository.git(&["commit", "-q", "-am", "change"]);
2069
2070
        let base = Rev::try_from("main").unwrap();
2071
        let target = Rev::try_from("topic").unwrap();
2072
        let backend = GitBackend::new(&repository.path, base, target).unwrap();
2073
        let commit = backend.commits().unwrap().pop().unwrap().id;
2074
        let mut brain = backend.reset_brain().unwrap();
2075
2076
        brain.toggle_commit_rejected(commit).unwrap();
2077
        assert!(backend.brain().unwrap().rejected.contains_key(&commit));
2078
2079
        brain.toggle_commit_rejected(commit).unwrap();
2080
        assert!(backend.brain().unwrap().rejected.is_empty());
2081
2082
        brain.toggle_commit_dropped(commit).unwrap();
2083
        let stored = backend.brain().unwrap();
2084
        assert!(stored.dropped.contains_key(&commit));
2085
        assert!(stored.rejected.is_empty());
2086
2087
        let document = backend.diff_document(commit).unwrap().split_hunks();
2088
        let identities = brain.hunk_identities(&document, commit).unwrap();
2089
        let history = HistoryStatus::for_commits(&brain, &[(commit, &document, &identities)]);
2090
        assert_eq!(history.progress, ReviewProgress::default());
2091
        assert_eq!(history.stats, DiffStat::default());
2092
2093
        brain.toggle_commit_rejected(commit).unwrap();
2094
        let stored = backend.brain().unwrap();
2095
        assert!(stored.rejected.contains_key(&commit));
2096
        assert!(stored.dropped.is_empty());
2097
2098
        brain.toggle_commit_dropped(commit).unwrap();
2099
        brain.toggle_commit_dropped(commit).unwrap();
2100
        assert!(backend.brain().unwrap().dropped.is_empty());
2101
2102
        brain.toggle_commit_rejected(commit).unwrap();
2103
        let document = backend.diff_document(commit).unwrap().split_hunks();
2104
        let identities = brain.hunk_identities(&document, commit).unwrap();
2105
        let file = &document.files[0];
2106
        let patches = FilePatches::new(file, file.hunks.clone()).unwrap();
2107
        brain.accept(identities.into_values(), [patches]).unwrap();
2108
        let stored = backend.brain().unwrap();
2109
2110
        assert!(stored.rejected.is_empty());
2111
        assert!(stored.dropped.is_empty());
2112
2113
        let identities = brain.hunk_identities(&document, commit).unwrap();
2114
        let history = HistoryStatus::for_commits(&brain, &[(commit, &document, &identities)]);
2115
        assert!(history.progress.is_complete());
2116
        assert_eq!(history.stats, DiffStat::default());
2117
    }
2118
2119
    #[test]
2120
    fn rebase_keeps_unchanged_hunk_acceptance_after_amend() {
2121
        let repository = TestRepository::new();
2122
        let reviewed = repository.path.join("reviewed.txt");
2123
        let amended = repository.path.join("amended.txt");
2124
        fs::write(&reviewed, "base\n").unwrap();
2125
        fs::write(&amended, "base\n").unwrap();
2126
        repository.git(&["add", "reviewed.txt", "amended.txt"]);
2127
        repository.git(&["commit", "-q", "-m", "base"]);
2128
        repository.git(&["switch", "-q", "-c", "topic"]);
2129
        fs::write(&reviewed, "accepted\n").unwrap();
2130
        fs::write(&amended, "first\n").unwrap();
2131
        repository.git(&["commit", "-q", "-am", "T1"]);
2132
2133
        let base = Rev::try_from("main").unwrap();
2134
        let target = Rev::try_from("topic").unwrap();
2135
        let backend = GitBackend::new(&repository.path, base, target).unwrap();
2136
        let first = backend.commits().unwrap().pop().unwrap();
2137
        let first_document = backend.diff_document(first.id).unwrap().split_hunks();
2138
        let mut brain = backend.reset_brain().unwrap();
2139
        let first_identities = brain.hunk_identities(&first_document, first.id).unwrap();
2140
        let first_file = first_document
2141
            .files
2142
            .iter()
2143
            .find(|file| {
2144
                file.header
2145
                    .display_path()
2146
                    .is_some_and(|path| path == Path::new("reviewed.txt"))
2147
            })
2148
            .unwrap();
2149
        let first_identity = first_identities[&first_file.hunks[0].id].clone();
2150
        let first_patches = FilePatches::new(first_file, first_file.hunks.clone()).unwrap();
2151
        brain.accept([first_identity], [first_patches]).unwrap();
2152
2153
        fs::write(&amended, "second\n").unwrap();
2154
        repository.git(&["commit", "-q", "-am", "T2", "--amend"]);
2155
        let second = backend.commits().unwrap().pop().unwrap();
2156
        let second_document = backend.diff_document(second.id).unwrap().split_hunks();
2157
        let second_identities = brain.hunk_identities(&second_document, second.id).unwrap();
2158
        let second_file = second_document
2159
            .files
2160
            .iter()
2161
            .find(|file| {
2162
                file.header
2163
                    .display_path()
2164
                    .is_some_and(|path| path == Path::new("reviewed.txt"))
2165
            })
2166
            .unwrap();
2167
        let second_identity = second_identities[&second_file.hunks[0].id].clone();
2168
2169
        assert!(matches!(backend.brain(), Err(Error::StaleReviewState)));
2170
2171
        let rebased = backend.rebase_brain().unwrap();
2172
2173
        assert_eq!(rebased.state_ref, brain.state_ref);
2174
        assert_eq!(rebased.target, second.id);
2175
        assert_eq!(rebased.accepted, Accepted::from([second_identity]));
2176
    }
2177
2178
    #[test]
2179
    fn rebase_keeps_rejection_for_an_unchanged_commit() {
2180
        let repository = TestRepository::new();
2181
        let reviewed = repository.path.join("reviewed.txt");
2182
        let unrelated = repository.path.join("unrelated.txt");
2183
        fs::write(&reviewed, "base\n").unwrap();
2184
        repository.git(&["add", "reviewed.txt"]);
2185
        repository.git(&["commit", "-q", "-m", "base"]);
2186
        repository.git(&["switch", "-q", "-c", "topic"]);
2187
        fs::write(&reviewed, "rejected\n").unwrap();
2188
        repository.git(&["commit", "-q", "-am", "topic"]);
2189
2190
        let base = Rev::try_from("main").unwrap();
2191
        let target = Rev::try_from("topic").unwrap();
2192
        let backend = GitBackend::new(&repository.path, base, target).unwrap();
2193
        let rejected = backend.commits().unwrap().pop().unwrap().id;
2194
        let mut brain = backend.reset_brain().unwrap();
2195
        brain.toggle_commit_rejected(rejected).unwrap();
2196
2197
        repository.git(&["switch", "-q", "main"]);
2198
        fs::write(&unrelated, "new base\n").unwrap();
2199
        repository.git(&["add", "unrelated.txt"]);
2200
        repository.git(&["commit", "-q", "-m", "advance base"]);
2201
        repository.git(&["switch", "-q", "topic"]);
2202
        repository.git(&["rebase", "-q", "main"]);
2203
        let rewritten = backend.commits().unwrap().pop().unwrap().id;
2204
2205
        assert_ne!(rewritten, rejected);
2206
        assert!(matches!(backend.brain(), Err(Error::StaleReviewState)));
2207
2208
        let rebased = backend.rebase_brain().unwrap();
2209
2210
        assert_eq!(
2211
            rebased.rejected.keys().copied().collect::<BTreeSet<_>>(),
2212
            BTreeSet::from([rewritten])
2213
        );
2214
    }
2215
2216
    #[test]
2217
    fn rebase_keeps_distinct_decisions_for_duplicate_commit_patches() {
2218
        let repository = TestRepository::with_duplicate_patch_commits();
2219
        let unrelated = repository.path.join("unrelated.txt");
2220
2221
        let base = Rev::try_from("main").unwrap();
2222
        let target = Rev::try_from("topic").unwrap();
2223
        let backend = GitBackend::new(&repository.path, base, target).unwrap();
2224
        let commits = backend.commits().unwrap();
2225
        let mut brain = backend.reset_brain().unwrap();
2226
        brain.toggle_commit_dropped(commits[0].id).unwrap();
2227
        brain.toggle_commit_rejected(commits[2].id).unwrap();
2228
2229
        repository.git(&["switch", "-q", "main"]);
2230
        fs::write(&unrelated, "new base\n").unwrap();
2231
        repository.git(&["add", "unrelated.txt"]);
2232
        repository.git(&["commit", "-q", "-m", "advance base"]);
2233
        repository.git(&["switch", "-q", "topic"]);
2234
        repository.git(&["rebase", "-q", "main"]);
2235
        let rewritten = backend.commits().unwrap();
2236
        let rebased = backend.rebase_brain().unwrap();
2237
2238
        assert_eq!(
2239
            rebased.dropped.keys().copied().collect::<BTreeSet<_>>(),
2240
            BTreeSet::from([rewritten[0].id])
2241
        );
2242
        assert_eq!(
2243
            rebased.rejected.keys().copied().collect::<BTreeSet<_>>(),
2244
            BTreeSet::from([rewritten[2].id])
2245
        );
2246
    }
2247
2248
    #[test]
2249
    fn rebase_reserves_an_unchanged_decision_before_matching_duplicates() {
2250
        let repository = TestRepository::with_duplicate_patch_commits();
2251
        repository.git(&["branch", "-f", "main", "HEAD~1"]);
2252
2253
        let base = Rev::try_from("main").unwrap();
2254
        let target = Rev::try_from("topic").unwrap();
2255
        let backend = GitBackend::new(&repository.path, base, target).unwrap();
2256
        let unchanged = backend.commits().unwrap().pop().unwrap().id;
2257
        let mut brain = backend.reset_brain().unwrap();
2258
        brain.toggle_commit_rejected(unchanged).unwrap();
2259
2260
        repository.git(&["branch", "-f", "main", "HEAD~3"]);
2261
        let commits = backend.commits().unwrap();
2262
        let rebased = backend.rebase_brain().unwrap();
2263
2264
        assert_eq!(commits[2].id, unchanged);
2265
        assert_eq!(
2266
            rebased.rejected.keys().copied().collect::<BTreeSet<_>>(),
2267
            BTreeSet::from([unchanged])
2268
        );
2269
    }
2270
2271
    #[test]
2272
    fn statuses_are_empty_in_repository_without_commits() {
2273
        let fixture = TestRepository::new();
2274
2275
        let statuses = statuses(fixture.path()).unwrap();
2276
2277
        assert!(statuses.is_empty());
2278
    }
2279
    #[test]
2280
    fn statuses_include_native_jujutsu_bookmarks() {
2281
        let fixture = TestRepository::new();
2282
        fs::remove_dir_all(fixture.path().join(".git")).unwrap();
2283
        fixture.jj(&["git", "init", "--no-colocate", "."]);
2284
        fixture.jj(&["describe", "-m", "base"]);
2285
        fixture.jj(&["bookmark", "create", "main", "-r", "@"]);
2286
        fixture.jj(&["new", "main"]);
2287
        fixture.jj(&["describe", "-m", "target"]);
2288
        fixture.jj(&["bookmark", "create", "topic", "-r", "@"]);
2289
2290
        let statuses = statuses(fixture.path()).unwrap();
2291
2292
        assert_eq!(
2293
            statuses
2294
                .into_iter()
2295
                .map(|status| status.head)
2296
                .collect::<BTreeSet<_>>(),
2297
            BTreeSet::from(["main".to_owned(), "topic".to_owned()])
2298
        );
2299
    }
2300
2301
    #[test]
2302
    fn statuses_require_trunk_in_nonempty_repository() {
2303
        let fixture = TestRepository::new();
2304
        fixture.git(&["branch", "-m", "topic"]);
2305
        fixture.git(&["commit", "-q", "--allow-empty", "-m", "topic"]);
2306
2307
        let error = statuses(fixture.path()).unwrap_err();
2308
2309
        assert_eq!(error.to_string(), "git: no trunk or master branch found");
2310
    }
2311
2312
    #[test]
2313
    fn statuses_match_symbolic_target_to_branch_commit() {
2314
        let fixture = TestRepository::new();
2315
        fixture.git(&["config", "init.defaultBranch", "main"]);
2316
        fixture.git(&["commit", "-q", "--allow-empty", "-m", "base"]);
2317
        fixture.git(&["commit", "-q", "--allow-empty", "-m", "target"]);
2318
        let repository = git::Repository::discover(fixture.path.clone()).unwrap();
2319
        let identity = ReviewIdentity::new(
2320
            Rev::try_from("main").unwrap(),
2321
            Rev::try_from("HEAD").unwrap(),
2322
        );
2323
        let base = repository.commit_id(&identity.base).unwrap();
2324
        let target = repository.commit_id(&identity.target).unwrap();
2325
        let _brain = Brain::reset(repository.clone(), base, target, &identity).unwrap();
2326
2327
        let statuses = Brain::statuses(&repository).unwrap();
2328
2329
        assert_eq!(statuses.len(), 1);
2330
        assert_eq!(statuses[0].head, "main");
2331
        assert_eq!(statuses[0].head_kind, BrainStatusHead::Branch);
2332
        assert_ne!(statuses[0].state, BrainStatusState::NoState);
2333
    }
2334
2335
    #[test]
2336
    fn statuses_recover_renamed_symbolic_target_by_persisted_oid() {
2337
        let fixture = TestRepository::new();
2338
        let file = fixture.path.join("reviewed.txt");
2339
        fs::write(&file, "base\n").unwrap();
2340
        fixture.git(&["add", "reviewed.txt"]);
2341
        fixture.git(&["commit", "-q", "-m", "base"]);
2342
        fixture.git(&["switch", "-q", "-c", "feature"]);
2343
        fs::write(&file, "reviewed\n").unwrap();
2344
        fixture.git(&["commit", "-q", "-am", "feature"]);
2345
        let repository = git::Repository::discover(fixture.path.clone()).unwrap();
2346
        let identity = ReviewIdentity::new(
2347
            Rev::try_from("main").unwrap(),
2348
            Rev::try_from("feature").unwrap(),
2349
        );
2350
        let base = repository.commit_id(&identity.base).unwrap();
2351
        let target = repository.commit_id(&identity.target).unwrap();
2352
        let brain = Brain::reset(repository.clone(), base, target, &identity).unwrap();
2353
        brain
2354
            .write_comments(
2355
                r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","ordinal":0,"body":"retained"}"#,
2356
            )
2357
            .unwrap();
2358
2359
        fixture.git(&["branch", "-m", "reviewed-feature"]);
2360
        let statuses = Brain::statuses(&repository).unwrap();
2361
        let reviewed = statuses
2362
            .iter()
2363
            .filter(|status| status.state != BrainStatusState::NoState)
2364
            .collect::<Vec<_>>();
2365
2366
        assert_eq!(reviewed.len(), 1);
2367
        assert_eq!(reviewed[0].head, "reviewed-feature");
2368
        assert_eq!(reviewed[0].head_kind, BrainStatusHead::Branch);
2369
        assert_eq!(reviewed[0].state, BrainStatusState::InReview);
2370
        assert_eq!(reviewed[0].comments, CommentStatus::Count(1));
2371
        assert!(reviewed[0].progress.total > 0);
2372
    }
2373
2374
    #[test]
2375
    fn statuses_skip_pruned_target_without_hiding_renamed_review() {
2376
        let fixture = TestRepository::new();
2377
        let file = fixture.path.join("reviewed.txt");
2378
        fs::write(&file, "base\n").unwrap();
2379
        fixture.git(&["add", "reviewed.txt"]);
2380
        fixture.git(&["commit", "-q", "-m", "base"]);
2381
        fixture.git(&["switch", "-q", "-c", "feature"]);
2382
        fs::write(&file, "reviewed\n").unwrap();
2383
        fixture.git(&["commit", "-q", "-am", "feature"]);
2384
        let repository = git::Repository::discover(fixture.path.clone()).unwrap();
2385
        let renamed = ReviewIdentity::new(
2386
            Rev::try_from("main").unwrap(),
2387
            Rev::try_from("feature").unwrap(),
2388
        );
2389
        let base = repository.commit_id(&renamed.base).unwrap();
2390
        let renamed_target = repository.commit_id(&renamed.target).unwrap();
2391
        let _renamed_brain =
2392
            Brain::reset(repository.clone(), base, renamed_target, &renamed).unwrap();
2393
        fixture.git(&["branch", "-m", "reviewed-feature"]);
2394
2395
        fixture.git(&["switch", "-q", "main"]);
2396
        fixture.git(&["switch", "-q", "-c", "abandoned"]);
2397
        fs::write(&file, "abandoned\n").unwrap();
2398
        fixture.git(&["commit", "-q", "-am", "abandoned"]);
2399
        let abandoned = ReviewIdentity::new(
2400
            Rev::try_from("main").unwrap(),
2401
            Rev::try_from("abandoned").unwrap(),
2402
        );
2403
        let abandoned_target = repository.commit_id(&abandoned.target).unwrap();
2404
        let _abandoned_brain =
2405
            Brain::reset(repository.clone(), base, abandoned_target, &abandoned).unwrap();
2406
        fixture.git(&["switch", "-q", "main"]);
2407
        fixture.git(&["branch", "-D", "abandoned"]);
2408
        fixture.git(&[
2409
            "reflog",
2410
            "expire",
2411
            "--expire=now",
2412
            "--expire-unreachable=now",
2413
            "--all",
2414
        ]);
2415
        fixture.git(&["gc", "--prune=now"]);
2416
        assert!(repository.commit_id(&Rev::from(abandoned_target)).is_err());
2417
2418
        let statuses = Brain::statuses(&repository).unwrap();
2419
        let renamed = statuses
2420
            .iter()
2421
            .find(|status| status.head == "reviewed-feature")
2422
            .unwrap();
2423
2424
        assert_eq!(statuses.len(), 2);
2425
        assert_eq!(renamed.head_kind, BrainStatusHead::Branch);
2426
        assert_ne!(renamed.state, BrainStatusState::NoState);
2427
    }
2428
2429
    /// Returns an accepted identity for one test commit and hunk.
2430
    fn accepted_hunk(commit: &str, patch: &str, ordinal: u32, total: u32) -> AcceptedHunk {
2431
        AcceptedHunk {
2432
            commit: commit.parse().unwrap(),
2433
            patch_id: PatchId::from(patch.to_owned()),
2434
            ordinal,
2435
            lines: 1,
2436
            commit_lines: total,
2437
        }
2438
    }
2439
2440
    #[test]
2441
    fn accepted_state_roundtrips_through_commit_message() {
2442
        let state = PersistedState {
2443
            target: "2222222222222222222222222222222222222222".parse().unwrap(),
2444
            accepted: Accepted::from([
2445
                accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 2),
2446
                accepted_hunk("1111111111111111111111111111111111111111", "beta", 0, 2),
2447
            ]),
2448
            rejected: Rejected::from([(
2449
                "3333333333333333333333333333333333333333".parse().unwrap(),
2450
                CommitDecision {
2451
                    patch_id: PatchId::from("rejected".to_owned()),
2452
                    ordinal: 0,
2453
                },
2454
            )]),
2455
            dropped: Dropped::from([(
2456
                "4444444444444444444444444444444444444444".parse().unwrap(),
2457
                CommitDecision {
2458
                    patch_id: PatchId::from("dropped".to_owned()),
2459
                    ordinal: 0,
2460
                },
2461
            )]),
2462
        };
2463
        let message = encode_state(&state);
2464
2465
        assert!(message.starts_with("Brain review 2222222\n\nbrain-v1\ntarget "));
2466
        assert_eq!(decode_state(&message), Some(state.clone()));
2467
        let (_, body) = message.split_once("\n\n").unwrap();
2468
        assert_eq!(decode_state(&format!("brain state\n\n{body}")), Some(state));
2469
    }
2470
2471
    #[test]
2472
    fn empty_accepted_state_roundtrips_through_commit_message() {
2473
        let state = PersistedState {
2474
            target: "2222222222222222222222222222222222222222".parse().unwrap(),
2475
            accepted: Accepted::new(),
2476
            rejected: Rejected::new(),
2477
            dropped: Dropped::new(),
2478
        };
2479
        let message = encode_state(&state);
2480
2481
        assert_eq!(decode_state(&message), Some(state.clone()));
2482
        // Git terminates `%B` output with its own newline.
2483
        assert_eq!(decode_state(&format!("{message}\n")), Some(state));
2484
    }
2485
2486
    #[test]
2487
    fn accepted_state_rejects_inconsistent_line_totals() {
2488
        let commit = "1111111111111111111111111111111111111111";
2489
        let target = format!("target {commit}\n");
2490
        let inconsistent = format!(
2491
            "Brain review 1111111\n\n{STATE_SECTION}\n{target}{commit} alpha 0 1 2\n{commit} beta 0 1 3\n"
2492
        );
2493
        let zero =
2494
            format!("Brain review 1111111\n\n{STATE_SECTION}\n{target}{commit} alpha 0 0 1\n");
2495
        let duplicate = format!(
2496
            "Brain review 1111111\n\n{STATE_SECTION}\n{target}{commit} alpha 0 1 1\n{commit} alpha 0 1 1\n"
2497
        );
2498
2499
        assert_eq!(decode_state(&inconsistent), None);
2500
        assert_eq!(decode_state(&zero), None);
2501
        assert_eq!(decode_state(&duplicate), None);
2502
    }
2503
2504
    #[test]
2505
    fn accepted_state_rejects_malformed_payload() {
2506
        let commit = "1111111111111111111111111111111111111111";
2507
        let extra_field = format!(
2508
            "Brain review 1111111\n\n{STATE_SECTION}\ntarget {commit}\n{commit} alpha 0 1 1 extra\n"
2509
        );
2510
        let missing_target =
2511
            format!("Brain review 1111111\n\n{STATE_SECTION}\n{commit} alpha 0 1 1\n");
2512
2513
        assert_eq!(decode_state(&extra_field), None);
2514
        assert_eq!(decode_state(&missing_target), None);
2515
    }
2516
2517
    #[test]
2518
    fn reconciliation_uses_exact_accepted_identities() {
2519
        let first = accepted_hunk("1111111111111111111111111111111111111111", "change", 0, 1);
2520
        let second = accepted_hunk("2222222222222222222222222222222222222222", "restore", 0, 1);
2521
        let first_hunks = BTreeMap::from([(HunkId::new(0), first.clone())]);
2522
        let second_hunks = BTreeMap::from([(HunkId::new(0), second.clone())]);
2523
        let commits = [
2524
            CommitHunks {
2525
                commit: first.commit,
2526
                hunks: Some(&first_hunks),
2527
            },
2528
            CommitHunks {
2529
                commit: second.commit,
2530
                hunks: Some(&second_hunks),
2531
            },
2532
        ];
2533
2534
        let fresh = Reconciled::for_commits(
2535
            &Accepted::new(),
2536
            &Rejected::new(),
2537
            &Dropped::new(),
2538
            &commits,
2539
        );
2540
        assert!(fresh.iter().all(|state| state.accepted.is_empty()));
2541
        assert!(fresh.iter().all(|state| state.progress
2542
            == ReviewProgress {
2543
                accepted: 0,
2544
                total: 1,
2545
            }));
2546
2547
        let remaining = Reconciled::for_commits(
2548
            &Accepted::from([second]),
2549
            &Rejected::new(),
2550
            &Dropped::new(),
2551
            &commits,
2552
        );
2553
        assert!(remaining[0].accepted.is_empty());
2554
        assert_eq!(remaining[1].accepted, BTreeSet::from([HunkId::new(0)]));
2555
        assert!(remaining[1].progress.is_complete());
2556
2557
        let rejected = Reconciled::for_commits(
2558
            &Accepted::new(),
2559
            &Rejected::from([(
2560
                first.commit,
2561
                CommitDecision {
2562
                    patch_id: PatchId::from("change".to_owned()),
2563
                    ordinal: 0,
2564
                },
2565
            )]),
2566
            &Dropped::new(),
2567
            &commits,
2568
        );
2569
        assert_eq!(rejected[0].state, CommitReviewState::Rejected);
2570
        assert_eq!(rejected[1].state, CommitReviewState::Pending);
2571
    }
2572
2573
    #[test]
2574
    fn reconciliation_weights_undecoded_progress_by_changed_lines() {
2575
        let first = AcceptedHunk {
2576
            lines: 3,
2577
            commit_lines: 4,
2578
            ..accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 4)
2579
        };
2580
        let second = AcceptedHunk {
2581
            commit_lines: 4,
2582
            ..accepted_hunk("1111111111111111111111111111111111111111", "beta", 0, 4)
2583
        };
2584
        let commits = [CommitHunks {
2585
            commit: first.commit,
2586
            hunks: None,
2587
        }];
2588
2589
        let partial = Reconciled::for_commits(
2590
            &Accepted::from([first.clone()]),
2591
            &Rejected::new(),
2592
            &Dropped::new(),
2593
            &commits,
2594
        );
2595
        assert_eq!(
2596
            partial[0].progress,
2597
            ReviewProgress {
2598
                accepted: 3,
2599
                total: 4,
2600
            }
2601
        );
2602
        assert!(partial[0].accepted.is_empty());
2603
2604
        let full = Reconciled::for_commits(
2605
            &Accepted::from([first, second]),
2606
            &Rejected::new(),
2607
            &Dropped::new(),
2608
            &commits,
2609
        );
2610
        assert!(full[0].progress.is_complete());
2611
        assert!(full[0].accepted.is_empty());
2612
    }
2613
2614
    #[test]
2615
    fn hunkless_commit_is_complete_without_accepted_identity() {
2616
        let commit = "1111111111111111111111111111111111111111".parse().unwrap();
2617
        let identities = BTreeMap::new();
2618
        let reconciled = Reconciled::for_commits(
2619
            &Accepted::new(),
2620
            &Rejected::new(),
2621
            &Dropped::new(),
2622
            &[CommitHunks {
2623
                commit,
2624
                hunks: Some(&identities),
2625
            }],
2626
        );
2627
2628
        assert!(reconciled[0].progress.is_complete());
2629
        assert_eq!(
2630
            reconciled[0].progress,
2631
            ReviewProgress {
2632
                accepted: 1,
2633
                total: 1,
2634
            }
2635
        );
2636
        assert!(reconciled[0].accepted.is_empty());
2637
    }
2638
2639
    #[test]
2640
    fn rebase_remaps_within_a_commit_before_across_commits() {
2641
        let moved = accepted_hunk("1111111111111111111111111111111111111111", "same", 0, 1);
2642
        // The commit still exists, but gained a hunk, so its stored identity no
2643
        // longer matches exactly.
2644
        let kept = accepted_hunk("2222222222222222222222222222222222222222", "same", 0, 1);
2645
        let stored = Accepted::from([kept.clone()]);
2646
        let elsewhere = accepted_hunk("3333333333333333333333333333333333333333", "same", 0, 1);
2647
        let same_commit = AcceptedHunk {
2648
            commit_lines: 2,
2649
            ..kept
2650
        };
2651
        let current = [elsewhere.clone(), same_commit.clone()];
2652
2653
        let remapped = AcceptedHunk::remap(&stored, &current, &BTreeMap::new());
2654
2655
        assert_eq!(remapped, Accepted::from([same_commit.clone()]));
2656
        // With no same-commit candidate, the patch id alone carries acceptance.
2657
        let remapped = AcceptedHunk::remap(&stored, [&moved], &BTreeMap::new());
2658
        assert_eq!(remapped, Accepted::from([moved.clone()]));
2659
2660
        let rewritten = accepted_hunk("4444444444444444444444444444444444444444", "same", 0, 1);
2661
        let commits = BTreeMap::from([(same_commit.commit, rewritten.commit)]);
2662
        let remapped = AcceptedHunk::remap(&stored, [&elsewhere, &rewritten], &commits);
2663
        assert_eq!(remapped, Accepted::from([rewritten]));
2664
    }
2665
2666
    #[test]
2667
    fn rebase_remaps_duplicate_patch_ids_by_occurrence() {
2668
        let stored = Accepted::from([
2669
            accepted_hunk("1111111111111111111111111111111111111111", "same", 0, 2),
2670
            accepted_hunk("1111111111111111111111111111111111111111", "same", 1, 2),
2671
        ]);
2672
        let first = accepted_hunk("2222222222222222222222222222222222222222", "same", 0, 3);
2673
        let second = accepted_hunk("2222222222222222222222222222222222222222", "same", 1, 3);
2674
        let third = accepted_hunk("2222222222222222222222222222222222222222", "same", 2, 3);
2675
        let current = [first.clone(), second.clone(), third];
2676
2677
        let remapped = AcceptedHunk::remap(&stored, &current, &BTreeMap::new());
2678
2679
        assert_eq!(remapped, Accepted::from([first, second]));
2680
    }
2681
2682
    #[test]
2683
    fn review_identity_roundtrips_through_ref() {
2684
        let base = Rev::try_from("HEAD^^^^").unwrap();
2685
        let target = Rev::try_from("HEAD").unwrap();
2686
        let identity = ReviewIdentity::new(base, target);
2687
        let reference = Brain::ref_for_identity(STATE_REF_NAMESPACE, &identity).unwrap();
2688
        let prefix = Brain::prefix_for(STATE_REF_NAMESPACE).unwrap();
2689
        let decoded = ReviewIdentity::from_ref(&prefix, &reference).unwrap();
2690
2691
        assert_eq!(decoded, identity);
2692
        assert_eq!(
2693
            reference.as_str(),
2694
            "refs/brain/state/range/HEAD%5e%5e%5e%5e/HEAD"
2695
        );
2696
    }
2697
2698
    #[test]
2699
    fn review_identity_rejects_unrecognized_refs() {
2700
        let prefix = Brain::prefix_for(STATE_REF_NAMESPACE).unwrap();
2701
        let unrecognized = prefix.join(component("HEAD".to_owned()).unwrap());
2702
2703
        assert_eq!(ReviewIdentity::from_ref(&prefix, &unrecognized), None);
2704
    }
2705
2706
    #[test]
2707
    fn hunk_identity_patch_omits_context_lines() {
2708
        let document = DiffDocument::decode_str(
2709
            r#"diff --git a/f b/f
2710
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
2711
--- a/f
2712
+++ b/f
2713
@@ -1,3 +1,3 @@
2714
 context before
2715
-old
2716
+new
2717
 context after
2718
"#,
2719
        )
2720
        .unwrap();
2721
        let patch = hunk_identity_patch(&document.files[0], &document.files[0].hunks[0]).unwrap();
2722
2723
        assert!(patch.contains("-old"));
2724
        assert!(patch.contains("+new"));
2725
        assert!(!patch.contains("context before"));
2726
    }
2727
2728
    #[test]
2729
    fn accepting_binary_hunk_projects_whole_file() {
2730
        let repository = TestRepository::new();
2731
        let path = repository.path.join("image.bin");
2732
        fs::write(&path, b"base\0binary").unwrap();
2733
        repository.git(&["add", "image.bin"]);
2734
        repository.git(&["commit", "-q", "-m", "base"]);
2735
        repository.git(&["switch", "-q", "-c", "topic"]);
2736
        let accepted_contents = b"accepted\0binary\0contents";
2737
        fs::write(&path, accepted_contents).unwrap();
2738
        repository.git(&["commit", "-q", "-am", "binary"]);
2739
2740
        let backend = GitBackend::new(
2741
            repository.path(),
2742
            Rev::try_from("main").unwrap(),
2743
            Rev::try_from("topic").unwrap(),
2744
        )
2745
        .unwrap();
2746
        let commit = backend.commits().unwrap().pop().unwrap();
2747
        let document = backend.diff_document(commit.id).unwrap().split_hunks();
2748
        let file = &document.files[0];
2749
        let mut brain = backend.reset_brain().unwrap();
2750
        let identities = brain.hunk_identities(&document, commit.id).unwrap();
2751
        let identity = identities[&file.hunks[0].id].clone();
2752
        let patches = FilePatches::new(file, file.hunks.clone()).unwrap();
2753
2754
        brain.accept([identity.clone()], [patches]).unwrap();
2755
2756
        assert_eq!(
2757
            backend.brain().unwrap().accepted,
2758
            Accepted::from([identity])
2759
        );
2760
        let object = format!("{}:image.bin", brain.commit);
2761
        assert_eq!(repository.git_output(&["show", &object]), accepted_contents);
2762
    }
2763
2764
    #[test]
2765
    fn commit_stats_count_binary_files_and_exclude_accepted_hunks() {
2766
        let document =
2767
            DiffDocument::decode_str(include_str!("../../diff/tests/golden/file_kinds.diff"))
2768
                .unwrap();
2769
        let metadata_and_binary = DiffDocument {
2770
            commit: None,
2771
            files: document.files[2..].to_vec(),
2772
        };
2773
2774
        assert_eq!(
2775
            commit_remaining_stats(&metadata_and_binary, &BTreeSet::new()),
2776
            DiffStat {
2777
                files_changed: 1,
2778
                ..DiffStat::default()
2779
            }
2780
        );
2781
        assert_eq!(
2782
            commit_remaining_stats(
2783
                &document,
2784
                &BTreeSet::from([HunkId::new(0), HunkId::new(1), HunkId::new(2)]),
2785
            ),
2786
            DiffStat::default()
2787
        );
2788
    }
2789
2790
    #[test]
2791
    fn commit_stats_count_pending_binary_deletion() {
2792
        let document = DiffDocument::decode_str(
2793
            r#"diff --git a/new.rs b/new.rs
2794
new file mode 100644
2795
index 0000000000000000000000000000000000000000..1111111111111111111111111111111111111111
2796
--- /dev/null
2797
+++ b/new.rs
2798
@@ -0,0 +1 @@
2799
+new
2800
diff --git a/image.png b/image.png
2801
deleted file mode 100644
2802
index 1111111111111111111111111111111111111111..0000000000000000000000000000000000000000
2803
Binary files a/image.png and /dev/null differ
2804
"#,
2805
        )
2806
        .unwrap();
2807
2808
        assert_eq!(
2809
            commit_remaining_stats(&document, &BTreeSet::new()),
2810
            DiffStat {
2811
                files_changed: 2,
2812
                insertions: 1,
2813
                deletions: 0,
2814
            }
2815
        );
2816
    }
2817
    #[test]
2818
    fn sequential_added_file_hunks_share_one_projected_file() {
2819
        let fixture = TestRepository::new();
2820
        fixture.git(&["commit", "-q", "--allow-empty", "-m", "base"]);
2821
        let repository = git::Repository::discover(fixture.path().to_owned()).unwrap();
2822
        let base = repository
2823
            .commit_id(&Rev::try_from("HEAD").unwrap())
2824
            .unwrap();
2825
        let identity = ReviewIdentity::new(Rev::from(base), Rev::try_from("HEAD").unwrap());
2826
        let mut brain = Brain::load(repository.clone(), base, base, &identity).unwrap();
2827
        let document = DiffDocument::decode_str(
2828
            r#"diff --git a/new.txt b/new.txt
2829
new file mode 100644
2830
index 0000000000000000000000000000000000000000..1111111111111111111111111111111111111111
2831
--- /dev/null
2832
+++ b/new.txt
2833
@@ -0,0 +1 @@
2834
+first accepted region
2835
@@ -0,0 +20 @@
2836
+second accepted region
2837
"#,
2838
        )
2839
        .unwrap();
2840
        let file = &document.files[0];
2841
        let first = FilePatches::new(file, vec![file.hunks[0].clone()]).unwrap();
2842
        let both = FilePatches::new(file, file.hunks.clone()).unwrap();
2843
        let commit = base.to_string();
2844
2845
        brain
2846
            .accept([accepted_hunk(&commit, "first", 0, 2)], [first])
2847
            .unwrap();
2848
        brain
2849
            .accept([accepted_hunk(&commit, "second", 0, 2)], [both])
2850
            .unwrap();
2851
2852
        let projected = repository.diff(base, brain.commit).unwrap();
2853
        assert!(projected.contains("+first accepted region"));
2854
        assert!(projected.contains("+second accepted region"));
2855
        assert_eq!(projected.matches("new file mode 100644").count(), 1);
2856
    }
2857
}