brain: Add status command

1513d69d43c8a67753bdd762c449f8582a115faa
Show local branches and persisted review state together so review
progress, comments, divergence, staleness, and merge conflicts can be
inspected without opening the interactive diff.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent 4350ff5c
crates/brain/src/backend.rs +357 -13
4 4
//! commit at a time. The commit list and each commit's diff (against its
5 5
//! parent) come from either Git or Jujutsu; the backend is auto-detected from
6 6
//! the working directory. Jujutsu repositories are supported whether or not
7 7
//! they are colocated with Git, since `jj` produces the patches directly.
8 8
9 +
use std::cmp::Ordering;
9 10
use std::collections::{BTreeMap, BTreeSet};
10 11
use std::ffi::OsString;
11 12
use std::path::Path;
12 13
13 -
use rustik_diff::{Decode as _, DiffDocument, Encode as _, FileDiff, Hunk, HunkId};
14 +
use rustik_diff::{Decode as _, DiffDocument, Encode as _, FileDiff, Hunk, HunkId, ReviewProgress};
14 15
use rustik_repo::{
15 -
    DiffStat, Oid, PatchId, ReadRepository, Rev, WriteRepository,
16 +
    AheadBehind, CommitTime, DiffStat, MergeStatus, Oid, PatchId, ReadRepository, Rev,
17 +
    WriteRepository,
16 18
    git::{
17 19
        self,
18 20
        refs::{Component, Qualified, RefString},
19 21
    },
20 22
    jj,
83 85
    pub reviewed: bool,
84 86
    /// Accepted hunks, for commits whose hunk patch ids were supplied.
85 87
    pub accepted: BTreeSet<HunkId>,
86 88
}
87 89
90 +
/// Stored status for one review identity.
91 +
#[derive(Clone, Debug, Eq, PartialEq)]
92 +
pub struct BrainStatus {
93 +
    /// Head name displayed to the user.
94 +
    pub head: String,
95 +
    /// Kind of review identity displayed in the head column.
96 +
    pub head_kind: BrainStatusHead,
97 +
    /// Brain state status for the review.
98 +
    pub state: BrainStatusState,
99 +
    /// Whether the stored base matches the current review base.
100 +
    pub base_state: BrainStatusBaseState,
101 +
    /// Accepted-hunk progress across the review.
102 +
    pub progress: ReviewProgress,
103 +
    /// Ahead and behind counts relative to the trunk branch.
104 +
    pub relation: AheadBehind,
105 +
    /// Merge status relative to the trunk branch.
106 +
    pub merge: MergeStatus,
107 +
    /// Comment storage status for this review.
108 +
    pub comments: CommentStatus,
109 +
    /// Head commit timestamp used to order status rows.
110 +
    pub recency: CommitTime,
111 +
}
112 +
113 +
/// Stored-base status for one review row.
114 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
115 +
pub enum BrainStatusBaseState {
116 +
    /// Stored state matches the current review base.
117 +
    Ok,
118 +
    /// Stored state was recorded on a different base and needs reset.
119 +
    Stale,
120 +
}
121 +
122 +
impl BrainStatusBaseState {
123 +
    /// Returns stored-base status relative to the current review base.
124 +
    fn from_base(stored: Oid, current: Oid) -> Self {
125 +
        if stored == current {
126 +
            Self::Ok
127 +
        } else {
128 +
            Self::Stale
129 +
        }
130 +
    }
131 +
}
132 +
133 +
/// Kind of review identity displayed in one status row.
134 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
135 +
pub enum BrainStatusHead {
136 +
    /// The review identity is a local branch name.
137 +
    Branch,
138 +
    /// The review identity is stored brain state that is not a local branch.
139 +
    Stored,
140 +
}
141 +
142 +
/// Brain state status for one review row.
143 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
144 +
pub enum BrainStatusState {
145 +
    /// Stored review state exists and all hunks are accepted.
146 +
    Approved,
147 +
    /// Stored review state exists but some hunks are not accepted.
148 +
    InReview,
149 +
    /// No stored review state exists.
150 +
    NoState,
151 +
}
152 +
153 +
/// Stored review state before it is joined to local branch rows.
154 +
struct StoredReview {
155 +
    /// Base commit recorded by the review state.
156 +
    base: Oid,
157 +
    /// Accepted-hunk progress across the review.
158 +
    progress: ReviewProgress,
159 +
    /// Comment storage status for this review.
160 +
    comments: CommentStatus,
161 +
    /// Head commit timestamp used to order status rows.
162 +
    recency: CommitTime,
163 +
}
164 +
165 +
/// Stored comment status for one review identity.
166 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
167 +
pub enum CommentStatus {
168 +
    /// No comment blob exists.
169 +
    None,
170 +
    /// Comment blob exists and contains this many rows.
171 +
    Count(usize),
172 +
    /// Comment blob exists but does not parse.
173 +
    Invalid,
174 +
}
175 +
88 176
/// A revision backend that lists the reviewed commits and their diffs.
89 177
///
90 178
/// The base and target revisions are resolved and stored when the backend is
91 179
/// constructed, so listing commits needs no further arguments.
92 180
pub trait Backend {
110 198
    /// Returns a backend for `cwd` bound to the `base..target` range.
111 199
    ///
112 200
    /// A [`JJ_DIR`] directory in `cwd` or an ancestor selects the Jujutsu
113 201
    /// backend; otherwise Git is used.
114 202
    pub fn from_path(cwd: &Path, base: Rev, target: Rev) -> Result<Box<dyn Backend>, Error> {
115 -
        if cwd.ancestors().any(|path| path.join(JJ_DIR).is_dir()) {
203 +
        if is_jj_workspace(cwd) {
116 204
            let backend = JjBackend::new(cwd, base, target)?;
117 205
            Ok(Box::new(backend))
118 206
        } else {
119 207
            let backend = GitBackend::new(cwd, base, target)?;
120 208
            Ok(Box::new(backend))
121 209
        }
122 210
    }
123 211
}
124 212
213 +
/// Returns stored review statuses for the repository containing `cwd`.
214 +
pub fn statuses(cwd: &Path) -> Result<Vec<BrainStatus>, Error> {
215 +
    let repository = if is_jj_workspace(cwd) {
216 +
        jj::Repository::new(cwd).git_repository()?
217 +
    } else {
218 +
        git::Repository::discover(cwd.to_path_buf())?
219 +
    };
220 +
    Brain::statuses(&repository)
221 +
}
222 +
223 +
/// Returns whether `cwd` is inside a Jujutsu workspace.
224 +
fn is_jj_workspace(cwd: &Path) -> bool {
225 +
    cwd.ancestors().any(|path| path.join(JJ_DIR).is_dir())
226 +
}
227 +
125 228
/// Hidden Git state holding one review's acceptance tree and comments.
126 229
///
127 230
/// The acceptance tree is the persistent source of truth for accepted review
128 231
/// content; comments are stored as a JSONL blob under a sibling ref. Both live
129 232
/// entirely inside the Git object store, so review state travels with the
141 244
    /// Current synthetic state commit.
142 245
    commit: Oid,
143 246
}
144 247
145 248
impl Brain {
146 -
    /// Returns the hidden Git ref for `review` under `namespace`.
147 -
    fn ref_for(namespace: &'static str, review: &str) -> Result<Qualified<'static>, Error> {
249 +
    /// Returns the hidden Git ref prefix for `namespace`.
250 +
    fn prefix_for(namespace: &'static str) -> Result<Qualified<'static>, Error> {
148 251
        let category = component(BRAIN_REF_CATEGORY)?;
149 252
        let namespace = component(namespace)?;
253 +
254 +
        Ok(Qualified::from_components(category, namespace, []))
255 +
    }
256 +
257 +
    /// Returns the hidden Git ref for `review` under `namespace`.
258 +
    fn ref_for(namespace: &'static str, review: &str) -> Result<Qualified<'static>, Error> {
259 +
        let prefix = Brain::prefix_for(namespace)?;
150 260
        let review = component(crate::comments::encode_component(review))?;
151 261
152 -
        Ok(Qualified::from_components(category, namespace, [review]))
262 +
        Ok(prefix.join(review))
263 +
    }
264 +
265 +
    /// Returns stored review statuses for all brain state refs.
266 +
    fn statuses(repository: &git::Repository) -> Result<Vec<BrainStatus>, Error> {
267 +
        let branches = repository.branches()?;
268 +
        let trunk = repository
269 +
            .trunk(&branches)?
270 +
            .ok_or_else(|| Error::Git("no trunk or master branch found".to_owned()))?;
271 +
        let trunk_rev = Rev::from(trunk.head);
272 +
        let mut stored = Brain::stored_reviews(repository)?;
273 +
        let mut statuses = Vec::new();
274 +
275 +
        for branch in &branches {
276 +
            let (relation, merge) = if branch.name == trunk.name {
277 +
                (AheadBehind::default(), MergeStatus::Clean)
278 +
            } else {
279 +
                relation_to_trunk(repository, &trunk_rev, &Rev::from(branch.head))?
280 +
            };
281 +
282 +
            if let Some(review) = stored.remove(&branch.name) {
283 +
                statuses.push(Brain::status_for_stored(
284 +
                    branch.name.clone(),
285 +
                    BrainStatusHead::Branch,
286 +
                    trunk.head,
287 +
                    relation,
288 +
                    merge,
289 +
                    review,
290 +
                ));
291 +
            } else {
292 +
                statuses.push(BrainStatus {
293 +
                    head: branch.name.clone(),
294 +
                    head_kind: BrainStatusHead::Branch,
295 +
                    state: BrainStatusState::NoState,
296 +
                    base_state: BrainStatusBaseState::Ok,
297 +
                    progress: ReviewProgress::default(),
298 +
                    relation,
299 +
                    merge,
300 +
                    comments: CommentStatus::None,
301 +
                    recency: repository.commit_time(branch.head)?,
302 +
                });
303 +
            }
304 +
        }
305 +
306 +
        for (review, stored) in stored {
307 +
            let target = Rev::try_from(review.as_str())
308 +
                .map_err(|error| Error::Usage(format!("target revision is invalid: {error}")))?;
309 +
            let (relation, merge) = relation_to_trunk(repository, &trunk_rev, &target)?;
310 +
            statuses.push(Brain::status_for_stored(
311 +
                review,
312 +
                BrainStatusHead::Stored,
313 +
                trunk.head,
314 +
                relation,
315 +
                merge,
316 +
                stored,
317 +
            ));
318 +
        }
319 +
        statuses.sort_by(status_order);
320 +
321 +
        Ok(statuses)
322 +
    }
323 +
324 +
    /// Returns stored review state keyed by decoded review identity.
325 +
    fn stored_reviews(
326 +
        repository: &git::Repository,
327 +
    ) -> Result<BTreeMap<String, StoredReview>, Error> {
328 +
        let prefix = Brain::prefix_for(STATE_REF_NAMESPACE)?;
329 +
        repository
330 +
            .refs(&prefix)?
331 +
            .into_iter()
332 +
            .map(|(reference, state)| {
333 +
                let encoded_review = review_from_ref(&prefix, &reference)?;
334 +
                let review = crate::comments::decode_component(&encoded_review);
335 +
                let base = repository.parent(state)?;
336 +
                let comments_ref = Brain::ref_for_encoded(COMMENTS_REF_NAMESPACE, &encoded_review)?;
337 +
                let brain = Brain {
338 +
                    repository: repository.clone(),
339 +
                    state_ref: reference,
340 +
                    comments_ref,
341 +
                    base,
342 +
                    commit: state,
343 +
                };
344 +
                let comments = brain.comment_status()?;
345 +
                let (head, progress) = brain.summary(&review)?;
346 +
                let recency = repository.commit_time(head)?;
347 +
348 +
                Ok((
349 +
                    review,
350 +
                    StoredReview {
351 +
                        base,
352 +
                        progress,
353 +
                        comments,
354 +
                        recency,
355 +
                    },
356 +
                ))
357 +
            })
358 +
            .collect()
359 +
    }
360 +
361 +
    /// Returns status for one stored review and branch relation.
362 +
    fn status_for_stored(
363 +
        head: String,
364 +
        head_kind: BrainStatusHead,
365 +
        current_base: Oid,
366 +
        relation: AheadBehind,
367 +
        merge: MergeStatus,
368 +
        stored: StoredReview,
369 +
    ) -> BrainStatus {
370 +
        BrainStatus {
371 +
            head,
372 +
            head_kind,
373 +
            state: brain_status_state(stored.progress),
374 +
            base_state: BrainStatusBaseState::from_base(stored.base, current_base),
375 +
            progress: stored.progress,
376 +
            relation,
377 +
            merge,
378 +
            comments: stored.comments,
379 +
            recency: stored.recency,
380 +
        }
381 +
    }
382 +
383 +
    /// Returns stored comment status for this review.
384 +
    fn comment_status(&self) -> Result<CommentStatus, Error> {
385 +
        let Some(text) = self.read_comments()? else {
386 +
            return Ok(CommentStatus::None);
387 +
        };
388 +
        let status = match crate::comments::ReviewComments::parse(&text) {
389 +
            Ok(comments) => CommentStatus::Count(comments.len()),
390 +
            Err(_) => CommentStatus::Invalid,
391 +
        };
392 +
        Ok(status)
393 +
    }
394 +
395 +
    /// Returns the hidden Git ref for already encoded `review` under `namespace`.
396 +
    fn ref_for_encoded(namespace: &'static str, review: &str) -> Result<Qualified<'static>, Error> {
397 +
        let prefix = Brain::prefix_for(namespace)?;
398 +
        let review = component(review.to_owned())?;
399 +
400 +
        Ok(prefix.join(review))
401 +
    }
402 +
403 +
    /// Returns the target commit and accepted-hunk progress for this review.
404 +
    fn summary(&self, review: &str) -> Result<(Oid, ReviewProgress), Error> {
405 +
        let base = Rev::from(self.base);
406 +
        let target = Rev::try_from(review)
407 +
            .map_err(|error| Error::Usage(format!("target revision is invalid: {error}")))?;
408 +
        let head = self.repository.commit_id(&target)?;
409 +
        let mut original = Vec::new();
410 +
411 +
        for (id, _) in self.repository.commits(&base, &target)? {
412 +
            let bytes = self.repository.commit_diff(id)?;
413 +
            let document = DiffDocument::decode_bytes(&bytes)?.split_hunks();
414 +
            original.extend(self.patch_ids(&document)?.into_values());
415 +
        }
416 +
417 +
        let accepted_ids = self.accepted_patch_ids()?;
418 +
        let accepted = original
419 +
            .iter()
420 +
            .filter(|patch_id| accepted_ids.contains(*patch_id))
421 +
            .count();
422 +
423 +
        Ok((
424 +
            head,
425 +
            ReviewProgress {
426 +
                accepted,
427 +
                total: original.len(),
428 +
            },
429 +
        ))
430 +
    }
431 +
432 +
    /// Returns patch ids present in the stored accepted-state diff.
433 +
    fn accepted_patch_ids(&self) -> Result<BTreeSet<PatchId>, Error> {
434 +
        let patch = self.repository.diff(self.base, self.commit)?;
435 +
        let document = DiffDocument::decode_str(&patch)?.split_hunks();
436 +
        let patch_ids = self.patch_ids(&document)?;
437 +
438 +
        Ok(patch_ids.into_values().collect())
439 +
    }
440 +
441 +
    /// Returns per-hunk patch ids from a decoded review document.
442 +
    ///
443 +
    /// All hunk patches are hashed by one `git patch-id` invocation.
444 +
    fn patch_ids(&self, document: &DiffDocument) -> Result<BTreeMap<HunkId, PatchId>, Error> {
445 +
        let mut ids = Vec::new();
446 +
        let mut patches = Vec::new();
447 +
448 +
        for file in &document.files {
449 +
            for hunk in &file.hunks {
450 +
                ids.push(hunk.id);
451 +
                patches.push(DiffDocument::for_hunks(file, [hunk.clone()]).to_unified_string()?);
452 +
            }
453 +
        }
454 +
        let patch_ids = self.repository.patch_ids(&patches)?;
455 +
456 +
        Ok(ids.into_iter().zip(patch_ids).collect())
153 457
    }
154 458
155 459
    /// Loads or initializes the hidden review state for one review.
156 460
    fn load(repository: git::Repository, base: Oid, review: &str) -> Result<Self, Error> {
157 461
        let state_ref = Brain::ref_for(STATE_REF_NAMESPACE, review)?;
333 637
        &self,
334 638
        original: &BTreeMap<HunkId, PatchId>,
335 639
        residual: &str,
336 640
    ) -> Result<BTreeSet<HunkId>, Error> {
337 641
        let residual = DiffDocument::decode_str(residual)?;
338 -
        let mut residual_ids = BTreeSet::new();
642 +
        let residual_ids: BTreeSet<_> = self.patch_ids(&residual)?.into_values().collect();
339 643
340 -
        for file in &residual.files {
341 -
            for hunk in &file.hunks {
342 -
                let patch_id = self.hunk_patch_id(file, hunk)?;
343 -
                residual_ids.insert(patch_id);
344 -
            }
345 -
        }
346 644
        Ok(accepted_hunks_from_patch_ids(original, &residual_ids))
347 645
    }
348 646
}
349 647
350 648
/// Returns original hunks whose patch ids are absent from the residual set.
356 654
        .iter()
357 655
        .filter_map(|(hunk, patch_id)| (!residual.contains(patch_id)).then_some(*hunk))
358 656
        .collect()
359 657
}
360 658
659 +
/// Returns trunk relation and merge status for `target`.
660 +
///
661 +
/// A branch that is only ahead or only behind merges trivially, so the merge
662 +
/// check only runs for diverged branches.
663 +
fn relation_to_trunk(
664 +
    repository: &git::Repository,
665 +
    trunk_rev: &Rev,
666 +
    target: &Rev,
667 +
) -> Result<(AheadBehind, MergeStatus), Error> {
668 +
    let relation = repository.ahead_behind(trunk_rev, target)?;
669 +
    let merge = if relation.ahead > 0 && relation.behind > 0 {
670 +
        repository.merge_status(trunk_rev, target)?
671 +
    } else {
672 +
        MergeStatus::Clean
673 +
    };
674 +
675 +
    Ok((relation, merge))
676 +
}
677 +
678 +
/// Orders status rows by review progress, comments, recency, and name.
679 +
fn status_order(left: &BrainStatus, right: &BrainStatus) -> Ordering {
680 +
    left.progress
681 +
        .cmp(&right.progress)
682 +
        .then_with(|| right.comments.cmp(&left.comments))
683 +
        .then_with(|| right.recency.cmp(&left.recency))
684 +
        .then_with(|| left.head.cmp(&right.head))
685 +
}
686 +
687 +
/// Returns the row status for stored review progress.
688 +
fn brain_status_state(progress: ReviewProgress) -> BrainStatusState {
689 +
    if progress.is_complete() {
690 +
        BrainStatusState::Approved
691 +
    } else {
692 +
        BrainStatusState::InReview
693 +
    }
694 +
}
695 +
361 696
/// Converts `input` to a slash-free refname component.
362 697
fn component(input: impl Into<String>) -> Result<Component<'static>, Error> {
363 698
    let refname = RefString::try_from(input.into())
364 699
        .map_err(|error| Error::Git(format!("invalid brain ref component: {error}")))?;
365 700
    Component::from_refstr(refname)
366 701
        .ok_or_else(|| Error::Git("invalid brain ref component: contains slash".to_owned()))
367 702
}
368 703
704 +
/// Returns the encoded review component from a state ref.
705 +
fn review_from_ref(prefix: &Qualified<'_>, reference: &Qualified<'_>) -> Result<String, Error> {
706 +
    reference
707 +
        .strip_prefix(prefix)
708 +
        .filter(|review| !review.is_empty() && !review.contains('/'))
709 +
        .map(|review| review.as_str().to_owned())
710 +
        .ok_or_else(|| Error::Git(format!("invalid brain state ref: {reference}")))
711 +
}
712 +
369 713
/// A [`Backend`] backed by the `git` command.
370 714
pub struct GitBackend {
371 715
    /// Git repository operations.
372 716
    repository: git::Repository,
373 717
    /// Base revision, the exclusive lower bound of the range.
crates/brain/src/comments.rs +43 -0
169 169
    /// Returns the author name used for newly authored comments.
170 170
    pub fn author(&self) -> &str {
171 171
        &self.author
172 172
    }
173 173
174 +
    /// Returns the number of stored comment rows.
175 +
    pub fn len(&self) -> usize {
176 +
        self.records.len()
177 +
    }
178 +
174 179
    /// Returns comments attached to `target`'s patch id, in storage order.
175 180
    fn matching(&self, target: &CommentTarget) -> Vec<Comment> {
176 181
        self.records
177 182
            .iter()
178 183
            .filter(|record| record.patch_id == target.patch_id)
336 341
        }
337 342
    }
338 343
    encoded
339 344
}
340 345
346 +
/// Decodes a review identity text from one encoded refname component.
347 +
pub(crate) fn decode_component(input: &str) -> String {
348 +
    let mut decoded = Vec::with_capacity(input.len());
349 +
    let mut bytes = input.as_bytes().iter().copied();
350 +
351 +
    while let Some(byte) = bytes.next() {
352 +
        if byte != b'%' {
353 +
            decoded.push(byte);
354 +
            continue;
355 +
        }
356 +
357 +
        let Some(high) = bytes.next() else {
358 +
            decoded.push(byte);
359 +
            break;
360 +
        };
361 +
        let Some(low) = bytes.next() else {
362 +
            decoded.extend([byte, high]);
363 +
            break;
364 +
        };
365 +
        match (hex_value(high), hex_value(low)) {
366 +
            (Some(high), Some(low)) => decoded.push(high << 4 | low),
367 +
            _ => decoded.extend([byte, high, low]),
368 +
        }
369 +
    }
370 +
371 +
    String::from_utf8_lossy(&decoded).into_owned()
372 +
}
373 +
374 +
/// Returns the numeric value of one hexadecimal digit.
375 +
fn hex_value(byte: u8) -> Option<u8> {
376 +
    match byte {
377 +
        b'0'..=b'9' => Some(byte - b'0'),
378 +
        b'a'..=b'f' => Some(byte - b'a' + 10),
379 +
        b'A'..=b'F' => Some(byte - b'A' + 10),
380 +
        _ => None,
381 +
    }
382 +
}
383 +
341 384
/// Returns the author name used for newly authored comments.
342 385
fn default_author() -> String {
343 386
    std::env::var("GIT_AUTHOR_NAME")
344 387
        .ok()
345 388
        .filter(|name| !name.trim().is_empty())
crates/brain/src/error.rs +6 -0
43 43
    fn from(error: DecodeError) -> Self {
44 44
        Self::Parse(error)
45 45
    }
46 46
}
47 47
48 +
impl From<lexopt::Error> for Error {
49 +
    fn from(error: lexopt::Error) -> Self {
50 +
        Self::Usage(error.to_string())
51 +
    }
52 +
}
53 +
48 54
impl From<RepoError> for Error {
49 55
    fn from(error: RepoError) -> Self {
50 56
        match error {
51 57
            RepoError::Io(e) => Self::Io(e),
52 58
            RepoError::Status(code) => Self::Backend(code),
crates/brain/src/main.rs +202 -34
19 19
use std::ffi::{OsStr, OsString};
20 20
use std::io::{self, Write as _};
21 21
use std::process::ExitCode;
22 22
23 23
use lexopt::prelude::*;
24 -
use rustik_diff::{Builtins, DiffOptions, FileTreeMode, HunkFocus};
25 -
use rustik_repo::Rev;
26 -
use rustik_tui::{ActionList, Dialog, Event, Key, Line, Size, Terminal};
24 +
use rustik_diff::{Builtins, DiffOptions, DiffPalette, FileTreeMode, HunkFocus};
25 +
use rustik_repo::{AheadBehind, MergeStatus, Rev};
26 +
use rustik_tui::{
27 +
    ActionList, Border, Color, Constraint, Dialog, Event, Key, Label, Line, Size, Style, Table,
28 +
    TableOptions, Terminal, colors,
29 +
};
27 30
use rustik_tui_termion as tui_termion;
28 31
29 -
use crate::comments::ReviewComments;
30 -
use crate::error::Error;
32 +
use backend::{
33 +
    BrainStatus, BrainStatusBaseState, BrainStatusHead, BrainStatusState, CommentStatus,
34 +
};
35 +
use comments::ReviewComments;
36 +
use error::Error;
31 37
32 38
/// Terminal backend used by the interactive viewer.
33 39
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
34 40
35 41
/// Command-line usage text.
36 -
const USAGE: &str = "usage: brain [--reset] diff <from> <to>";
42 +
const USAGE: &str = "usage: brain [status]\n       brain [--reset] diff <from> <to>";
43 +
/// Default output width used when terminal width is unknown.
44 +
const DEFAULT_STATUS_WIDTH: usize = 140;
45 +
/// Marker shown for approved review state: โœ”.
46 +
const APPROVED_STATUS_ICON: char = 'โœ”';
47 +
/// Marker shown for in-review state: โ—.
48 +
const IN_REVIEW_STATUS_ICON: char = 'โ—';
49 +
/// Marker shown when no brain state exists: โ—.
50 +
const NO_STATE_STATUS_ICON: char = 'โ—';
51 +
/// Marker shown as the review-state table heading.
52 +
const STATUS_HEADING_ICON: char = 'โ—‹';
37 53
38 54
/// Parsed command-line arguments.
39 55
#[derive(Debug, Eq, PartialEq)]
40 56
struct Args {
41 57
    /// How persisted review state should be loaded.
50 66
        let mut parser =
51 67
            lexopt::Parser::from_iter([OsString::from("brain")].into_iter().chain(args));
52 68
        let mut state = ReviewStateLoad::Existing;
53 69
        let mut command = None;
54 70
55 -
        while let Some(arg) = parser
56 -
            .next()
57 -
            .map_err(|error| Error::Usage(error.to_string()))?
58 -
        {
71 +
        while let Some(arg) = parser.next()? {
72 +
            if command.is_some() {
73 +
                return Err(Error::Usage(format!(
74 +
                    "unexpected argument: {arg:?}\n{USAGE}"
75 +
                )));
76 +
            }
59 77
            match arg {
60 78
                Long("reset") => state = ReviewStateLoad::Fresh,
79 +
                Value(command_name) if command_name == "status" => {
80 +
                    command = Some(Command::Status);
81 +
                }
61 82
                Value(command_name) if command_name == "diff" => {
62 -
                    let from = parser
63 -
                        .value()
64 -
                        .map_err(|error| Error::Usage(error.to_string()))?;
65 -
                    let to = parser
66 -
                        .value()
67 -
                        .map_err(|error| Error::Usage(error.to_string()))?;
68 -
                    if let Some(arg) = parser
69 -
                        .next()
70 -
                        .map_err(|error| Error::Usage(error.to_string()))?
71 -
                    {
72 -
                        return Err(Error::Usage(format!(
73 -
                            "unexpected argument: {arg:?}\n{USAGE}"
74 -
                        )));
75 -
                    }
76 -
                    let from = parse_revision("from", from)?;
77 -
                    let to = parse_revision("to", to)?;
83 +
                    let from = parse_revision("from", parser.value()?)?;
84 +
                    let to = parse_revision("to", parser.value()?)?;
78 85
79 86
                    command = Some(Command::Diff { from, to });
80 87
                }
81 88
                Value(value) => {
82 89
                    let value = value.to_string_lossy();
83 90
                    return Err(Error::Usage(format!("unknown command: {value}\n{USAGE}")));
84 91
                }
85 92
                _ => return Err(Error::Usage(USAGE.to_owned())),
86 93
            }
87 94
        }
88 -
        let command = command.ok_or_else(|| Error::Usage(USAGE.to_owned()))?;
95 +
        if state == ReviewStateLoad::Fresh && !matches!(command, Some(Command::Diff { .. })) {
96 +
            return Err(Error::Usage(USAGE.to_owned()));
97 +
        }
89 98
90 -
        Ok(Self { state, command })
99 +
        Ok(Self {
100 +
            state,
101 +
            command: command.unwrap_or(Command::Status),
102 +
        })
91 103
    }
92 104
}
93 105
94 106
/// Review command requested by the user.
95 107
#[derive(Debug, Eq, PartialEq)]
96 108
enum Command {
109 +
    /// Show stored review state.
110 +
    Status,
97 111
    /// Review the commits in `from..to`.
98 112
    Diff {
99 113
        /// Exclusive lower bound of the reviewed range.
100 114
        from: Rev,
101 115
        /// Inclusive upper bound of the reviewed range.
162 176
            ExitCode::FAILURE
163 177
        }
164 178
    }
165 179
}
166 180
167 -
/// Parses arguments, loads the review range, and runs the session.
181 +
/// Parses arguments and dispatches the requested command.
168 182
fn run(args: Vec<OsString>) -> Result<(), Error> {
169 183
    let args = Args::parse(args)?;
170 -
    let Command::Diff { from, to } = args.command;
184 +
    match args.command {
185 +
        Command::Status => run_status(),
186 +
        Command::Diff { from, to } => run_diff(args.state, from, to),
187 +
    }
188 +
}
171 189
190 +
/// Loads the review range and runs the interactive diff session.
191 +
fn run_diff(state: ReviewStateLoad, from: Rev, to: Rev) -> Result<(), Error> {
172 192
    let cwd = env::current_dir()?;
173 193
    let backend = <dyn backend::Backend>::from_path(&cwd, from, to)?;
174 194
    let mut terminal = None;
175 195
    let mut events = None;
176 -
    let brain = match args.state {
196 +
    let brain = match state {
177 197
        ReviewStateLoad::Existing => match backend.brain() {
178 198
            Ok(brain) => brain,
179 199
            Err(Error::StaleReviewState { .. }) => {
180 200
                let terminal = terminal.get_or_insert(open_terminal()?);
181 201
                let events = events.get_or_insert_with(session::Events::spawn);
242 262
243 263
    result?;
244 264
    cursor.map_err(Error::Io)
245 265
}
246 266
267 +
/// Prints the stored review status table.
268 +
fn run_status() -> Result<(), Error> {
269 +
    let cwd = env::current_dir()?;
270 +
    let statuses = backend::statuses(&cwd)?;
271 +
    let mut stdout = io::stdout().lock();
272 +
273 +
    for line in status_lines(&statuses, status_width()) {
274 +
        writeln!(stdout, "{}", line.styled())?;
275 +
    }
276 +
277 +
    Ok(())
278 +
}
279 +
280 +
/// Returns styled status output lines.
281 +
fn status_lines(statuses: &[BrainStatus], width: usize) -> Vec<Line> {
282 +
    if statuses.is_empty() {
283 +
        return vec![Line::new(Label::new("No branches.").fg(colors::fixed::DIM))];
284 +
    }
285 +
286 +
    let palette = DiffPalette::default();
287 +
    let mut table = Table::<6, Line>::new(TableOptions {
288 +
        border: Some(Border::new(colors::fixed::DIM)),
289 +
        ..TableOptions::bordered()
290 +
    });
291 +
    table.header([
292 +
        Line::new(Label::from_char(STATUS_HEADING_ICON).fg(colors::fixed::DIM)),
293 +
        status_heading("head"),
294 +
        status_heading("status"),
295 +
        status_heading("โ†–โ†˜"),
296 +
        status_heading("comments"),
297 +
        status_heading("progress"),
298 +
    ]);
299 +
    table.divider();
300 +
301 +
    for status in statuses {
302 +
        table.push([
303 +
            brain_state(status.state),
304 +
            status_head(status),
305 +
            review_status(status),
306 +
            ahead_behind(status.relation),
307 +
            comment_status(status.comments),
308 +
            session::progress_bar(status.progress, palette, colors::fixed::DIM),
309 +
        ]);
310 +
    }
311 +
    table.lines(Constraint::max(Size::new(width, usize::MAX)))
312 +
}
313 +
314 +
/// Returns a styled review status cell.
315 +
fn review_status(status: &BrainStatus) -> Line {
316 +
    match (status.base_state, status.merge) {
317 +
        (BrainStatusBaseState::Stale, _) => Line::new(Label::new("stale").fg(colors::fixed::DIM)),
318 +
        (_, MergeStatus::Conflicts) => {
319 +
            Line::new(Label::new("conflict").fg(colors::rgb::GREY_LIGHT))
320 +
        }
321 +
        (_, MergeStatus::Clean) => Line::new(Label::new("ok").fg(colors::rgb::GREEN)),
322 +
    }
323 +
}
324 +
325 +
/// Returns a styled status head cell.
326 +
fn status_head(status: &BrainStatus) -> Line {
327 +
    let color = match status.head_kind {
328 +
        BrainStatusHead::Branch => Color::Yellow,
329 +
        BrainStatusHead::Stored => Color::White,
330 +
    };
331 +
    Line::new(Label::new(&status.head).fg(color))
332 +
}
333 +
334 +
/// Returns a styled table heading cell.
335 +
fn status_heading(text: &str) -> Line {
336 +
    Line::new(Label::new(text).style(Style::default().fg(colors::rgb::GREY_LIGHT).bold()))
337 +
}
338 +
339 +
/// Returns a styled brain state glyph cell.
340 +
fn brain_state(state: BrainStatusState) -> Line {
341 +
    match state {
342 +
        BrainStatusState::Approved => {
343 +
            Line::new(Label::from_char(APPROVED_STATUS_ICON).fg(session::BRAIN_BADGE_BG))
344 +
        }
345 +
        BrainStatusState::InReview => {
346 +
            Line::new(Label::from_char(IN_REVIEW_STATUS_ICON).fg(session::BRAIN_BADGE_BG))
347 +
        }
348 +
        BrainStatusState::NoState => {
349 +
            Line::new(Label::from_char(NO_STATE_STATUS_ICON).fg(colors::fixed::DIM))
350 +
        }
351 +
    }
352 +
}
353 +
354 +
/// Returns a styled ahead/behind cell.
355 +
fn ahead_behind(relation: AheadBehind) -> Line {
356 +
    let ahead_color = if relation.ahead > 0 {
357 +
        colors::rgb::GREEN
358 +
    } else {
359 +
        colors::fixed::DIM
360 +
    };
361 +
    let behind_color = if relation.behind > 0 {
362 +
        colors::rgb::RED
363 +
    } else {
364 +
        colors::fixed::DIM
365 +
    };
366 +
367 +
    Line::new(Label::new("โ†–").fg(colors::fixed::DIM))
368 +
        .item(Label::new(&format!("{:<2}", relation.ahead)).fg(ahead_color))
369 +
        .item(Label::space())
370 +
        .item(Label::new("โ†˜").fg(colors::fixed::DIM))
371 +
        .item(Label::new(&format!("{:<2}", relation.behind)).fg(behind_color))
372 +
}
373 +
374 +
/// Returns a styled comment status cell.
375 +
fn comment_status(status: CommentStatus) -> Line {
376 +
    match status {
377 +
        CommentStatus::None => Line::new(Label::new("-").fg(colors::fixed::DIM)),
378 +
        CommentStatus::Count(0) => Line::new(Label::new("0").fg(colors::fixed::DIM)),
379 +
        CommentStatus::Count(count) => {
380 +
            Line::new(Label::new(&count.to_string()).fg(colors::rgb::TEAL))
381 +
        }
382 +
        CommentStatus::Invalid => Line::new(Label::new("invalid").fg(colors::rgb::RED)),
383 +
    }
384 +
}
385 +
386 +
/// Returns the target status table width.
387 +
///
388 +
/// Falls back to `COLUMNS`, then a fixed width, when stdout is not a terminal.
389 +
fn status_width() -> usize {
390 +
    tui_termion::term::viewport()
391 +
        .map(|size| size.cols)
392 +
        .or_else(|| {
393 +
            env::var("COLUMNS")
394 +
                .ok()
395 +
                .and_then(|value| value.parse().ok())
396 +
        })
397 +
        .filter(|width| *width > 0)
398 +
        .unwrap_or(DEFAULT_STATUS_WIDTH)
399 +
}
400 +
247 401
/// Parses one revision argument for the `diff` command.
248 402
fn parse_revision(name: &str, value: OsString) -> Result<Rev, Error> {
249 403
    let value = value
250 404
        .to_str()
251 405
        .ok_or_else(|| Error::Usage(format!("{name} revision must be valid UTF-8")))?;
316 470
317 471
        assert_eq!(parsed.state, ReviewStateLoad::Fresh);
318 472
    }
319 473
320 474
    #[test]
321 -
    fn rejects_missing_diff_command() {
322 -
        let error = Args::parse(args(&["main", "HEAD"])).unwrap_err();
475 +
    fn parses_status_command() {
476 +
        let parsed = Args::parse(args(&["status"])).unwrap();
477 +
478 +
        assert_eq!(parsed.command, Command::Status);
479 +
    }
480 +
481 +
    #[test]
482 +
    fn defaults_to_status_command() {
483 +
        let parsed = Args::parse(args(&[])).unwrap();
484 +
485 +
        assert_eq!(parsed.command, Command::Status);
486 +
    }
487 +
488 +
    #[test]
489 +
    fn rejects_reset_without_diff_command() {
490 +
        let error = Args::parse(args(&["--reset"])).unwrap_err();
323 491
324 -
        assert!(error.to_string().contains("unknown command"));
492 +
        assert!(error.to_string().contains("usage: brain"));
325 493
    }
326 494
}
crates/brain/src/session.rs +2 -0
25 25
use commit::{CommitReview, CommitSlot};
26 26
use event::{ContextFetch, Resize, TerminalEvent, Update, context_change};
27 27
use hunk::{CommentEdit, HunkView};
28 28
use status::{Status, commit_row, viewer_area};
29 29
30 +
pub(crate) use status::{BRAIN_BADGE_BG, progress_bar};
31 +
30 32
/// Terminal backend used by the interactive viewer.
31 33
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
32 34
33 35
/// Active view in the session.
34 36
enum Mode {
crates/brain/src/session/commit.rs +1 -29
1 1
//! Per-commit review state for the session.
2 2
3 3
use std::collections::BTreeMap;
4 -
use std::mem;
5 4
6 5
use rustik_diff::{DiffDocument, DiffOptions, DiffViewer, Encode as _, FileDiff, FileId, HunkId};
7 6
use rustik_repo::PatchId;
8 7
9 8
use crate::backend::{Brain, Commit};
60 59
        document: DiffDocument,
61 60
        options: DiffOptions,
62 61
        brain: &Brain,
63 62
        store: &ReviewComments,
64 63
    ) -> Result<Self, Error> {
65 -
        let document = Self::split_review_hunks(document);
64 +
        let document = document.split_hunks();
66 65
        let viewer = DiffViewer::new(document, options);
67 66
        let files = viewer.document().files.clone();
68 67
        let heading = format!("{} {}", commit.id.short(), commit.summary);
69 68
        let mut hunk_patches = BTreeMap::new();
70 69
        let mut patch_ids = BTreeMap::new();
105 104
        loaded.refresh_decorations();
106 105
107 106
        Ok(loaded)
108 107
    }
109 108
110 -
    /// Splits multi-change hunks into independently reviewable hunks.
111 -
    ///
112 -
    /// The split runs before patch ids, comments, and viewer state are built,
113 -
    /// so split pieces have stable hunk identities across reloads.
114 -
    fn split_review_hunks(mut document: DiffDocument) -> DiffDocument {
115 -
        let mut next = 0;
116 -
        for file in &mut document.files {
117 -
            let mut hunks = Vec::with_capacity(file.hunks.len());
118 -
            for hunk in mem::take(&mut file.hunks) {
119 -
                if let Some(split) = hunk.split() {
120 -
                    for mut hunk in split {
121 -
                        hunk.id = HunkId::new(next);
122 -
                        next += 1;
123 -
                        hunks.push(hunk);
124 -
                    }
125 -
                } else {
126 -
                    let mut hunk = hunk;
127 -
                    hunk.id = HunkId::new(next);
128 -
                    next += 1;
129 -
                    hunks.push(hunk);
130 -
                }
131 -
            }
132 -
            file.hunks = hunks;
133 -
        }
134 -
        document
135 -
    }
136 -
137 109
    /// Reinstalls a fresh decoration snapshot on the viewer.
138 110
    ///
139 111
    /// Decorations are immutable snapshots, so this must run after every
140 112
    /// change to acceptance or comment state for the viewer to observe it.
141 113
    pub(super) fn refresh_decorations(&mut self) {
a.rs +0 -0
crates/brain/src/session/status.rs +25 -18
18 18
const FOOTER_ROWS: usize = 1;
19 19
/// Foreground color for dim footer text.
20 20
const FOOTER_FG: Color = Color::Fixed(240);
21 21
/// Background color for the footer row, matching file border chrome.
22 22
const FOOTER_BG: Color = colors::FAINT;
23 -
/// Background color for the application badge.
24 -
const APP_BADGE_BG: Color = Color::RGB(124, 36, 32);
23 +
/// Background color for the brain application badge.
24 +
pub(crate) const BRAIN_BADGE_BG: Color = Color::RGB(124, 36, 32);
25 25
/// Background color for the active-mode badge.
26 26
const MODE_BADGE_BG: Color = Color::RGB(68, 68, 68);
27 27
/// Foreground color for the current commit hash.
28 28
const FOOTER_HASH_FG: Color = Color::Fixed(250);
29 29
/// Foreground color for neutral footer values.
116 116
    fn left_status(&self) -> Line {
117 117
        Line::blank()
118 118
            .item(
119 119
                Label::new(" brain ")
120 120
                    .fg(Color::White)
121 -
                    .bg(APP_BADGE_BG)
121 +
                    .bg(BRAIN_BADGE_BG)
122 122
                    .style(Style::default().bold()),
123 123
            )
124 124
            .item(
125 125
                Label::new(&format!(" {} ", self.mode))
126 126
                    .fg(Color::White)
148 148
        };
149 149
        let files = self.stats.files_changed;
150 150
        let plural = if files == 1 { "" } else { "s" };
151 151
152 152
        Line::blank()
153 -
            .extend(Self::progress_bar(self.progress, self.palette))
153 +
            .extend(progress_bar(self.progress, self.palette, FOOTER_FG))
154 154
            .item(Label::space())
155 155
            .item(Label::new(&format!("+{}", self.stats.insertions)).fg(self.palette.positive_fg))
156 156
            .item(Label::space())
157 157
            .item(Label::new(&format!("-{}", self.stats.deletions)).fg(self.palette.negative_fg))
158 158
            .item(Label::new(FOOTER_SEPARATOR).fg(FOOTER_FG))
162 162
            .item(Label::space())
163 163
            .item(Label::new(FULL_FILE_MODE_ICON).fg(full_file_fg))
164 164
            .item(Label::space())
165 165
            .style(Style::default().bg(FOOTER_BG))
166 166
    }
167 +
}
167 168
168 -
    /// Returns a compact commit review progress bar.
169 -
    fn progress_bar(progress: ReviewProgress, palette: DiffPalette) -> Line {
170 -
        let filled = progress
171 -
            .accepted
172 -
            .saturating_mul(COMMIT_PROGRESS_BAR_WIDTH)
173 -
            .checked_div(progress.total)
174 -
            .unwrap_or(0)
175 -
            .min(COMMIT_PROGRESS_BAR_WIDTH);
176 -
        let empty = COMMIT_PROGRESS_BAR_WIDTH - filled;
177 -
178 -
        Line::blank()
179 -
            .item(Label::new(&COMMIT_PROGRESS_BAR_GLYPH.repeat(filled)).fg(palette.positive_fg))
180 -
            .item(Label::new(&COMMIT_PROGRESS_BAR_GLYPH.repeat(empty)).fg(FOOTER_FG))
181 -
    }
169 +
/// Returns a compact commit review progress bar.
170 +
///
171 +
/// The empty segment renders in `empty_fg`, chosen by the caller to fit its
172 +
/// background.
173 +
pub(crate) fn progress_bar(
174 +
    progress: ReviewProgress,
175 +
    palette: DiffPalette,
176 +
    empty_fg: Color,
177 +
) -> Line {
178 +
    let filled = progress
179 +
        .accepted
180 +
        .saturating_mul(COMMIT_PROGRESS_BAR_WIDTH)
181 +
        .checked_div(progress.total)
182 +
        .unwrap_or(0)
183 +
        .min(COMMIT_PROGRESS_BAR_WIDTH);
184 +
    let empty = COMMIT_PROGRESS_BAR_WIDTH - filled;
185 +
186 +
    Line::blank()
187 +
        .item(Label::new(&COMMIT_PROGRESS_BAR_GLYPH.repeat(filled)).fg(palette.positive_fg))
188 +
        .item(Label::new(&COMMIT_PROGRESS_BAR_GLYPH.repeat(empty)).fg(empty_fg))
182 189
}
183 190
184 191
/// Returns the viewer area above the footer chrome.
185 192
pub(super) fn viewer_area(area: Rect) -> Rect {
186 193
    Status::areas(area).0
crates/diff/src/decorate.rs +25 -1
4 4
//! nothing about approval state, comments, or any other host concept. A host
5 5
//! application owns those concerns and feeds per-file and per-hunk decorations
6 6
//! into the viewer through the [`DiffDecorator`] trait, which the renderer
7 7
//! queries by [`FileId`] and [`HunkId`] while drawing each frame.
8 8
9 -
use std::fmt;
9 +
use std::{cmp::Ordering, fmt};
10 10
11 11
use rustik_tui as tui;
12 12
use tui::{Line, Paint, Style};
13 13
14 14
use crate::{FileId, HunkId};
64 64
    pub fn is_complete(self) -> bool {
65 65
        self.total > 0 && self.accepted >= self.total
66 66
    }
67 67
}
68 68
69 +
impl Ord for ReviewProgress {
70 +
    fn cmp(&self, other: &Self) -> Ordering {
71 +
        match (self.total == 0, other.total == 0) {
72 +
            (true, true) => self.accepted.cmp(&other.accepted),
73 +
            (true, false) => Ordering::Greater,
74 +
            (false, true) => Ordering::Less,
75 +
            (false, false) => {
76 +
                let left = (self.accepted as u128) * (other.total as u128);
77 +
                let right = (other.accepted as u128) * (self.total as u128);
78 +
79 +
                left.cmp(&right)
80 +
                    .then_with(|| self.accepted.cmp(&other.accepted))
81 +
                    .then_with(|| self.total.cmp(&other.total))
82 +
            }
83 +
        }
84 +
    }
85 +
}
86 +
87 +
impl PartialOrd for ReviewProgress {
88 +
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
89 +
        Some(self.cmp(other))
90 +
    }
91 +
}
92 +
69 93
/// Decoration overlaid on a hunk.
70 94
///
71 95
/// Decorations never add rows: the corner is drawn over the hunk's first body
72 96
/// row, and the style is composed onto the hunk's existing body rows.
73 97
#[derive(Clone, Debug, Default)]
crates/diff/src/document.rs +28 -0
590 590
                header: file.header.clone(),
591 591
                hunks: hunks.into_iter().collect(),
592 592
            }],
593 593
        }
594 594
    }
595 +
596 +
    /// Splits multi-change hunks into independently reviewable hunks.
597 +
    ///
598 +
    /// Hunk ids are reassigned sequentially across the whole document, so the
599 +
    /// split must run before any per-hunk state is derived for pieces to keep
600 +
    /// stable identities across reloads.
601 +
    pub fn split_hunks(mut self) -> Self {
602 +
        let mut next = 0;
603 +
        for file in &mut self.files {
604 +
            let mut hunks = Vec::with_capacity(file.hunks.len());
605 +
            for hunk in std::mem::take(&mut file.hunks) {
606 +
                if let Some(split) = hunk.split() {
607 +
                    for mut hunk in split {
608 +
                        hunk.id = HunkId::new(next);
609 +
                        next += 1;
610 +
                        hunks.push(hunk);
611 +
                    }
612 +
                } else {
613 +
                    let mut hunk = hunk;
614 +
                    hunk.id = HunkId::new(next);
615 +
                    next += 1;
616 +
                    hunks.push(hunk);
617 +
                }
618 +
            }
619 +
            file.hunks = hunks;
620 +
        }
621 +
        self
622 +
    }
595 623
}
596 624
597 625
/// Half-open range of non-context lines inside a hunk.
598 626
#[derive(Clone, Copy, Debug)]
599 627
struct ChangeGroup {
a.txt +0 -0
a +0 -0
crates/repo/src/git.rs +200 -1
8 8
use std::process::{Command, Output, Stdio};
9 9
use std::time::{SystemTime, UNIX_EPOCH};
10 10
11 11
use self::refs::Qualified;
12 12
use crate::{
13 -
    DiffRepository, DiffStat, Oid, PatchId, ReadRepository, RepoError, Rev, WriteRepository,
13 +
    AheadBehind, Branch, CommitTime, DiffRepository, DiffStat, MergeStatus, Oid, PatchId,
14 +
    ReadRepository, RepoError, Rev, WriteRepository,
14 15
};
15 16
16 17
/// Git reference names and refspecs.
17 18
pub mod refs;
18 19
238 239
            .map_err(|_| RepoError::Git(format!("invalid oid from {reference}")))?;
239 240
240 241
        Ok(Some(oid))
241 242
    }
242 243
244 +
    /// Returns refs below `prefix`, sorted by refname.
245 +
    fn refs(&self, prefix: &Qualified<'_>) -> Result<Vec<(Qualified<'static>, Oid)>, RepoError> {
246 +
        let bytes = self.git(
247 +
            "for-each-ref",
248 +
            &["--format=%(refname) %(objectname)", prefix.as_str()],
249 +
        )?;
250 +
        let text = utf8(bytes)?;
251 +
        text.lines()
252 +
            .map(|line| {
253 +
                let (refname, object) = line
254 +
                    .split_once(' ')
255 +
                    .ok_or_else(|| RepoError::Git(format!("invalid for-each-ref line: {line}")))?;
256 +
                let refname = refs::RefString::try_from(refname.to_owned())
257 +
                    .map_err(|error| RepoError::Git(format!("invalid refname: {error}")))?;
258 +
                let reference = Qualified::from_refstr(refname.as_refstr())
259 +
                    .ok_or_else(|| RepoError::Git(format!("unqualified refname: {refname}")))?
260 +
                    .into_owned();
261 +
                let oid = object
262 +
                    .parse()
263 +
                    .map_err(|_| RepoError::Git(format!("invalid oid from {reference}")))?;
264 +
265 +
                Ok((reference, oid))
266 +
            })
267 +
            .collect()
268 +
    }
269 +
270 +
    /// Returns local branches, sorted by branch name.
271 +
    fn branches(&self) -> Result<Vec<Branch>, RepoError> {
272 +
        let bytes = self.git(
273 +
            "for-each-ref",
274 +
            &["--format=%(refname:short)%00%(objectname)", "refs/heads"],
275 +
        )?;
276 +
        let text = utf8(bytes)?;
277 +
        text.lines()
278 +
            .map(|line| {
279 +
                let (name, head) = line
280 +
                    .split_once('\0')
281 +
                    .ok_or_else(|| RepoError::Git(format!("invalid branch line: {line}")))?;
282 +
                let head = head
283 +
                    .parse()
284 +
                    .map_err(|_| RepoError::Git(format!("invalid branch head: {head}")))?;
285 +
286 +
                Ok(Branch {
287 +
                    name: name.to_owned(),
288 +
                    head,
289 +
                })
290 +
            })
291 +
            .collect()
292 +
    }
293 +
294 +
    /// Returns a Git configuration value, if set.
295 +
    fn config(&self, key: &str) -> Result<Option<String>, RepoError> {
296 +
        let output = self.run("config", &["--get", key], Opts::default())?;
297 +
        if !output.status.success() {
298 +
            return Ok(None);
299 +
        }
300 +
        let value = utf8(output.stdout)?;
301 +
        let value = value.trim().to_owned();
302 +
303 +
        Ok((!value.is_empty()).then_some(value))
304 +
    }
305 +
306 +
    /// Returns the repository trunk branch among `branches`.
307 +
    fn trunk(&self, branches: &[Branch]) -> Result<Option<Branch>, RepoError> {
308 +
        let default = self.default_branch()?;
309 +
        Ok(default
310 +
            .as_deref()
311 +
            .and_then(|name| branches.iter().find(|branch| branch.name == name))
312 +
            .or_else(|| branches.iter().find(|branch| branch.name == "master"))
313 +
            .cloned())
314 +
    }
315 +
316 +
    /// Returns ahead and behind counts for `target` relative to `base`.
317 +
    fn ahead_behind(&self, base: &Rev, target: &Rev) -> Result<AheadBehind, RepoError> {
318 +
        let range = format!("{}...{}", base.as_str(), target.as_str());
319 +
        let bytes = self.git("rev-list", &["--left-right", "--count", &range])?;
320 +
        let text = utf8(bytes)?;
321 +
        let mut fields = text.split_whitespace();
322 +
        let behind = fields
323 +
            .next()
324 +
            .ok_or_else(|| RepoError::Git("missing behind count".to_owned()))?
325 +
            .parse()
326 +
            .map_err(|_| RepoError::Git("invalid behind count".to_owned()))?;
327 +
        let ahead = fields
328 +
            .next()
329 +
            .ok_or_else(|| RepoError::Git("missing ahead count".to_owned()))?
330 +
            .parse()
331 +
            .map_err(|_| RepoError::Git("invalid ahead count".to_owned()))?;
332 +
333 +
        Ok(AheadBehind { ahead, behind })
334 +
    }
335 +
336 +
    /// Returns whether `target` would merge into `base` with conflicts.
337 +
    fn merge_status(&self, base: &Rev, target: &Rev) -> Result<MergeStatus, RepoError> {
338 +
        let merge_base = self.git("merge-base", &[base.as_str(), target.as_str()])?;
339 +
        let merge_base = utf8(merge_base)?;
340 +
        let merge_base = merge_base.trim();
341 +
        let bytes = self.git(
342 +
            "merge-tree",
343 +
            &[
344 +
                "--trivial-merge",
345 +
                merge_base,
346 +
                base.as_str(),
347 +
                target.as_str(),
348 +
            ],
349 +
        )?;
350 +
        let text = utf8(bytes)?;
351 +
        if text.trim().is_empty() {
352 +
            Ok(MergeStatus::Clean)
353 +
        } else {
354 +
            Ok(MergeStatus::Conflicts)
355 +
        }
356 +
    }
357 +
243 358
    /// Returns the single parent of `commit`, or an error if it has more or fewer.
244 359
    fn parent(&self, commit: Oid) -> Result<Oid, RepoError> {
245 360
        let commit = commit.to_string();
246 361
        let bytes = self.git("show", &["-s", "--format=%P", &commit])?;
247 362
        let text = utf8(bytes)?;
262 377
        let commit = commit.to_string();
263 378
        self.git("show", &["-s", "--format=%B", &commit])
264 379
            .and_then(utf8)
265 380
    }
266 381
382 +
    /// Returns the committer timestamp for `commit`.
383 +
    fn commit_time(&self, commit: Oid) -> Result<CommitTime, RepoError> {
384 +
        let commit = commit.to_string();
385 +
        let text = self.git("show", &["-s", "--format=%ct", &commit])?;
386 +
        let seconds = utf8(text)?
387 +
            .trim()
388 +
            .parse()
389 +
            .map_err(|_| RepoError::Git("invalid commit timestamp".to_owned()))?;
390 +
391 +
        Ok(CommitTime { seconds })
392 +
    }
393 +
267 394
    /// Returns each commit's aggregated diff size, in the given order.
268 395
    ///
269 396
    /// All stats come from one `git log --shortstat` invocation so callers can
270 397
    /// size a whole review range without a subprocess per commit. Commits with
271 398
    /// no shortstat output (empty diffs, unwalked merges) report zero stats.
336 463
        let id = stdout.split_once(' ').map_or(stdout.trim(), |(id, _)| id);
337 464
338 465
        Ok(PatchId(id.to_owned()))
339 466
    }
340 467
468 +
    /// Computes stable Git patch ids for many patches in one invocation.
469 +
    ///
470 +
    /// The patches are streamed to a single `git patch-id` process, separated
471 +
    /// by synthetic `commit` headers whose ids map output rows back to input
472 +
    /// positions. Patches with no content report the default patch id.
473 +
    fn patch_ids(&self, patches: &[String]) -> Result<Vec<PatchId>, RepoError> {
474 +
        if patches.is_empty() {
475 +
            return Ok(Vec::new());
476 +
        }
477 +
        let mut stream = String::new();
478 +
        for (index, patch) in patches.iter().enumerate() {
479 +
            stream.push_str(&format!("commit {index:040x}\n"));
480 +
            stream.push_str(patch);
481 +
            if !patch.ends_with('\n') {
482 +
                stream.push('\n');
483 +
            }
484 +
        }
485 +
        let output = self.run(
486 +
            "patch-id",
487 +
            &["--stable"],
488 +
            Opts {
489 +
                stdin: Some(stream.as_bytes()),
490 +
                ..Opts::default()
491 +
            },
492 +
        )?;
493 +
        if !output.status.success() {
494 +
            return Err(RepoError::git(&output));
495 +
        }
496 +
        let stdout = utf8(output.stdout)?;
497 +
        let mut by_commit = BTreeMap::new();
498 +
        for line in stdout.lines() {
499 +
            if let Some((id, commit)) = line.split_once(' ') {
500 +
                by_commit.insert(commit.trim().to_owned(), PatchId(id.to_owned()));
501 +
            }
502 +
        }
503 +
        Ok((0..patches.len())
504 +
            .map(|index| {
505 +
                by_commit
506 +
                    .remove(&format!("{index:040x}"))
507 +
                    .unwrap_or_default()
508 +
            })
509 +
            .collect())
510 +
    }
511 +
341 512
    /// Computes a three-way merge tree and returns the resulting tree id.
342 513
    fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result<Oid, RepoError> {
343 514
        let merge_base = merge_base.to_string();
344 515
        let ours = ours.to_string();
345 516
        let theirs = theirs.to_string();
475 646
        Ok(())
476 647
    }
477 648
}
478 649
479 650
impl Repository {
651 +
    /// Returns the repository default branch name, if one is configured.
652 +
    fn default_branch(&self) -> Result<Option<String>, RepoError> {
653 +
        if let Some(name) = self.remote_default_branch()? {
654 +
            return Ok(Some(name));
655 +
        }
656 +
        self.config("init.defaultBranch")
657 +
    }
658 +
659 +
    /// Returns the default branch reported by `origin/HEAD`, if present.
660 +
    fn remote_default_branch(&self) -> Result<Option<String>, RepoError> {
661 +
        let output = self.run(
662 +
            "symbolic-ref",
663 +
            &["--quiet", "--short", "refs/remotes/origin/HEAD"],
664 +
            Opts::default(),
665 +
        )?;
666 +
        if !output.status.success() {
667 +
            return Ok(None);
668 +
        }
669 +
        let name = utf8(output.stdout)?;
670 +
        let name = name
671 +
            .trim()
672 +
            .strip_prefix("origin/")
673 +
            .unwrap_or_else(|| name.trim())
674 +
            .to_owned();
675 +
676 +
        Ok((!name.is_empty()).then_some(name))
677 +
    }
678 +
480 679
    /// Applies or reverses a Git-format patch against an isolated tree.
481 680
    fn apply_patch_to_tree_with_direction(
482 681
        &self,
483 682
        base: Oid,
484 683
        patch: &str,
crates/repo/src/lib.rs +67 -0
120 120
        }
121 121
        Ok(Self(value.to_owned()))
122 122
    }
123 123
}
124 124
125 +
impl From<Oid> for Rev {
126 +
    fn from(oid: Oid) -> Self {
127 +
        Self(oid.to_string())
128 +
    }
129 +
}
130 +
131 +
/// Local branch head.
132 +
#[derive(Clone, Debug, Eq, PartialEq)]
133 +
pub struct Branch {
134 +
    /// Short branch name.
135 +
    pub name: String,
136 +
    /// Commit at the branch tip.
137 +
    pub head: Oid,
138 +
}
139 +
140 +
/// Commit timestamp in seconds since the Unix epoch.
141 +
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
142 +
pub struct CommitTime {
143 +
    /// Seconds since the Unix epoch in the committer timestamp.
144 +
    pub seconds: i64,
145 +
}
146 +
147 +
/// Commit counts between a base and target revision.
148 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
149 +
pub struct AheadBehind {
150 +
    /// Commits reachable from the target but not the base.
151 +
    pub ahead: usize,
152 +
    /// Commits reachable from the base but not the target.
153 +
    pub behind: usize,
154 +
}
155 +
156 +
/// Whether a target can be merged into a base without content conflicts.
157 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
158 +
pub enum MergeStatus {
159 +
    /// The merge does not report content conflicts.
160 +
    Clean,
161 +
    /// The merge reports content conflicts.
162 +
    Conflicts,
163 +
}
164 +
125 165
/// Repository operations that read commits, objects, refs, and derived data.
126 166
pub trait ReadRepository {
127 167
    /// Resolves a revision reference to a commit id.
128 168
    fn commit_id(&self, rev: &Rev) -> Result<Oid, RepoError>;
129 169
131 171
    fn tree_id(&self, object: Oid) -> Result<Oid, RepoError>;
132 172
133 173
    /// Returns the current commit stored in `reference`, if the ref exists.
134 174
    fn optional_ref(&self, reference: &Qualified<'_>) -> Result<Option<Oid>, RepoError>;
135 175
176 +
    /// Returns refs below `prefix`, sorted by refname.
177 +
    fn refs(&self, prefix: &Qualified<'_>) -> Result<Vec<(Qualified<'static>, Oid)>, RepoError>;
178 +
179 +
    /// Returns local branches, sorted by branch name.
180 +
    fn branches(&self) -> Result<Vec<Branch>, RepoError>;
181 +
182 +
    /// Returns a Git configuration value, if set.
183 +
    fn config(&self, key: &str) -> Result<Option<String>, RepoError>;
184 +
185 +
    /// Returns the repository trunk branch among `branches`.
186 +
    ///
187 +
    /// The trunk is the remote default branch when configured, the
188 +
    /// `init.defaultBranch` branch when configured, or `master` otherwise.
189 +
    fn trunk(&self, branches: &[Branch]) -> Result<Option<Branch>, RepoError>;
190 +
191 +
    /// Returns ahead and behind counts for `target` relative to `base`.
192 +
    fn ahead_behind(&self, base: &Rev, target: &Rev) -> Result<AheadBehind, RepoError>;
193 +
194 +
    /// Returns whether `target` would merge into `base` with conflicts.
195 +
    fn merge_status(&self, base: &Rev, target: &Rev) -> Result<MergeStatus, RepoError>;
196 +
136 197
    /// Returns the single parent of `commit`, or an error if it has more or fewer.
137 198
    fn parent(&self, commit: Oid) -> Result<Oid, RepoError>;
138 199
139 200
    /// Returns the full commit message for `commit`.
140 201
    fn commit_message(&self, commit: Oid) -> Result<String, RepoError>;
141 202
203 +
    /// Returns the committer timestamp for `commit`.
204 +
    fn commit_time(&self, commit: Oid) -> Result<CommitTime, RepoError>;
205 +
142 206
    /// Returns each commit's aggregated diff size, in the given order.
143 207
    fn commit_stats(&self, commits: &[Oid]) -> Result<Vec<DiffStat>, RepoError>;
144 208
145 209
    /// Reads a blob object's bytes.
146 210
    fn cat_blob(&self, blob: Oid) -> Result<Vec<u8>, RepoError>;
149 213
    fn diff(&self, from: Oid, to: Oid) -> Result<String, RepoError>;
150 214
151 215
    /// Computes a stable Git patch id for `patch` text.
152 216
    fn patch_id(&self, patch: &str) -> Result<PatchId, RepoError>;
153 217
218 +
    /// Computes stable Git patch ids for many patches in one invocation.
219 +
    fn patch_ids(&self, patches: &[String]) -> Result<Vec<PatchId>, RepoError>;
220 +
154 221
    /// Computes a three-way merge tree and returns the resulting tree id.
155 222
    fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result<Oid, RepoError>;
156 223
157 224
    /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs.
158 225
    fn commits(&self, base: &Rev, target: &Rev) -> Result<Vec<(Oid, String)>, RepoError>;
crates/tui-termion/src/term.rs +1 -1
127 127
                .open(STDERR_DEVICE)
128 128
        })
129 129
}
130 130
131 131
/// Returns the current terminal viewport size.
132 -
fn viewport() -> Option<Size> {
132 +
pub fn viewport() -> Option<Size> {
133 133
    termion::terminal_size()
134 134
        .map(|(cols, rows)| Size::new(cols as usize, rows as usize))
135 135
        .ok()
136 136
}
137 137