brain: Initialize new crate
503310581c199bf0500d7a20ede32069586976ba
1 parent
cafbb5ad
Cargo.lock
+18 -4
| 30 | 30 | source = "registry+https://github.com/rust-lang/crates.io-index" |
|
| 31 | 31 | checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" |
|
| 32 | 32 | ||
| 33 | 33 | [[package]] |
|
| 34 | 34 | name = "microserde" |
|
| 35 | - | version = "0.2.0" |
|
| 35 | + | version = "0.3.1" |
|
| 36 | 36 | source = "registry+https://github.com/rust-lang/crates.io-index" |
|
| 37 | - | checksum = "bcec4fadec845fca55c475f81f7adabe9151b7e16c1d090d95f4eed29ff0412c" |
|
| 37 | + | checksum = "94f3c0f398300b284c7e012a51b00175b494543a8dedf1f45cfe814c075c0f08" |
|
| 38 | 38 | dependencies = [ |
|
| 39 | 39 | "microserde-derive", |
|
| 40 | 40 | ] |
|
| 41 | 41 | ||
| 42 | 42 | [[package]] |
|
| 43 | 43 | name = "microserde-derive" |
|
| 44 | - | version = "0.2.0" |
|
| 44 | + | version = "0.3.0" |
|
| 45 | 45 | source = "registry+https://github.com/rust-lang/crates.io-index" |
|
| 46 | - | checksum = "ab91f2f9f9c8079c5ebab098deb191eaff87107b2d044041520a499b0af1e08c" |
|
| 46 | + | checksum = "139bb33aa12a2aa815ac9507866421ad77df215d18b5068e1feca9948df120eb" |
|
| 47 | 47 | dependencies = [ |
|
| 48 | 48 | "proc-macro2", |
|
| 49 | 49 | "quote", |
|
| 50 | 50 | "syn", |
|
| 51 | 51 | ] |
| 117 | 117 | "rustik-highlight", |
|
| 118 | 118 | "rustik-tui", |
|
| 119 | 119 | "shlex", |
|
| 120 | 120 | ] |
|
| 121 | 121 | ||
| 122 | + | [[package]] |
|
| 123 | + | name = "rustik-brain" |
|
| 124 | + | version = "0.2.0" |
|
| 125 | + | dependencies = [ |
|
| 126 | + | "microserde", |
|
| 127 | + | "rustik-diff", |
|
| 128 | + | "rustik-repo", |
|
| 129 | + | "rustik-tui", |
|
| 130 | + | "rustik-tui-termion", |
|
| 131 | + | ] |
|
| 132 | + | ||
| 122 | 133 | [[package]] |
|
| 123 | 134 | name = "rustik-diff" |
|
| 124 | 135 | version = "0.2.0" |
|
| 125 | 136 | dependencies = [ |
|
| 126 | 137 | "rustik-highlight", |
| 147 | 158 | ] |
|
| 148 | 159 | ||
| 149 | 160 | [[package]] |
|
| 150 | 161 | name = "rustik-repo" |
|
| 151 | 162 | version = "0.2.0" |
|
| 163 | + | dependencies = [ |
|
| 164 | + | "microserde", |
|
| 165 | + | ] |
|
| 152 | 166 | ||
| 153 | 167 | [[package]] |
|
| 154 | 168 | name = "rustik-signals" |
|
| 155 | 169 | version = "0.2.0" |
|
| 156 | 170 | dependencies = [ |
Cargo.toml
+2 -1
| 1 | 1 | [workspace] |
|
| 2 | 2 | members = [ |
|
| 3 | + | "crates/brain", |
|
| 3 | 4 | "crates/diff", |
|
| 4 | 5 | "crates/files", |
|
| 5 | 6 | "crates/highlight", |
|
| 6 | 7 | "crates/repo", |
|
| 7 | 8 | "crates/signals", |
| 46 | 47 | license = "MIT" |
|
| 47 | 48 | ||
| 48 | 49 | [workspace.dependencies] |
|
| 49 | 50 | libc = { version = "0.2" } |
|
| 50 | 51 | onig = { package = "onig-regset", version = "6.7.0", default-features = false } |
|
| 51 | - | serde = { package = "microserde", version = "0.2.0" } |
|
| 52 | + | serde = { package = "microserde", version = "0.3.0" } |
|
| 52 | 53 | termion = { version = "4" } |
|
| 53 | 54 | rustik-highlight = { path = "crates/highlight", version = "0.2.0" } |
|
| 54 | 55 | rustik-diff = { path = "crates/diff", version = "0.2.0" } |
|
| 55 | 56 | rustik-repo = { path = "crates/repo", version = "0.2.0" } |
|
| 56 | 57 | rustik-signals = { path = "crates/signals", version = "0.2.0" } |
crates/brain/Cargo.toml
added
+22 -0
| 1 | + | [package] |
|
| 2 | + | name = "rustik-brain" |
|
| 3 | + | description = "Commit-by-commit code review TUI for Rustik." |
|
| 4 | + | documentation = "https://docs.rs/rustik-brain" |
|
| 5 | + | homepage = "https://crates.io/crates/rustik-brain" |
|
| 6 | + | version.workspace = true |
|
| 7 | + | edition.workspace = true |
|
| 8 | + | license.workspace = true |
|
| 9 | + | ||
| 10 | + | [[bin]] |
|
| 11 | + | name = "brain" |
|
| 12 | + | path = "src/main.rs" |
|
| 13 | + | ||
| 14 | + | [dependencies] |
|
| 15 | + | serde.workspace = true |
|
| 16 | + | rustik-diff.workspace = true |
|
| 17 | + | rustik-repo.workspace = true |
|
| 18 | + | rustik-tui = { workspace = true, features = ["widgets"] } |
|
| 19 | + | rustik-tui-termion.workspace = true |
|
| 20 | + | ||
| 21 | + | [lints] |
|
| 22 | + | workspace = true |
crates/brain/src/backend.rs
added
+454 -0
| 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::collections::{BTreeMap, BTreeSet}; |
|
| 10 | + | use std::ffi::OsString; |
|
| 11 | + | use std::path::Path; |
|
| 12 | + | ||
| 13 | + | use rustik_diff::{Decode as _, DiffDocument, Encode as _, FileDiff, Hunk, HunkId}; |
|
| 14 | + | use rustik_repo::{ |
|
| 15 | + | DiffStat, Oid, PatchId, ReadRepository, Rev, WriteRepository, |
|
| 16 | + | git::{ |
|
| 17 | + | self, |
|
| 18 | + | refs::{Component, Qualified, RefString}, |
|
| 19 | + | }, |
|
| 20 | + | jj, |
|
| 21 | + | }; |
|
| 22 | + | ||
| 23 | + | use crate::error::Error; |
|
| 24 | + | ||
| 25 | + | /// Directory marking a Jujutsu workspace. |
|
| 26 | + | const JJ_DIR: &str = ".jj"; |
|
| 27 | + | /// Commit message used for synthetic brain state commits. |
|
| 28 | + | const SYNTHETIC_BRAIN_MESSAGE: &str = "brain state"; |
|
| 29 | + | /// Hidden Git ref category holding all review state. |
|
| 30 | + | const BRAIN_REF_CATEGORY: &str = "brain"; |
|
| 31 | + | /// Namespace under the brain category for acceptance state commits. |
|
| 32 | + | const STATE_REF_NAMESPACE: &str = "state"; |
|
| 33 | + | /// Namespace under the brain category for comment blobs. |
|
| 34 | + | const COMMENTS_REF_NAMESPACE: &str = "comments"; |
|
| 35 | + | ||
| 36 | + | /// One commit in the reviewed range, identified by its Git hash. |
|
| 37 | + | #[derive(Clone, Debug, Eq, PartialEq)] |
|
| 38 | + | pub struct Commit { |
|
| 39 | + | /// Full Git commit hash. |
|
| 40 | + | pub id: Oid, |
|
| 41 | + | /// First line of the commit message. |
|
| 42 | + | pub summary: String, |
|
| 43 | + | /// Aggregated diff size, shown in the commit list. |
|
| 44 | + | pub stats: DiffStat, |
|
| 45 | + | } |
|
| 46 | + | ||
| 47 | + | impl Commit { |
|
| 48 | + | /// Returns Git revision selectors for this commit's parent diff. |
|
| 49 | + | fn selectors(&self) -> [OsString; 2] { |
|
| 50 | + | [ |
|
| 51 | + | OsString::from(format!("{}^", self.id)), |
|
| 52 | + | OsString::from(self.id.to_string()), |
|
| 53 | + | ] |
|
| 54 | + | } |
|
| 55 | + | ||
| 56 | + | /// Joins `(id, summary)` pairs with their bulk-fetched diff stats. |
|
| 57 | + | fn with_stats( |
|
| 58 | + | repository: &impl ReadRepository, |
|
| 59 | + | pairs: Vec<(Oid, String)>, |
|
| 60 | + | ) -> Result<Vec<Self>, Error> { |
|
| 61 | + | let ids = pairs.iter().map(|(id, _)| *id).collect::<Vec<_>>(); |
|
| 62 | + | let stats = repository.commit_stats(&ids)?; |
|
| 63 | + | ||
| 64 | + | Ok(pairs |
|
| 65 | + | .into_iter() |
|
| 66 | + | .zip(stats) |
|
| 67 | + | .map(|((id, summary), stats)| Self { id, summary, stats }) |
|
| 68 | + | .collect()) |
|
| 69 | + | } |
|
| 70 | + | } |
|
| 71 | + | ||
| 72 | + | /// Hunk identity data for one commit during tree-state reconciliation. |
|
| 73 | + | pub struct CommitHunks<'a> { |
|
| 74 | + | /// Commit whose hunks are being reconciled. |
|
| 75 | + | pub commit: &'a Commit, |
|
| 76 | + | /// Stable patch id per decoded hunk, when the commit's diff is loaded. |
|
| 77 | + | pub hunks: Option<&'a BTreeMap<HunkId, PatchId>>, |
|
| 78 | + | } |
|
| 79 | + | ||
| 80 | + | /// Review state of one commit derived from the hidden tree. |
|
| 81 | + | pub struct Reconciled { |
|
| 82 | + | /// Whether the commit's entire diff is contained in the accepted tree. |
|
| 83 | + | pub reviewed: bool, |
|
| 84 | + | /// Accepted hunks, for commits whose hunk patch ids were supplied. |
|
| 85 | + | pub accepted: BTreeSet<HunkId>, |
|
| 86 | + | } |
|
| 87 | + | ||
| 88 | + | /// A revision backend that lists the reviewed commits and their diffs. |
|
| 89 | + | /// |
|
| 90 | + | /// The base and target revisions are resolved and stored when the backend is |
|
| 91 | + | /// constructed, so listing commits needs no further arguments. |
|
| 92 | + | pub trait Backend { |
|
| 93 | + | /// Returns the reviewed commits in `base..target`, oldest first. |
|
| 94 | + | fn commits(&self) -> Result<Vec<Commit>, Error>; |
|
| 95 | + | ||
| 96 | + | /// Returns `commit`'s diff against its parent as a parsed document. |
|
| 97 | + | fn commit_diff(&self, commit: &Commit) -> Result<DiffDocument, Error>; |
|
| 98 | + | ||
| 99 | + | /// Loads the hidden review state for this backend. |
|
| 100 | + | fn brain(&self) -> Result<Brain, Error>; |
|
| 101 | + | ||
| 102 | + | /// Returns a repo handle for widening `commit`'s hunk context. |
|
| 103 | + | fn repo(&self, commit: &Commit) -> git::Repository; |
|
| 104 | + | } |
|
| 105 | + | ||
| 106 | + | impl dyn Backend { |
|
| 107 | + | /// Returns a backend for `cwd` bound to the `base..target` range. |
|
| 108 | + | /// |
|
| 109 | + | /// A [`JJ_DIR`] directory in `cwd` or an ancestor selects the Jujutsu |
|
| 110 | + | /// backend; otherwise Git is used. |
|
| 111 | + | pub fn from_path(cwd: &Path, base: Rev, target: Rev) -> Result<Box<dyn Backend>, Error> { |
|
| 112 | + | if cwd.ancestors().any(|path| path.join(JJ_DIR).is_dir()) { |
|
| 113 | + | let backend = JjBackend::new(cwd, base, target)?; |
|
| 114 | + | Ok(Box::new(backend)) |
|
| 115 | + | } else { |
|
| 116 | + | let backend = GitBackend::new(cwd, base, target)?; |
|
| 117 | + | Ok(Box::new(backend)) |
|
| 118 | + | } |
|
| 119 | + | } |
|
| 120 | + | } |
|
| 121 | + | ||
| 122 | + | /// Hidden Git state holding one review's acceptance tree and comments. |
|
| 123 | + | /// |
|
| 124 | + | /// The acceptance tree is the persistent source of truth for accepted review |
|
| 125 | + | /// content; comments are stored as a JSONL blob under a sibling ref. Both live |
|
| 126 | + | /// entirely inside the Git object store, so review state travels with the |
|
| 127 | + | /// repository and never touches the working tree. |
|
| 128 | + | #[derive(Clone, Debug)] |
|
| 129 | + | pub struct Brain { |
|
| 130 | + | /// Git command context. |
|
| 131 | + | repository: git::Repository, |
|
| 132 | + | /// Hidden ref storing the synthetic acceptance state commit. |
|
| 133 | + | state_ref: Qualified<'static>, |
|
| 134 | + | /// Hidden ref storing the review's comments blob. |
|
| 135 | + | comments_ref: Qualified<'static>, |
|
| 136 | + | /// Base commit used as the parent of synthetic state commits. |
|
| 137 | + | base: Oid, |
|
| 138 | + | /// Current synthetic state commit. |
|
| 139 | + | commit: Oid, |
|
| 140 | + | } |
|
| 141 | + | ||
| 142 | + | impl Brain { |
|
| 143 | + | /// Returns the hidden Git ref for `review` under `namespace`. |
|
| 144 | + | fn ref_for(namespace: &'static str, review: &str) -> Result<Qualified<'static>, Error> { |
|
| 145 | + | let category = component(BRAIN_REF_CATEGORY)?; |
|
| 146 | + | let namespace = component(namespace)?; |
|
| 147 | + | let review = component(crate::comments::encode_component(review))?; |
|
| 148 | + | ||
| 149 | + | Ok(Qualified::from_components(category, namespace, [review])) |
|
| 150 | + | } |
|
| 151 | + | ||
| 152 | + | /// Loads or initializes the hidden review state for one review. |
|
| 153 | + | fn load(repository: git::Repository, base: Oid, review: &str) -> Result<Self, Error> { |
|
| 154 | + | let state_ref = Brain::ref_for(STATE_REF_NAMESPACE, review)?; |
|
| 155 | + | let comments_ref = Brain::ref_for(COMMENTS_REF_NAMESPACE, review)?; |
|
| 156 | + | let commit = match repository.optional_ref(&state_ref)? { |
|
| 157 | + | Some(existing) => { |
|
| 158 | + | let parent = repository.parent(existing)?; |
|
| 159 | + | if parent == base { |
|
| 160 | + | existing |
|
| 161 | + | } else { |
|
| 162 | + | return Err(Error::StaleReviewState { |
|
| 163 | + | stored_base: parent, |
|
| 164 | + | current_base: base, |
|
| 165 | + | }); |
|
| 166 | + | } |
|
| 167 | + | } |
|
| 168 | + | None => { |
|
| 169 | + | let tree = repository.tree_id(base)?; |
|
| 170 | + | let fresh = repository.commit( |
|
| 171 | + | tree, |
|
| 172 | + | base, |
|
| 173 | + | "brain", |
|
| 174 | + | "brain@example.invalid", |
|
| 175 | + | SYNTHETIC_BRAIN_MESSAGE, |
|
| 176 | + | )?; |
|
| 177 | + | repository.update_ref(&state_ref, fresh)?; |
|
| 178 | + | fresh |
|
| 179 | + | } |
|
| 180 | + | }; |
|
| 181 | + | Ok(Self { |
|
| 182 | + | repository, |
|
| 183 | + | state_ref, |
|
| 184 | + | comments_ref, |
|
| 185 | + | base, |
|
| 186 | + | commit, |
|
| 187 | + | }) |
|
| 188 | + | } |
|
| 189 | + | ||
| 190 | + | /// Computes the stable Git patch id for `patch` text. |
|
| 191 | + | pub fn patch_id(&self, patch: &str) -> Result<PatchId, Error> { |
|
| 192 | + | let patch_id = self.repository.patch_id(patch)?; |
|
| 193 | + | Ok(patch_id) |
|
| 194 | + | } |
|
| 195 | + | ||
| 196 | + | /// Computes the stable Git patch id for one hunk of `file`. |
|
| 197 | + | pub fn hunk_patch_id(&self, file: &FileDiff, hunk: &Hunk) -> Result<PatchId, Error> { |
|
| 198 | + | let document = DiffDocument::for_hunks(file, [hunk.clone()]); |
|
| 199 | + | let patch = document.to_unified_string()?; |
|
| 200 | + | self.patch_id(&patch) |
|
| 201 | + | } |
|
| 202 | + | ||
| 203 | + | /// Reads the review's persisted comments blob, if any. |
|
| 204 | + | pub fn read_comments(&self) -> Result<Option<String>, Error> { |
|
| 205 | + | let Some(blob) = self.repository.optional_ref(&self.comments_ref)? else { |
|
| 206 | + | return Ok(None); |
|
| 207 | + | }; |
|
| 208 | + | let bytes = self.repository.cat_blob(blob)?; |
|
| 209 | + | Ok(Some(String::from_utf8_lossy(&bytes).into_owned())) |
|
| 210 | + | } |
|
| 211 | + | ||
| 212 | + | /// Persists the review's comments blob. |
|
| 213 | + | pub fn write_comments(&self, text: &str) -> Result<(), Error> { |
|
| 214 | + | let blob = self.repository.write_blob(text.as_bytes())?; |
|
| 215 | + | self.repository.update_ref(&self.comments_ref, blob)?; |
|
| 216 | + | Ok(()) |
|
| 217 | + | } |
|
| 218 | + | ||
| 219 | + | /// Applies one selected hunk patch to the hidden tree and persists it. |
|
| 220 | + | /// |
|
| 221 | + | /// The hidden tree is the source of truth for accepted review content. Each |
|
| 222 | + | /// accepted hunk produces a new synthetic commit whose parent remains the |
|
| 223 | + | /// exact review base, so later loads can reject state from a different base |
|
| 224 | + | /// instead of trying to reinterpret it. |
|
| 225 | + | pub fn apply_patch(&mut self, patch: &str) -> Result<(), Error> { |
|
| 226 | + | let tree = self.repository.apply_patch_to_tree(self.commit, patch)?; |
|
| 227 | + | let commit = self.repository.commit( |
|
| 228 | + | tree, |
|
| 229 | + | self.base, |
|
| 230 | + | "brain", |
|
| 231 | + | "brain@example.invalid", |
|
| 232 | + | SYNTHETIC_BRAIN_MESSAGE, |
|
| 233 | + | )?; |
|
| 234 | + | self.repository.update_ref(&self.state_ref, commit)?; |
|
| 235 | + | self.commit = commit; |
|
| 236 | + | ||
| 237 | + | Ok(()) |
|
| 238 | + | } |
|
| 239 | + | ||
| 240 | + | /// Reconciles per-commit review state against the current hidden tree. |
|
| 241 | + | /// |
|
| 242 | + | /// The algorithm walks reviewed commits in order and asks what would remain |
|
| 243 | + | /// if each commit were merged into the current accepted-content cursor. The |
|
| 244 | + | /// residual diff is compared against the supplied per-hunk patch ids; a |
|
| 245 | + | /// hunk is accepted when its patch id no longer appears in the residual. |
|
| 246 | + | /// Commits without supplied patch ids (not yet decoded) still report their |
|
| 247 | + | /// `reviewed` state, which needs only the residual. |
|
| 248 | + | /// |
|
| 249 | + | /// The cursor only advances through commits that are fully accepted. This |
|
| 250 | + | /// keeps later commits from being classified relative to unaccepted changes |
|
| 251 | + | /// that still belong in the pending review. |
|
| 252 | + | pub fn reconcile(&self, commits: &[CommitHunks<'_>]) -> Result<Vec<Reconciled>, Error> { |
|
| 253 | + | let mut cursor = self.commit; |
|
| 254 | + | let mut reconciled = Vec::with_capacity(commits.len()); |
|
| 255 | + | ||
| 256 | + | for commit in commits { |
|
| 257 | + | let parent = self.repository.parent(commit.commit.id)?; |
|
| 258 | + | let candidate = match self.repository.merge_tree(parent, cursor, commit.commit.id) { |
|
| 259 | + | Ok(candidate) => candidate, |
|
| 260 | + | Err(rustik_repo::RepoError::MergeConflict(_)) => { |
|
| 261 | + | // A conflict means this commit cannot be cleanly replayed on |
|
| 262 | + | // the accepted cursor, so none of its hunks can be proven |
|
| 263 | + | // accepted from tree state. |
|
| 264 | + | reconciled.push(Reconciled { |
|
| 265 | + | reviewed: false, |
|
| 266 | + | accepted: BTreeSet::new(), |
|
| 267 | + | }); |
|
| 268 | + | continue; |
|
| 269 | + | } |
|
| 270 | + | Err(error) => return Err(error.into()), |
|
| 271 | + | }; |
|
| 272 | + | let residual = self.repository.diff(cursor, candidate)?; |
|
| 273 | + | let reviewed = residual.trim().is_empty(); |
|
| 274 | + | let accepted = match commit.hunks { |
|
| 275 | + | Some(hunks) if reviewed => hunks.keys().copied().collect(), |
|
| 276 | + | Some(hunks) => self.accepted_hunks(hunks, &residual)?, |
|
| 277 | + | None => BTreeSet::new(), |
|
| 278 | + | }; |
|
| 279 | + | reconciled.push(Reconciled { reviewed, accepted }); |
|
| 280 | + | ||
| 281 | + | if reviewed { |
|
| 282 | + | // Only fully accepted commits become part of the base used to |
|
| 283 | + | // classify later commits. |
|
| 284 | + | cursor = candidate; |
|
| 285 | + | } |
|
| 286 | + | } |
|
| 287 | + | Ok(reconciled) |
|
| 288 | + | } |
|
| 289 | + | ||
| 290 | + | /// Returns hunks whose patch id is absent from `residual`. |
|
| 291 | + | /// |
|
| 292 | + | /// Patch ids make the comparison insensitive to hunk line numbers and other |
|
| 293 | + | /// context drift in the residual diff. Only the residual's hunks are hashed |
|
| 294 | + | /// here; the original ids were computed once when the commit was loaded. |
|
| 295 | + | fn accepted_hunks( |
|
| 296 | + | &self, |
|
| 297 | + | original: &BTreeMap<HunkId, PatchId>, |
|
| 298 | + | residual: &str, |
|
| 299 | + | ) -> Result<BTreeSet<HunkId>, Error> { |
|
| 300 | + | let residual = DiffDocument::decode_str(residual)?; |
|
| 301 | + | let mut residual_ids = BTreeSet::new(); |
|
| 302 | + | ||
| 303 | + | for file in &residual.files { |
|
| 304 | + | for hunk in &file.hunks { |
|
| 305 | + | let patch_id = self.hunk_patch_id(file, hunk)?; |
|
| 306 | + | residual_ids.insert(patch_id); |
|
| 307 | + | } |
|
| 308 | + | } |
|
| 309 | + | Ok(accepted_hunks_from_patch_ids(original, &residual_ids)) |
|
| 310 | + | } |
|
| 311 | + | } |
|
| 312 | + | ||
| 313 | + | /// Returns original hunks whose patch ids are absent from the residual set. |
|
| 314 | + | fn accepted_hunks_from_patch_ids<P: Ord>( |
|
| 315 | + | original: &BTreeMap<HunkId, P>, |
|
| 316 | + | residual: &BTreeSet<P>, |
|
| 317 | + | ) -> BTreeSet<HunkId> { |
|
| 318 | + | original |
|
| 319 | + | .iter() |
|
| 320 | + | .filter_map(|(hunk, patch_id)| (!residual.contains(patch_id)).then_some(*hunk)) |
|
| 321 | + | .collect() |
|
| 322 | + | } |
|
| 323 | + | ||
| 324 | + | /// Converts `input` to a slash-free refname component. |
|
| 325 | + | fn component(input: impl Into<String>) -> Result<Component<'static>, Error> { |
|
| 326 | + | let refname = RefString::try_from(input.into()) |
|
| 327 | + | .map_err(|error| Error::Git(format!("invalid brain ref component: {error}")))?; |
|
| 328 | + | Component::from_refstr(refname) |
|
| 329 | + | .ok_or_else(|| Error::Git("invalid brain ref component: contains slash".to_owned())) |
|
| 330 | + | } |
|
| 331 | + | ||
| 332 | + | /// A [`Backend`] backed by the `git` command. |
|
| 333 | + | pub struct GitBackend { |
|
| 334 | + | /// Git repository operations. |
|
| 335 | + | repository: git::Repository, |
|
| 336 | + | /// Base revision, the exclusive lower bound of the range. |
|
| 337 | + | base: Rev, |
|
| 338 | + | /// Target revision, the inclusive upper bound of the range. |
|
| 339 | + | target: Rev, |
|
| 340 | + | } |
|
| 341 | + | ||
| 342 | + | impl GitBackend { |
|
| 343 | + | /// Creates a Git backend reviewing `base..target` in `cwd`. |
|
| 344 | + | fn new(cwd: &Path, base: Rev, target: Rev) -> Result<Self, Error> { |
|
| 345 | + | let repository = git::Repository::discover(cwd.to_path_buf())?; |
|
| 346 | + | Ok(Self { |
|
| 347 | + | repository, |
|
| 348 | + | base, |
|
| 349 | + | target, |
|
| 350 | + | }) |
|
| 351 | + | } |
|
| 352 | + | } |
|
| 353 | + | ||
| 354 | + | impl Backend for GitBackend { |
|
| 355 | + | fn commits(&self) -> Result<Vec<Commit>, Error> { |
|
| 356 | + | let pairs = self.repository.commits(&self.base, &self.target)?; |
|
| 357 | + | Commit::with_stats(&self.repository, pairs) |
|
| 358 | + | } |
|
| 359 | + | ||
| 360 | + | fn commit_diff(&self, commit: &Commit) -> Result<DiffDocument, Error> { |
|
| 361 | + | let bytes = self.repository.commit_diff(commit.id)?; |
|
| 362 | + | let document = DiffDocument::decode_bytes(&bytes)?; |
|
| 363 | + | Ok(document) |
|
| 364 | + | } |
|
| 365 | + | ||
| 366 | + | fn brain(&self) -> Result<Brain, Error> { |
|
| 367 | + | let base = self.repository.commit_id(&self.base)?; |
|
| 368 | + | Brain::load(self.repository.clone(), base, self.target.as_str()) |
|
| 369 | + | } |
|
| 370 | + | ||
| 371 | + | fn repo(&self, commit: &Commit) -> git::Repository { |
|
| 372 | + | self.repository.with_selector_args(commit.selectors()) |
|
| 373 | + | } |
|
| 374 | + | } |
|
| 375 | + | ||
| 376 | + | /// A [`Backend`] backed by the `jj` command. |
|
| 377 | + | pub struct JjBackend { |
|
| 378 | + | /// Jujutsu workspace handle. |
|
| 379 | + | jj: jj::Repository, |
|
| 380 | + | /// Embedded Git repository, used for stats and review state. |
|
| 381 | + | repository: git::Repository, |
|
| 382 | + | /// Base revision, the exclusive lower bound of the range. |
|
| 383 | + | base: Rev, |
|
| 384 | + | /// Target revision, the inclusive upper bound of the range. |
|
| 385 | + | target: Rev, |
|
| 386 | + | } |
|
| 387 | + | ||
| 388 | + | impl JjBackend { |
|
| 389 | + | /// Creates a Jujutsu backend reviewing `base..target` in `cwd`. |
|
| 390 | + | fn new(cwd: &Path, base: Rev, target: Rev) -> Result<Self, Error> { |
|
| 391 | + | let jj = jj::Repository::new(cwd); |
|
| 392 | + | let repository = jj.git_repository()?; |
|
| 393 | + | Ok(Self { |
|
| 394 | + | jj, |
|
| 395 | + | repository, |
|
| 396 | + | base, |
|
| 397 | + | target, |
|
| 398 | + | }) |
|
| 399 | + | } |
|
| 400 | + | } |
|
| 401 | + | ||
| 402 | + | impl Backend for JjBackend { |
|
| 403 | + | fn commits(&self) -> Result<Vec<Commit>, Error> { |
|
| 404 | + | let pairs = self.jj.commits(&self.base, &self.target)?; |
|
| 405 | + | Commit::with_stats(&self.repository, pairs) |
|
| 406 | + | } |
|
| 407 | + | ||
| 408 | + | fn commit_diff(&self, commit: &Commit) -> Result<DiffDocument, Error> { |
|
| 409 | + | let bytes = self.jj.commit_diff(commit.id)?; |
|
| 410 | + | let document = DiffDocument::decode_bytes(&bytes)?; |
|
| 411 | + | Ok(document) |
|
| 412 | + | } |
|
| 413 | + | ||
| 414 | + | fn brain(&self) -> Result<Brain, Error> { |
|
| 415 | + | let base = self.jj.resolve(&self.base)?; |
|
| 416 | + | Brain::load(self.repository.clone(), base, self.target.as_str()) |
|
| 417 | + | } |
|
| 418 | + | ||
| 419 | + | fn repo(&self, commit: &Commit) -> git::Repository { |
|
| 420 | + | self.repository.with_selector_args(commit.selectors()) |
|
| 421 | + | } |
|
| 422 | + | } |
|
| 423 | + | ||
| 424 | + | #[cfg(test)] |
|
| 425 | + | mod tests { |
|
| 426 | + | use super::*; |
|
| 427 | + | ||
| 428 | + | /// Returns a set of hunk ids from raw indexes. |
|
| 429 | + | fn hunk_set(ids: impl IntoIterator<Item = usize>) -> BTreeSet<HunkId> { |
|
| 430 | + | ids.into_iter().map(HunkId::new).collect() |
|
| 431 | + | } |
|
| 432 | + | ||
| 433 | + | #[test] |
|
| 434 | + | fn accepted_hunks_from_patch_ids_excludes_residual_patches() { |
|
| 435 | + | let original = BTreeMap::from([ |
|
| 436 | + | (HunkId::new(0), "alpha"), |
|
| 437 | + | (HunkId::new(1), "beta"), |
|
| 438 | + | (HunkId::new(2), "gamma"), |
|
| 439 | + | ]); |
|
| 440 | + | let residual = BTreeSet::from(["beta"]); |
|
| 441 | + | let accepted = accepted_hunks_from_patch_ids(&original, &residual); |
|
| 442 | + | ||
| 443 | + | assert_eq!(accepted, hunk_set([0, 2])); |
|
| 444 | + | } |
|
| 445 | + | ||
| 446 | + | #[test] |
|
| 447 | + | fn accepted_hunks_from_patch_ids_accepts_all_when_residual_is_empty() { |
|
| 448 | + | let original = BTreeMap::from([(HunkId::new(0), 10), (HunkId::new(1), 20)]); |
|
| 449 | + | let residual = BTreeSet::new(); |
|
| 450 | + | let accepted = accepted_hunks_from_patch_ids(&original, &residual); |
|
| 451 | + | ||
| 452 | + | assert_eq!(accepted, hunk_set([0, 1])); |
|
| 453 | + | } |
|
| 454 | + | } |
crates/brain/src/comments.rs
added
+310 -0
| 1 | + | //! Review comments attached to hunks. |
|
| 2 | + | //! |
|
| 3 | + | //! A review has one JSONL-encoded [`ReviewComments`] store, persisted as a |
|
| 4 | + | //! blob in the hidden review ref (see [`crate::backend::Brain`]). Each |
|
| 5 | + | //! reviewed commit owns a [`Comments`] view that maps the store's rows back |
|
| 6 | + | //! to the commit's hunk ids using the hunk's stable patch id, so comments |
|
| 7 | + | //! survive rebases that keep a hunk's content intact. |
|
| 8 | + | ||
| 9 | + | use std::collections::BTreeMap; |
|
| 10 | + | use std::fmt::Write as _; |
|
| 11 | + | use std::io; |
|
| 12 | + | use std::path::PathBuf; |
|
| 13 | + | use std::time::{SystemTime, UNIX_EPOCH}; |
|
| 14 | + | ||
| 15 | + | use rustik_diff::HunkId; |
|
| 16 | + | use rustik_repo::{Oid, PatchId}; |
|
| 17 | + | use serde::de::{Deserialize as DeserializeTrait, Scalar, Visitor}; |
|
| 18 | + | use serde::ser::{Fragment, Serialize as SerializeTrait}; |
|
| 19 | + | use serde::{Deserialize, Error, Result, Serialize, json}; |
|
| 20 | + | ||
| 21 | + | /// A single review comment authored on a hunk. |
|
| 22 | + | #[derive(Clone, Debug, Eq, PartialEq)] |
|
| 23 | + | pub struct Comment { |
|
| 24 | + | /// Stable local comment id. |
|
| 25 | + | pub id: CommentId, |
|
| 26 | + | /// Author shown for this comment. |
|
| 27 | + | pub author: String, |
|
| 28 | + | /// Comment body entered by the reviewer. |
|
| 29 | + | pub body: String, |
|
| 30 | + | } |
|
| 31 | + | ||
| 32 | + | /// Stable local identifier for one review comment. |
|
| 33 | + | #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] |
|
| 34 | + | pub struct CommentId( |
|
| 35 | + | /// Numeric component assigned within one persisted comment store. |
|
| 36 | + | u64, |
|
| 37 | + | ); |
|
| 38 | + | ||
| 39 | + | impl CommentId { |
|
| 40 | + | /// Returns the local numeric comment id. |
|
| 41 | + | pub fn as_u64(&self) -> u64 { |
|
| 42 | + | self.0 |
|
| 43 | + | } |
|
| 44 | + | } |
|
| 45 | + | ||
| 46 | + | impl From<u64> for CommentId { |
|
| 47 | + | fn from(value: u64) -> Self { |
|
| 48 | + | Self(value) |
|
| 49 | + | } |
|
| 50 | + | } |
|
| 51 | + | ||
| 52 | + | impl SerializeTrait for CommentId { |
|
| 53 | + | fn begin(&self) -> Fragment<'_> { |
|
| 54 | + | Fragment::U64(self.0) |
|
| 55 | + | } |
|
| 56 | + | } |
|
| 57 | + | ||
| 58 | + | /// Deserializes persisted comment ids. |
|
| 59 | + | pub struct CommentIdVisitor<'a> { |
|
| 60 | + | /// Output slot receiving the parsed comment id. |
|
| 61 | + | out: &'a mut Option<CommentId>, |
|
| 62 | + | } |
|
| 63 | + | ||
| 64 | + | impl Visitor for CommentIdVisitor<'_> { |
|
| 65 | + | fn scalar(&mut self, scalar: &Scalar) -> Result<()> { |
|
| 66 | + | let Scalar::Nonnegative(id) = scalar else { |
|
| 67 | + | return Err(Error); |
|
| 68 | + | }; |
|
| 69 | + | let id = *id; |
|
| 70 | + | *self.out = Some(CommentId(id)); |
|
| 71 | + | Ok(()) |
|
| 72 | + | } |
|
| 73 | + | } |
|
| 74 | + | ||
| 75 | + | impl DeserializeTrait for CommentId { |
|
| 76 | + | type Visitor<'a> = CommentIdVisitor<'a>; |
|
| 77 | + | ||
| 78 | + | fn begin(out: &mut Option<Self>) -> Self::Visitor<'_> { |
|
| 79 | + | CommentIdVisitor { out } |
|
| 80 | + | } |
|
| 81 | + | } |
|
| 82 | + | ||
| 83 | + | /// Target metadata for one commentable hunk. |
|
| 84 | + | #[derive(Clone, Debug, Eq, PartialEq)] |
|
| 85 | + | pub struct CommentTarget { |
|
| 86 | + | /// Heading identifying the reviewed item. |
|
| 87 | + | pub heading: String, |
|
| 88 | + | /// Optional file path associated with the hunk. |
|
| 89 | + | pub path: Option<PathBuf>, |
|
| 90 | + | /// Stable patch id of the hunk the comment is attached to. |
|
| 91 | + | pub patch_id: PatchId, |
|
| 92 | + | } |
|
| 93 | + | ||
| 94 | + | /// Persistent comment store for one review identity. |
|
| 95 | + | #[derive(Clone, Debug)] |
|
| 96 | + | pub struct ReviewComments { |
|
| 97 | + | /// Stored comment rows in JSONL order. |
|
| 98 | + | records: Vec<CommentRecord>, |
|
| 99 | + | /// Author name used for newly authored comments. |
|
| 100 | + | author: String, |
|
| 101 | + | } |
|
| 102 | + | ||
| 103 | + | /// One persisted comment row. |
|
| 104 | + | #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] |
|
| 105 | + | struct CommentRecord { |
|
| 106 | + | /// Stable local comment id. |
|
| 107 | + | id: CommentId, |
|
| 108 | + | /// Author shown for this comment. |
|
| 109 | + | author: String, |
|
| 110 | + | /// Unix timestamp when the comment was authored. |
|
| 111 | + | timestamp: u64, |
|
| 112 | + | /// Heading identifying the reviewed item. |
|
| 113 | + | heading: String, |
|
| 114 | + | /// Optional file path associated with the hunk. |
|
| 115 | + | path: Option<PathBuf>, |
|
| 116 | + | /// Stable patch id of the hunk the comment is attached to. |
|
| 117 | + | patch_id: PatchId, |
|
| 118 | + | /// Comment body. |
|
| 119 | + | body: String, |
|
| 120 | + | /// Agent update waiting for reviewer re-review. |
|
| 121 | + | pending_updates: Option<PendingUpdates>, |
|
| 122 | + | } |
|
| 123 | + | ||
| 124 | + | /// Agent-authored update linked to a review comment. |
|
| 125 | + | #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] |
|
| 126 | + | struct PendingUpdates { |
|
| 127 | + | /// Agent identity that made the update. |
|
| 128 | + | by: String, |
|
| 129 | + | /// Commit containing the pending update. |
|
| 130 | + | commit: Oid, |
|
| 131 | + | } |
|
| 132 | + | ||
| 133 | + | /// Per-commit comment view keyed by the commit's hunk ids. |
|
| 134 | + | #[derive(Clone, Debug)] |
|
| 135 | + | pub struct Comments { |
|
| 136 | + | /// Comments keyed by the hunk they were authored on. |
|
| 137 | + | by_hunk: BTreeMap<HunkId, Vec<Comment>>, |
|
| 138 | + | /// Hunk metadata used to persist newly authored comments. |
|
| 139 | + | targets: BTreeMap<HunkId, CommentTarget>, |
|
| 140 | + | } |
|
| 141 | + | ||
| 142 | + | impl ReviewComments { |
|
| 143 | + | /// Parses persisted JSONL text; empty text yields an empty store. |
|
| 144 | + | pub fn parse(text: &str) -> io::Result<Self> { |
|
| 145 | + | let mut records = Vec::new(); |
|
| 146 | + | for line in text.lines().filter(|line| !line.trim().is_empty()) { |
|
| 147 | + | let record = json::from_str(line) |
|
| 148 | + | .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "malformed comment"))?; |
|
| 149 | + | records.push(record); |
|
| 150 | + | } |
|
| 151 | + | Ok(Self { |
|
| 152 | + | records, |
|
| 153 | + | author: default_author(), |
|
| 154 | + | }) |
|
| 155 | + | } |
|
| 156 | + | ||
| 157 | + | /// Encodes all comment rows as JSONL text for persistence. |
|
| 158 | + | pub fn encode(&self) -> String { |
|
| 159 | + | let mut rows = String::new(); |
|
| 160 | + | for record in &self.records { |
|
| 161 | + | rows.push_str(&json::to_string(record)); |
|
| 162 | + | rows.push('\n'); |
|
| 163 | + | } |
|
| 164 | + | rows |
|
| 165 | + | } |
|
| 166 | + | ||
| 167 | + | /// Returns comments attached to `target`'s patch id, in storage order. |
|
| 168 | + | fn matching(&self, target: &CommentTarget) -> Vec<Comment> { |
|
| 169 | + | self.records |
|
| 170 | + | .iter() |
|
| 171 | + | .filter(|record| record.patch_id == target.patch_id) |
|
| 172 | + | .map(Comment::from) |
|
| 173 | + | .collect() |
|
| 174 | + | } |
|
| 175 | + | ||
| 176 | + | /// Adds one comment row for `target` and returns its view. |
|
| 177 | + | fn add(&mut self, target: &CommentTarget, body: String) -> Comment { |
|
| 178 | + | let timestamp = SystemTime::now() |
|
| 179 | + | .duration_since(UNIX_EPOCH) |
|
| 180 | + | .unwrap_or_default() |
|
| 181 | + | .as_secs(); |
|
| 182 | + | let record = CommentRecord { |
|
| 183 | + | id: self.next_id(), |
|
| 184 | + | author: self.author.clone(), |
|
| 185 | + | timestamp, |
|
| 186 | + | heading: target.heading.clone(), |
|
| 187 | + | path: target.path.clone(), |
|
| 188 | + | patch_id: target.patch_id.clone(), |
|
| 189 | + | body, |
|
| 190 | + | pending_updates: None, |
|
| 191 | + | }; |
|
| 192 | + | let comment = Comment::from(&record); |
|
| 193 | + | self.records.push(record); |
|
| 194 | + | ||
| 195 | + | comment |
|
| 196 | + | } |
|
| 197 | + | ||
| 198 | + | /// Returns the next stable local comment id. |
|
| 199 | + | fn next_id(&self) -> CommentId { |
|
| 200 | + | let next = self |
|
| 201 | + | .records |
|
| 202 | + | .iter() |
|
| 203 | + | .map(|record| record.id.as_u64()) |
|
| 204 | + | .max() |
|
| 205 | + | .unwrap_or_default() |
|
| 206 | + | .saturating_add(1); |
|
| 207 | + | CommentId::from(next) |
|
| 208 | + | } |
|
| 209 | + | } |
|
| 210 | + | ||
| 211 | + | impl From<&CommentRecord> for Comment { |
|
| 212 | + | fn from(record: &CommentRecord) -> Self { |
|
| 213 | + | Self { |
|
| 214 | + | id: record.id.clone(), |
|
| 215 | + | author: record.author.clone(), |
|
| 216 | + | body: record.body.clone(), |
|
| 217 | + | } |
|
| 218 | + | } |
|
| 219 | + | } |
|
| 220 | + | ||
| 221 | + | impl Comments { |
|
| 222 | + | /// Creates a comment view for a commit's hunk targets. |
|
| 223 | + | pub fn new(store: &ReviewComments, targets: BTreeMap<HunkId, CommentTarget>) -> Self { |
|
| 224 | + | let by_hunk = targets |
|
| 225 | + | .iter() |
|
| 226 | + | .filter_map(|(hunk, target)| { |
|
| 227 | + | let comments = store.matching(target); |
|
| 228 | + | (!comments.is_empty()).then_some((*hunk, comments)) |
|
| 229 | + | }) |
|
| 230 | + | .collect(); |
|
| 231 | + | ||
| 232 | + | Self { by_hunk, targets } |
|
| 233 | + | } |
|
| 234 | + | ||
| 235 | + | /// Authors a comment on `hunk` into `store`, returning whether one was |
|
| 236 | + | /// added. The caller is responsible for persisting the updated store. |
|
| 237 | + | pub fn author(&mut self, store: &mut ReviewComments, hunk: HunkId, body: String) -> bool { |
|
| 238 | + | let Some(target) = self.targets.get(&hunk) else { |
|
| 239 | + | return false; |
|
| 240 | + | }; |
|
| 241 | + | let comment = store.add(target, body); |
|
| 242 | + | self.by_hunk.entry(hunk).or_default().push(comment); |
|
| 243 | + | true |
|
| 244 | + | } |
|
| 245 | + | ||
| 246 | + | /// Returns the comments authored on `hunk`. |
|
| 247 | + | pub fn for_hunk(&self, hunk: HunkId) -> &[Comment] { |
|
| 248 | + | self.by_hunk.get(&hunk).map_or(&[], Vec::as_slice) |
|
| 249 | + | } |
|
| 250 | + | ||
| 251 | + | /// Returns per-hunk comment counts, for decoration snapshots. |
|
| 252 | + | pub fn counts(&self) -> BTreeMap<HunkId, usize> { |
|
| 253 | + | self.by_hunk |
|
| 254 | + | .iter() |
|
| 255 | + | .map(|(hunk, comments)| (*hunk, comments.len())) |
|
| 256 | + | .collect() |
|
| 257 | + | } |
|
| 258 | + | } |
|
| 259 | + | ||
| 260 | + | /// Encodes arbitrary review identity text as one path or refname component. |
|
| 261 | + | pub(crate) fn encode_component(input: &str) -> String { |
|
| 262 | + | let mut encoded = String::new(); |
|
| 263 | + | for byte in input.bytes() { |
|
| 264 | + | match byte { |
|
| 265 | + | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'_' | b'-' => { |
|
| 266 | + | encoded.push(byte as char); |
|
| 267 | + | } |
|
| 268 | + | _ => { |
|
| 269 | + | write!(encoded, "%{byte:02x}").ok(); |
|
| 270 | + | } |
|
| 271 | + | } |
|
| 272 | + | } |
|
| 273 | + | encoded |
|
| 274 | + | } |
|
| 275 | + | ||
| 276 | + | /// Returns the author name used for newly authored comments. |
|
| 277 | + | fn default_author() -> String { |
|
| 278 | + | std::env::var("GIT_AUTHOR_NAME") |
|
| 279 | + | .ok() |
|
| 280 | + | .filter(|name| !name.trim().is_empty()) |
|
| 281 | + | .or_else(|| { |
|
| 282 | + | std::env::var("USER") |
|
| 283 | + | .ok() |
|
| 284 | + | .filter(|name| !name.trim().is_empty()) |
|
| 285 | + | }) |
|
| 286 | + | .unwrap_or_else(|| "You".to_owned()) |
|
| 287 | + | } |
|
| 288 | + | ||
| 289 | + | #[cfg(test)] |
|
| 290 | + | mod tests { |
|
| 291 | + | use super::*; |
|
| 292 | + | ||
| 293 | + | #[test] |
|
| 294 | + | fn comment_id_serializes_as_number() { |
|
| 295 | + | let id = CommentId::from(7); |
|
| 296 | + | ||
| 297 | + | assert_eq!(json::to_string(&id), "7"); |
|
| 298 | + | assert_eq!(json::from_str::<CommentId>("7").unwrap(), id); |
|
| 299 | + | } |
|
| 300 | + | ||
| 301 | + | #[test] |
|
| 302 | + | fn next_id_continues_above_stored_ids() { |
|
| 303 | + | let store = ReviewComments::parse( |
|
| 304 | + | r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","body":"old","pending_updates":null}"#, |
|
| 305 | + | ) |
|
| 306 | + | .unwrap(); |
|
| 307 | + | ||
| 308 | + | assert_eq!(store.next_id(), CommentId::from(8)); |
|
| 309 | + | } |
|
| 310 | + | } |
crates/brain/src/decorate.rs
added
+93 -0
| 1 | + | //! Diff decorations derived from review and comment state. |
|
| 2 | + | //! |
|
| 3 | + | //! The diff viewer is review-agnostic; this decorator feeds it per-hunk |
|
| 4 | + | //! markers. A [`Decorations`] value is an immutable snapshot of the review |
|
| 5 | + | //! state, rebuilt and reinstalled by the session whenever acceptance or |
|
| 6 | + | //! comments change, so the viewer never observes state mutating underneath |
|
| 7 | + | //! it. Accepted hunks are dimmed and marked with a check mark; commented |
|
| 8 | + | //! hunks show a comment marker and count. |
|
| 9 | + | ||
| 10 | + | use std::collections::{BTreeMap, BTreeSet}; |
|
| 11 | + | ||
| 12 | + | use rustik_diff::{DiffDecorator, FileDecoration, FileId, HunkDecoration, HunkId}; |
|
| 13 | + | use rustik_tui as tui; |
|
| 14 | + | use tui::{Color, Label, Line, Paint, Style}; |
|
| 15 | + | ||
| 16 | + | use crate::comments::Comments; |
|
| 17 | + | use crate::review::Review; |
|
| 18 | + | ||
| 19 | + | /// Check mark drawn beside accepted hunks and fully accepted files. |
|
| 20 | + | const ACCEPTED_MARK: char = '\u{2713}'; |
|
| 21 | + | /// Marker drawn in the corner of a hunk that has comments. |
|
| 22 | + | const COMMENT_MARK: char = '\u{1F5E8}'; |
|
| 23 | + | ||
| 24 | + | /// Immutable decoration snapshot of one commit's review state. |
|
| 25 | + | #[derive(Clone, Debug)] |
|
| 26 | + | pub struct Decorations { |
|
| 27 | + | /// Hunks accepted at snapshot time. |
|
| 28 | + | accepted: BTreeSet<HunkId>, |
|
| 29 | + | /// Per-hunk comment counts at snapshot time. |
|
| 30 | + | comments: BTreeMap<HunkId, usize>, |
|
| 31 | + | /// Original hunk ids for each file in the commit. |
|
| 32 | + | file_hunks: BTreeMap<FileId, Vec<HunkId>>, |
|
| 33 | + | } |
|
| 34 | + | ||
| 35 | + | impl Decorations { |
|
| 36 | + | /// Captures the current review and comment state for `file_hunks`. |
|
| 37 | + | pub fn snapshot( |
|
| 38 | + | review: &Review, |
|
| 39 | + | comments: &Comments, |
|
| 40 | + | file_hunks: &BTreeMap<FileId, Vec<HunkId>>, |
|
| 41 | + | ) -> Self { |
|
| 42 | + | Self { |
|
| 43 | + | accepted: review.accepted().clone(), |
|
| 44 | + | comments: comments.counts(), |
|
| 45 | + | file_hunks: file_hunks.clone(), |
|
| 46 | + | } |
|
| 47 | + | } |
|
| 48 | + | } |
|
| 49 | + | ||
| 50 | + | impl DiffDecorator for Decorations { |
|
| 51 | + | fn file(&self, file: FileId) -> FileDecoration { |
|
| 52 | + | let accepted = self.file_hunks.get(&file).is_some_and(|hunks| { |
|
| 53 | + | !hunks.is_empty() && hunks.iter().all(|hunk| self.accepted.contains(hunk)) |
|
| 54 | + | }); |
|
| 55 | + | if accepted { |
|
| 56 | + | FileDecoration { |
|
| 57 | + | status: Some(Paint::new(ACCEPTED_MARK).fg(Color::Green)), |
|
| 58 | + | ..FileDecoration::default() |
|
| 59 | + | } |
|
| 60 | + | } else { |
|
| 61 | + | FileDecoration::default() |
|
| 62 | + | } |
|
| 63 | + | } |
|
| 64 | + | ||
| 65 | + | fn hunk(&self, _file: FileId, hunk: HunkId) -> HunkDecoration { |
|
| 66 | + | let accepted = self.accepted.contains(&hunk); |
|
| 67 | + | let comments = self.comments.get(&hunk).copied().unwrap_or_default(); |
|
| 68 | + | if !accepted && comments == 0 { |
|
| 69 | + | return HunkDecoration::default(); |
|
| 70 | + | } |
|
| 71 | + | ||
| 72 | + | let mut corner = Line::blank(); |
|
| 73 | + | if comments > 0 { |
|
| 74 | + | let marker = if comments > 1 { |
|
| 75 | + | format!("{COMMENT_MARK} {comments}") |
|
| 76 | + | } else { |
|
| 77 | + | COMMENT_MARK.to_string() |
|
| 78 | + | }; |
|
| 79 | + | corner = corner.item(Label::new(&marker).fg(Color::Yellow)); |
|
| 80 | + | } |
|
| 81 | + | if accepted { |
|
| 82 | + | if comments > 0 { |
|
| 83 | + | corner = corner.item(Label::space()); |
|
| 84 | + | } |
|
| 85 | + | corner = corner.item(Label::from_char(ACCEPTED_MARK).fg(Color::Green)); |
|
| 86 | + | } |
|
| 87 | + | ||
| 88 | + | HunkDecoration { |
|
| 89 | + | corner, |
|
| 90 | + | style: accepted.then(|| Style::default().dim()), |
|
| 91 | + | } |
|
| 92 | + | } |
|
| 93 | + | } |
crates/brain/src/error.rs
added
+81 -0
| 1 | + | //! Error handling for the `brain` binary. |
|
| 2 | + | ||
| 3 | + | use std::io; |
|
| 4 | + | ||
| 5 | + | use rustik_diff::DecodeError; |
|
| 6 | + | use rustik_repo::{Oid, RepoError}; |
|
| 7 | + | ||
| 8 | + | /// Top-level error type for the binary. |
|
| 9 | + | #[derive(Debug)] |
|
| 10 | + | pub enum Error { |
|
| 11 | + | /// I/O failed. |
|
| 12 | + | Io(io::Error), |
|
| 13 | + | /// A backend command exited with a failing status code. |
|
| 14 | + | Backend(i32), |
|
| 15 | + | /// A Git plumbing command failed, carrying its diagnostic. |
|
| 16 | + | Git(String), |
|
| 17 | + | /// A hidden-tree merge encountered a content conflict. |
|
| 18 | + | MergeConflict(String), |
|
| 19 | + | /// The persisted review state belongs to another base commit. |
|
| 20 | + | StaleReviewState { |
|
| 21 | + | /// Base commit recorded by the persisted state commit. |
|
| 22 | + | stored_base: Oid, |
|
| 23 | + | /// Base commit requested by the current review. |
|
| 24 | + | current_base: Oid, |
|
| 25 | + | }, |
|
| 26 | + | /// Diff parsing failed. |
|
| 27 | + | Parse(DecodeError), |
|
| 28 | + | /// Highlighting asset setup failed, carrying the backend message. |
|
| 29 | + | Highlight(String), |
|
| 30 | + | /// The command-line arguments were invalid, carrying a usage message. |
|
| 31 | + | Usage(String), |
|
| 32 | + | /// The review range contained no changes to review. |
|
| 33 | + | Empty, |
|
| 34 | + | } |
|
| 35 | + | ||
| 36 | + | impl From<io::Error> for Error { |
|
| 37 | + | fn from(error: io::Error) -> Self { |
|
| 38 | + | Self::Io(error) |
|
| 39 | + | } |
|
| 40 | + | } |
|
| 41 | + | ||
| 42 | + | impl From<DecodeError> for Error { |
|
| 43 | + | fn from(error: DecodeError) -> Self { |
|
| 44 | + | Self::Parse(error) |
|
| 45 | + | } |
|
| 46 | + | } |
|
| 47 | + | ||
| 48 | + | impl From<RepoError> for Error { |
|
| 49 | + | fn from(error: RepoError) -> Self { |
|
| 50 | + | match error { |
|
| 51 | + | RepoError::Io(e) => Self::Io(e), |
|
| 52 | + | RepoError::Status(code) => Self::Backend(code), |
|
| 53 | + | RepoError::Git(msg) => Self::Git(msg), |
|
| 54 | + | RepoError::MergeConflict(msg) => Self::MergeConflict(msg), |
|
| 55 | + | } |
|
| 56 | + | } |
|
| 57 | + | } |
|
| 58 | + | ||
| 59 | + | impl std::fmt::Display for Error { |
|
| 60 | + | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
|
| 61 | + | match self { |
|
| 62 | + | Self::Io(error) => write!(f, "{error}"), |
|
| 63 | + | Self::Backend(code) => write!(f, "backend command exited with status {code}"), |
|
| 64 | + | Self::Git(message) => write!(f, "{message}"), |
|
| 65 | + | Self::MergeConflict(message) => write!(f, "merge conflict: {message}"), |
|
| 66 | + | Self::StaleReviewState { |
|
| 67 | + | stored_base, |
|
| 68 | + | current_base, |
|
| 69 | + | } => write!( |
|
| 70 | + | f, |
|
| 71 | + | "stored review state is for base {stored_base}, but current base is {current_base}" |
|
| 72 | + | ), |
|
| 73 | + | Self::Parse(error) => write!(f, "{error}"), |
|
| 74 | + | Self::Highlight(error) => write!(f, "{error}"), |
|
| 75 | + | Self::Usage(message) => write!(f, "{message}"), |
|
| 76 | + | Self::Empty => write!(f, "no changes to review between base and target"), |
|
| 77 | + | } |
|
| 78 | + | } |
|
| 79 | + | } |
|
| 80 | + | ||
| 81 | + | impl std::error::Error for Error {} |
crates/brain/src/main.rs
added
+99 -0
| 1 | + | //! Binary entry point for the `brain` code-review TUI. |
|
| 2 | + | //! |
|
| 3 | + | //! `brain <base> <target>` opens an interactive review of the changes between |
|
| 4 | + | //! two revisions. The reviewer accepts hunks one by one; accepted hunks are |
|
| 5 | + | //! hidden by default and can be revealed for inspection. |
|
| 6 | + | ||
| 7 | + | // `serde` is the local alias for the `microserde` crate; the derive macro |
|
| 8 | + | // emits `microserde::*` paths so the original crate name must remain in scope. |
|
| 9 | + | extern crate serde as microserde; |
|
| 10 | + | ||
| 11 | + | mod backend; |
|
| 12 | + | mod comments; |
|
| 13 | + | mod decorate; |
|
| 14 | + | mod error; |
|
| 15 | + | mod review; |
|
| 16 | + | mod session; |
|
| 17 | + | ||
| 18 | + | use std::env; |
|
| 19 | + | use std::ffi::{OsStr, OsString}; |
|
| 20 | + | use std::io::{self, Write as _}; |
|
| 21 | + | use std::process::ExitCode; |
|
| 22 | + | ||
| 23 | + | use rustik_diff::{Builtins, DiffOptions, FileTreeMode}; |
|
| 24 | + | use rustik_repo::Rev; |
|
| 25 | + | use rustik_tui::Terminal; |
|
| 26 | + | use rustik_tui_termion as tui_termion; |
|
| 27 | + | ||
| 28 | + | use crate::comments::ReviewComments; |
|
| 29 | + | use crate::error::Error; |
|
| 30 | + | ||
| 31 | + | /// Program entry point. |
|
| 32 | + | fn main() -> ExitCode { |
|
| 33 | + | match run(env::args_os().skip(1).collect()) { |
|
| 34 | + | Ok(()) => ExitCode::SUCCESS, |
|
| 35 | + | Err(error) => { |
|
| 36 | + | let _ = writeln!(io::stderr(), "brain: {error}"); |
|
| 37 | + | ExitCode::FAILURE |
|
| 38 | + | } |
|
| 39 | + | } |
|
| 40 | + | } |
|
| 41 | + | ||
| 42 | + | /// Parses arguments, loads the review range, and runs the session. |
|
| 43 | + | fn run(args: Vec<OsString>) -> Result<(), Error> { |
|
| 44 | + | let (base, target) = match args.as_slice() { |
|
| 45 | + | [base, target] => (base, target), |
|
| 46 | + | _ => return Err(Error::Usage("usage: brain <base> <target>".to_owned())), |
|
| 47 | + | }; |
|
| 48 | + | let base = base |
|
| 49 | + | .to_str() |
|
| 50 | + | .ok_or_else(|| Error::Usage("base revision must be valid UTF-8".to_owned()))?; |
|
| 51 | + | let target = target |
|
| 52 | + | .to_str() |
|
| 53 | + | .ok_or_else(|| Error::Usage("target revision must be valid UTF-8".to_owned()))?; |
|
| 54 | + | let base = Rev::try_from(base) |
|
| 55 | + | .map_err(|error| Error::Usage(format!("base revision is invalid: {error}")))?; |
|
| 56 | + | let target = Rev::try_from(target) |
|
| 57 | + | .map_err(|error| Error::Usage(format!("target revision is invalid: {error}")))?; |
|
| 58 | + | ||
| 59 | + | let cwd = env::current_dir()?; |
|
| 60 | + | let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?; |
|
| 61 | + | let brain = backend.brain()?; |
|
| 62 | + | let persisted = brain.read_comments()?; |
|
| 63 | + | let comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?; |
|
| 64 | + | ||
| 65 | + | let assets = Builtins::load().map_err(|error| Error::Highlight(error.to_string()))?; |
|
| 66 | + | let root = cwd |
|
| 67 | + | .file_name() |
|
| 68 | + | .and_then(OsStr::to_str) |
|
| 69 | + | .filter(|name| !name.is_empty()) |
|
| 70 | + | .map(str::to_owned) |
|
| 71 | + | .unwrap_or_else(|| cwd.display().to_string()); |
|
| 72 | + | let options = DiffOptions { |
|
| 73 | + | diff_palette: assets.palette, |
|
| 74 | + | file_tree: FileTreeMode::Auto, |
|
| 75 | + | file_tree_root: root, |
|
| 76 | + | ..DiffOptions::default() |
|
| 77 | + | }; |
|
| 78 | + | ||
| 79 | + | // Commit diffs are decoded lazily when first displayed; only the commit |
|
| 80 | + | // list and its stats are fetched up front. Commits that introduce no |
|
| 81 | + | // changes are skipped. |
|
| 82 | + | let mut commits = backend.commits()?; |
|
| 83 | + | commits.retain(|commit| commit.stats.files_changed > 0); |
|
| 84 | + | if commits.is_empty() { |
|
| 85 | + | return Err(Error::Empty); |
|
| 86 | + | } |
|
| 87 | + | ||
| 88 | + | let screen = tui_termion::term::screen()?; |
|
| 89 | + | let mut terminal = Terminal::new(screen)?; |
|
| 90 | + | ||
| 91 | + | terminal.clear()?; |
|
| 92 | + | terminal.set_cursor_visible(false)?; |
|
| 93 | + | ||
| 94 | + | let result = session::run(&mut terminal, commits, backend, brain, comments, options); |
|
| 95 | + | let cursor = terminal.set_cursor_visible(true); |
|
| 96 | + | ||
| 97 | + | result?; |
|
| 98 | + | cursor.map_err(Error::Io) |
|
| 99 | + | } |
crates/brain/src/review.rs
added
+61 -0
| 1 | + | //! Per-hunk review state. |
|
| 2 | + | //! |
|
| 3 | + | //! Tracks which hunks of one commit the reviewer has accepted. Each reviewed |
|
| 4 | + | //! commit owns its own [`Review`], since the decoded hunk ids restart per |
|
| 5 | + | //! commit. The state is plainly owned by the session; the commit's viewer |
|
| 6 | + | //! decorator receives immutable snapshots of it (see [`crate::decorate`]) |
|
| 7 | + | //! whenever it changes. |
|
| 8 | + | ||
| 9 | + | use std::collections::BTreeSet; |
|
| 10 | + | ||
| 11 | + | use rustik_diff::HunkId; |
|
| 12 | + | ||
| 13 | + | /// Session-wide view preferences controlling what the diff shows. |
|
| 14 | + | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
|
| 15 | + | pub struct Visibility { |
|
| 16 | + | /// Show accepted hunks instead of hiding them. |
|
| 17 | + | pub show_accepted: bool, |
|
| 18 | + | /// Show the full file instead of just hunks with surrounding context. |
|
| 19 | + | pub full_file: bool, |
|
| 20 | + | } |
|
| 21 | + | ||
| 22 | + | /// Per-hunk acceptance state for one commit. |
|
| 23 | + | #[derive(Clone, Debug, Default)] |
|
| 24 | + | pub struct Review { |
|
| 25 | + | /// Hunks the reviewer has accepted. |
|
| 26 | + | accepted: BTreeSet<HunkId>, |
|
| 27 | + | } |
|
| 28 | + | ||
| 29 | + | impl Review { |
|
| 30 | + | /// Creates empty review state with no accepted hunks. |
|
| 31 | + | pub fn new() -> Self { |
|
| 32 | + | Self::default() |
|
| 33 | + | } |
|
| 34 | + | ||
| 35 | + | /// Returns whether `hunk` is accepted. |
|
| 36 | + | pub fn is_accepted(&self, hunk: HunkId) -> bool { |
|
| 37 | + | self.accepted.contains(&hunk) |
|
| 38 | + | } |
|
| 39 | + | ||
| 40 | + | /// Returns the set of accepted hunks. |
|
| 41 | + | pub fn accepted(&self) -> &BTreeSet<HunkId> { |
|
| 42 | + | &self.accepted |
|
| 43 | + | } |
|
| 44 | + | ||
| 45 | + | /// Replaces the accepted hunk set. |
|
| 46 | + | pub fn replace(&mut self, accepted: BTreeSet<HunkId>) { |
|
| 47 | + | self.accepted = accepted; |
|
| 48 | + | } |
|
| 49 | + | ||
| 50 | + | /// Returns the number of accepted hunks. |
|
| 51 | + | pub fn count(&self) -> usize { |
|
| 52 | + | self.accepted.len() |
|
| 53 | + | } |
|
| 54 | + | ||
| 55 | + | /// Returns whether every hunk in `hunks` has been accepted. |
|
| 56 | + | pub fn accepts_all(&self, hunks: impl IntoIterator<Item = HunkId>) -> bool { |
|
| 57 | + | let mut hunks = hunks.into_iter().peekable(); |
|
| 58 | + | ||
| 59 | + | hunks.peek().is_some() && hunks.all(|hunk| self.accepted.contains(&hunk)) |
|
| 60 | + | } |
|
| 61 | + | } |
crates/brain/src/session.rs
added
+666 -0
| 1 | + | //! Terminal session loop for the `brain` review TUI. |
|
| 2 | + | ||
| 3 | + | use std::io; |
|
| 4 | + | use std::mem; |
|
| 5 | + | use std::sync::mpsc::{self, Sender}; |
|
| 6 | + | ||
| 7 | + | use rustik_diff::{ |
|
| 8 | + | ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffViewer, FileDiff, |
|
| 9 | + | FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ViewChange, spawn_highlighter, |
|
| 10 | + | }; |
|
| 11 | + | use rustik_tui::{ |
|
| 12 | + | Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, Terminal, TextInput, |
|
| 13 | + | }; |
|
| 14 | + | use rustik_tui_termion as tui_termion; |
|
| 15 | + | ||
| 16 | + | use crate::backend::{Backend, Brain, Commit, CommitHunks}; |
|
| 17 | + | use crate::comments::ReviewComments; |
|
| 18 | + | use crate::error::Error; |
|
| 19 | + | use crate::review::Visibility; |
|
| 20 | + | ||
| 21 | + | mod commit; |
|
| 22 | + | mod event; |
|
| 23 | + | mod hunk; |
|
| 24 | + | mod status; |
|
| 25 | + | ||
| 26 | + | use commit::{CommitReview, CommitSlot}; |
|
| 27 | + | use event::{ContextFetch, Resize, TerminalEvent, Update, context_change}; |
|
| 28 | + | use hunk::HunkView; |
|
| 29 | + | use status::{Status, comment_block_lines, commit_row, viewer_area}; |
|
| 30 | + | ||
| 31 | + | /// Terminal backend used by the interactive viewer. |
|
| 32 | + | type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>; |
|
| 33 | + | ||
| 34 | + | /// Active view in the session. |
|
| 35 | + | enum Mode { |
|
| 36 | + | /// The commit list. |
|
| 37 | + | Commits, |
|
| 38 | + | /// The diff of the current commit. |
|
| 39 | + | Diff, |
|
| 40 | + | /// A single hunk with an inline comment box. |
|
| 41 | + | /// |
|
| 42 | + | /// Boxed because the hunk view owns its own diff viewer, which would |
|
| 43 | + | /// otherwise dominate the size of every mode value. |
|
| 44 | + | Hunk(Box<HunkView>), |
|
| 45 | + | } |
|
| 46 | + | ||
| 47 | + | /// Runs the terminal event loop until the reviewer quits. |
|
| 48 | + | pub fn run( |
|
| 49 | + | terminal: &mut BrainTerminal, |
|
| 50 | + | commits: Vec<Commit>, |
|
| 51 | + | backend: Box<dyn Backend>, |
|
| 52 | + | brain: Brain, |
|
| 53 | + | comments: ReviewComments, |
|
| 54 | + | options: DiffOptions, |
|
| 55 | + | ) -> Result<(), Error> { |
|
| 56 | + | let (events_tx, events_rx) = mpsc::channel(); |
|
| 57 | + | TerminalEvent::spawn_input_worker(events_tx.clone()); |
|
| 58 | + | ||
| 59 | + | let mut session = Session { |
|
| 60 | + | terminal, |
|
| 61 | + | commits: commits |
|
| 62 | + | .into_iter() |
|
| 63 | + | .map(|commit| CommitSlot { |
|
| 64 | + | commit, |
|
| 65 | + | reviewed: false, |
|
| 66 | + | loaded: None, |
|
| 67 | + | }) |
|
| 68 | + | .collect(), |
|
| 69 | + | current: 0, |
|
| 70 | + | visibility: Visibility::default(), |
|
| 71 | + | mode: Mode::Diff, |
|
| 72 | + | parked: None, |
|
| 73 | + | list: ListState::new(), |
|
| 74 | + | options, |
|
| 75 | + | backend, |
|
| 76 | + | brain, |
|
| 77 | + | comments, |
|
| 78 | + | events_tx, |
|
| 79 | + | generation: 0, |
|
| 80 | + | highlighter: None, |
|
| 81 | + | context_fetch: ContextFetch::default(), |
|
| 82 | + | }; |
|
| 83 | + | session.current()?; |
|
| 84 | + | session.reconcile_reviews()?; |
|
| 85 | + | session.activate()?; |
|
| 86 | + | session.redraw()?; |
|
| 87 | + | ||
| 88 | + | while let Ok(event) = events_rx.recv() { |
|
| 89 | + | let mut redraw = false; |
|
| 90 | + | let mut next = Some(event); |
|
| 91 | + | // Drain queued events before repainting so bursts coalesce into one |
|
| 92 | + | // frame. |
|
| 93 | + | while let Some(event) = next { |
|
| 94 | + | match session.update(event)? { |
|
| 95 | + | Update::Continue => {} |
|
| 96 | + | Update::Redraw => redraw = true, |
|
| 97 | + | Update::Quit => return Ok(()), |
|
| 98 | + | } |
|
| 99 | + | next = events_rx.try_recv().ok(); |
|
| 100 | + | } |
|
| 101 | + | if redraw { |
|
| 102 | + | session.redraw()?; |
|
| 103 | + | } |
|
| 104 | + | } |
|
| 105 | + | Ok(()) |
|
| 106 | + | } |
|
| 107 | + | ||
| 108 | + | /// Interactive terminal session state. |
|
| 109 | + | struct Session<'a> { |
|
| 110 | + | /// Terminal frame target. |
|
| 111 | + | terminal: &'a mut BrainTerminal, |
|
| 112 | + | /// Per-commit review slots, oldest first. |
|
| 113 | + | commits: Vec<CommitSlot>, |
|
| 114 | + | /// Index of the commit currently displayed. |
|
| 115 | + | current: usize, |
|
| 116 | + | /// Session-wide accepted-hunk visibility. |
|
| 117 | + | visibility: Visibility, |
|
| 118 | + | /// Active view: the commit list, the diff, or a hunk's comment box. |
|
| 119 | + | mode: Mode, |
|
| 120 | + | /// Hunk view kept alive while another tab is active, for Tab round-trips. |
|
| 121 | + | parked: Option<Box<HunkView>>, |
|
| 122 | + | /// Selection and scroll state for the commit-list tab. |
|
| 123 | + | list: ListState, |
|
| 124 | + | /// Viewer options used to build commit and per-hunk viewers. |
|
| 125 | + | options: DiffOptions, |
|
| 126 | + | /// Revision backend used for lazy commit loads and context refetches. |
|
| 127 | + | backend: Box<dyn Backend>, |
|
| 128 | + | /// Hidden review state storing accepted content and comments. |
|
| 129 | + | brain: Brain, |
|
| 130 | + | /// Review-wide persistent comment store. |
|
| 131 | + | comments: ReviewComments, |
|
| 132 | + | /// Sender used to respawn the highlighter for the current commit. |
|
| 133 | + | events_tx: Sender<TerminalEvent>, |
|
| 134 | + | /// Generation of the active highlighter; stale output is ignored. |
|
| 135 | + | generation: u64, |
|
| 136 | + | /// Highlighter for the current commit, respawned on each switch. |
|
| 137 | + | highlighter: Option<Highlighter>, |
|
| 138 | + | /// Whether a context refetch is in flight. |
|
| 139 | + | context_fetch: ContextFetch, |
|
| 140 | + | } |
|
| 141 | + | ||
| 142 | + | impl Session<'_> { |
|
| 143 | + | /// Returns the current commit's diff state, decoding it on first access. |
|
| 144 | + | fn current(&mut self) -> Result<&mut CommitReview, Error> { |
|
| 145 | + | self.load(self.current) |
|
| 146 | + | } |
|
| 147 | + | ||
| 148 | + | /// Returns commit `index`'s diff state, decoding it on first access. |
|
| 149 | + | fn load(&mut self, index: usize) -> Result<&mut CommitReview, Error> { |
|
| 150 | + | let slot = &mut self.commits[index]; |
|
| 151 | + | let loaded = match slot.loaded.take() { |
|
| 152 | + | Some(loaded) => loaded, |
|
| 153 | + | None => { |
|
| 154 | + | let document = self.backend.commit_diff(&slot.commit)?; |
|
| 155 | + | CommitReview::load( |
|
| 156 | + | &slot.commit, |
|
| 157 | + | document, |
|
| 158 | + | self.options.clone(), |
|
| 159 | + | &self.brain, |
|
| 160 | + | &self.comments, |
|
| 161 | + | )? |
|
| 162 | + | } |
|
| 163 | + | }; |
|
| 164 | + | Ok(slot.loaded.insert(loaded)) |
|
| 165 | + | } |
|
| 166 | + | ||
| 167 | + | /// Applies one terminal or worker event and records redraw work. |
|
| 168 | + | /// |
|
| 169 | + | /// Input is routed by active mode first so the commit list and hunk editor |
|
| 170 | + | /// can reserve keys that would otherwise belong to the diff viewer. Worker |
|
| 171 | + | /// output is tagged with a generation, letting stale highlighter results |
|
| 172 | + | /// from a previous commit be ignored after a commit switch. |
|
| 173 | + | fn update(&mut self, event: TerminalEvent) -> Result<Update, Error> { |
|
| 174 | + | match event { |
|
| 175 | + | TerminalEvent::Input(event) => { |
|
| 176 | + | let event = event?; |
|
| 177 | + | let resize = if matches!(event, Event::Resize(_)) { |
|
| 178 | + | Resize::Changed |
|
| 179 | + | } else { |
|
| 180 | + | Resize::Stable |
|
| 181 | + | }; |
|
| 182 | + | let control = match self.mode { |
|
| 183 | + | Mode::Hunk(_) => self.handle_hunk_key(event)?, |
|
| 184 | + | Mode::Commits => self.handle_commits_key(event)?, |
|
| 185 | + | Mode::Diff => { |
|
| 186 | + | if let Some(change) = context_change(&event) { |
|
| 187 | + | // Context expansion is asynchronous and may not |
|
| 188 | + | // redraw immediately, so it bypasses the ordinary |
|
| 189 | + | // diff input path. |
|
| 190 | + | self.request_context(change); |
|
| 191 | + | return Ok(Update::Continue); |
|
| 192 | + | } |
|
| 193 | + | let area = viewer_area(self.terminal.area()); |
|
| 194 | + | self.handle_key(event, area)? |
|
| 195 | + | } |
|
| 196 | + | }; |
|
| 197 | + | Ok(Update::from_control(control, resize)) |
|
| 198 | + | } |
|
| 199 | + | TerminalEvent::Highlight(generation, HighlightOutput::Highlights(results)) => { |
|
| 200 | + | if generation == self.generation { |
|
| 201 | + | // Always populate the cache so returning to the diff is |
|
| 202 | + | // instant, but only repaint when the diff is on screen. |
|
| 203 | + | let changed = self.commits[self.current] |
|
| 204 | + | .loaded |
|
| 205 | + | .as_mut() |
|
| 206 | + | .is_some_and(|loaded| loaded.viewer.apply_highlights(results)); |
|
| 207 | + | if changed && matches!(self.mode, Mode::Diff) { |
|
| 208 | + | self.draw_frame()?; |
|
| 209 | + | } |
|
| 210 | + | } |
|
| 211 | + | Ok(Update::Continue) |
|
| 212 | + | } |
|
| 213 | + | TerminalEvent::Highlight(generation, HighlightOutput::Context(update)) => { |
|
| 214 | + | if generation != self.generation { |
|
| 215 | + | return Ok(Update::Continue); |
|
| 216 | + | } |
|
| 217 | + | // A missing update still completes the in-flight request. |
|
| 218 | + | self.context_fetch = ContextFetch::Idle; |
|
| 219 | + | if let Some(update) = update { |
|
| 220 | + | let area = viewer_area(self.terminal.area()); |
|
| 221 | + | if let Some(loaded) = &mut self.commits[self.current].loaded { |
|
| 222 | + | loaded.viewer.apply_context_update(update, area); |
|
| 223 | + | } |
|
| 224 | + | return Ok(Update::Redraw); |
|
| 225 | + | } |
|
| 226 | + | Ok(Update::Continue) |
|
| 227 | + | } |
|
| 228 | + | } |
|
| 229 | + | } |
|
| 230 | + | ||
| 231 | + | /// Dispatches one input event, handling review keys before the viewer. |
|
| 232 | + | fn handle_key(&mut self, event: Event<()>, area: Rect) -> Result<Control, Error> { |
|
| 233 | + | match event { |
|
| 234 | + | Event::Key(Key::Char('a')) => { |
|
| 235 | + | self.accept_focused(area)?; |
|
| 236 | + | Ok(Control::Redraw) |
|
| 237 | + | } |
|
| 238 | + | Event::Key(Key::Char('v')) => { |
|
| 239 | + | self.visibility.show_accepted = !self.visibility.show_accepted; |
|
| 240 | + | self.refresh_visibility()?; |
|
| 241 | + | Ok(Control::Redraw) |
|
| 242 | + | } |
|
| 243 | + | Event::Key(Key::Char('n')) => self.apply(DiffAction::NextHunk, area), |
|
| 244 | + | Event::Key(Key::Char('p')) => self.apply(DiffAction::PreviousHunk, area), |
|
| 245 | + | Event::Key(Key::Char('c')) => { |
|
| 246 | + | self.enter_hunk_view(area)?; |
|
| 247 | + | Ok(Control::Redraw) |
|
| 248 | + | } |
|
| 249 | + | Event::Key(Key::Char(']')) => self.switch(1), |
|
| 250 | + | Event::Key(Key::Char('[')) => self.switch(-1), |
|
| 251 | + | Event::Key(Key::Tab) => { |
|
| 252 | + | self.next_tab(); |
|
| 253 | + | Ok(Control::Redraw) |
|
| 254 | + | } |
|
| 255 | + | _ => Ok(self.current()?.viewer.handle_input(event, area)), |
|
| 256 | + | } |
|
| 257 | + | } |
|
| 258 | + | ||
| 259 | + | /// Applies a viewer action, returning `Redraw` if the view changed. |
|
| 260 | + | fn apply(&mut self, action: DiffAction, area: Rect) -> Result<Control, Error> { |
|
| 261 | + | if self.current()?.viewer.apply(action, area) == ViewChange::Changed { |
|
| 262 | + | Ok(Control::Redraw) |
|
| 263 | + | } else { |
|
| 264 | + | Ok(Control::Continue) |
|
| 265 | + | } |
|
| 266 | + | } |
|
| 267 | + | ||
| 268 | + | /// Moves to another commit by `delta`. |
|
| 269 | + | fn switch(&mut self, delta: isize) -> Result<Control, Error> { |
|
| 270 | + | let last = self.commits.len().saturating_sub(1); |
|
| 271 | + | let next = (self.current as isize + delta).clamp(0, last as isize) as usize; |
|
| 272 | + | if next == self.current { |
|
| 273 | + | return Ok(Control::Continue); |
|
| 274 | + | } |
|
| 275 | + | self.select_commit(next)?; |
|
| 276 | + | ||
| 277 | + | Ok(Control::Redraw) |
|
| 278 | + | } |
|
| 279 | + | ||
| 280 | + | /// Displays the commit at `index`, loading it and respawning workers. |
|
| 281 | + | fn select_commit(&mut self, index: usize) -> Result<(), Error> { |
|
| 282 | + | self.current = index; |
|
| 283 | + | self.parked = None; |
|
| 284 | + | ||
| 285 | + | let newly_loaded = self.commits[index].loaded.is_none(); |
|
| 286 | + | self.current()?; |
|
| 287 | + | ||
| 288 | + | if newly_loaded { |
|
| 289 | + | // Classify the freshly decoded hunks against the accepted tree. |
|
| 290 | + | self.reconcile_reviews()?; |
|
| 291 | + | } |
|
| 292 | + | self.activate()?; |
|
| 293 | + | ||
| 294 | + | Ok(()) |
|
| 295 | + | } |
|
| 296 | + | ||
| 297 | + | /// Routes one key while the commit-list tab is open. |
|
| 298 | + | fn handle_commits_key(&mut self, event: Event<()>) -> Result<Control, Error> { |
|
| 299 | + | let delta = match event { |
|
| 300 | + | Event::Key(Key::Char('q')) => return Ok(Control::Quit), |
|
| 301 | + | Event::Key(Key::Char('j') | Key::Down) |
|
| 302 | + | | Event::Mouse(Mouse::Press { |
|
| 303 | + | button: MouseButton::WheelDown, |
|
| 304 | + | .. |
|
| 305 | + | }) => 1, |
|
| 306 | + | Event::Key(Key::Char('k') | Key::Up) |
|
| 307 | + | | Event::Mouse(Mouse::Press { |
|
| 308 | + | button: MouseButton::WheelUp, |
|
| 309 | + | .. |
|
| 310 | + | }) => -1, |
|
| 311 | + | Event::Key(Key::Enter) => { |
|
| 312 | + | let selected = self.list.selected(); |
|
| 313 | + | if selected != self.current { |
|
| 314 | + | self.select_commit(selected)?; |
|
| 315 | + | } |
|
| 316 | + | self.mode = Mode::Diff; |
|
| 317 | + | return Ok(Control::Redraw); |
|
| 318 | + | } |
|
| 319 | + | Event::Key(Key::Tab) => { |
|
| 320 | + | self.next_tab(); |
|
| 321 | + | return Ok(Control::Redraw); |
|
| 322 | + | } |
|
| 323 | + | Event::Resize(_) => return Ok(Control::Redraw), |
|
| 324 | + | _ => return Ok(Control::Continue), |
|
| 325 | + | }; |
|
| 326 | + | if self.list.move_by(delta, self.commits.len()) { |
|
| 327 | + | Ok(Control::Redraw) |
|
| 328 | + | } else { |
|
| 329 | + | Ok(Control::Continue) |
|
| 330 | + | } |
|
| 331 | + | } |
|
| 332 | + | ||
| 333 | + | /// Persists acceptance of the focused hunk, or focuses one when none is. |
|
| 334 | + | /// |
|
| 335 | + | /// Accepting updates the hidden tree first, then rebuilds all per-commit |
|
| 336 | + | /// accepted hunk sets from that tree. The visible commit state is derived |
|
| 337 | + | /// rather than patched locally so overlapping commits stay consistent. |
|
| 338 | + | fn accept_focused(&mut self, area: Rect) -> Result<(), Error> { |
|
| 339 | + | let loaded = self.current()?; |
|
| 340 | + | let Some(DiffFocus::Hunk(hunk)) = loaded.viewer.state().focus else { |
|
| 341 | + | // No hunk is focused yet: move focus to the first hunk so the next |
|
| 342 | + | // accept has an unambiguous target. |
|
| 343 | + | loaded.viewer.apply(DiffAction::NextHunk, area); |
|
| 344 | + | return Ok(()); |
|
| 345 | + | }; |
|
| 346 | + | if loaded.review.is_accepted(hunk) { |
|
| 347 | + | return Ok(()); |
|
| 348 | + | } |
|
| 349 | + | let Some(patch) = loaded.hunk_patches.get(&hunk).cloned() else { |
|
| 350 | + | return Ok(()); |
|
| 351 | + | }; |
|
| 352 | + | self.brain.apply_patch(&patch)?; |
|
| 353 | + | self.reconcile_reviews()?; |
|
| 354 | + | ||
| 355 | + | Ok(()) |
|
| 356 | + | } |
|
| 357 | + | ||
| 358 | + | /// Opens the hunk view for the focused hunk to author a comment. |
|
| 359 | + | fn enter_hunk_view(&mut self, area: Rect) -> Result<(), Error> { |
|
| 360 | + | let focus = self.current()?.viewer.state().focus; |
|
| 361 | + | let Some(DiffFocus::Hunk(hunk)) = focus else { |
|
| 362 | + | // Focus the first hunk so a later press has a target to comment on. |
|
| 363 | + | self.current()?.viewer.apply(DiffAction::NextHunk, area); |
|
| 364 | + | return Ok(()); |
|
| 365 | + | }; |
|
| 366 | + | // Resume a parked draft on the same hunk instead of discarding it. |
|
| 367 | + | if let Some(parked) = self.parked.take_if(|parked| parked.hunk == hunk) { |
|
| 368 | + | self.mode = Mode::Hunk(parked); |
|
| 369 | + | return Ok(()); |
|
| 370 | + | } |
|
| 371 | + | self.parked = None; |
|
| 372 | + | let mut options = self.options.clone(); |
|
| 373 | + | options.file_tree = FileTreeMode::Hidden; |
|
| 374 | + | ||
| 375 | + | let loaded = self.current()?; |
|
| 376 | + | let Some((file, focused)) = loaded.files.iter().find_map(|file| { |
|
| 377 | + | let focused = file.hunks.iter().find(|candidate| candidate.id == hunk)?; |
|
| 378 | + | Some((file, focused)) |
|
| 379 | + | }) else { |
|
| 380 | + | return Ok(()); |
|
| 381 | + | }; |
|
| 382 | + | let document = DiffDocument::for_hunks(file, [focused.clone()]); |
|
| 383 | + | let viewer = DiffViewer::new(document, options); |
|
| 384 | + | ||
| 385 | + | self.mode = Mode::Hunk(Box::new(HunkView { |
|
| 386 | + | hunk, |
|
| 387 | + | viewer, |
|
| 388 | + | input: TextInput::new(), |
|
| 389 | + | })); |
|
| 390 | + | ||
| 391 | + | Ok(()) |
|
| 392 | + | } |
|
| 393 | + | ||
| 394 | + | /// Switches to the next review tab, parking any open hunk view. |
|
| 395 | + | fn next_tab(&mut self) { |
|
| 396 | + | self.mode = match mem::replace(&mut self.mode, Mode::Diff) { |
|
| 397 | + | Mode::Commits => Mode::Diff, |
|
| 398 | + | Mode::Diff => { |
|
| 399 | + | if let Some(parked) = self.parked.take() { |
|
| 400 | + | Mode::Hunk(parked) |
|
| 401 | + | } else { |
|
| 402 | + | self.list.select(self.current, self.commits.len()); |
|
| 403 | + | Mode::Commits |
|
| 404 | + | } |
|
| 405 | + | } |
|
| 406 | + | Mode::Hunk(view) => { |
|
| 407 | + | self.parked = Some(view); |
|
| 408 | + | self.list.select(self.current, self.commits.len()); |
|
| 409 | + | Mode::Commits |
|
| 410 | + | } |
|
| 411 | + | }; |
|
| 412 | + | } |
|
| 413 | + | ||
| 414 | + | /// Routes one key to the comment editor while the hunk view is open. |
|
| 415 | + | fn handle_hunk_key(&mut self, event: Event<()>) -> Result<Control, Error> { |
|
| 416 | + | match event { |
|
| 417 | + | Event::Key(Key::Esc) => { |
|
| 418 | + | self.mode = Mode::Diff; |
|
| 419 | + | return Ok(Control::Redraw); |
|
| 420 | + | } |
|
| 421 | + | Event::Key(Key::Tab) => { |
|
| 422 | + | self.next_tab(); |
|
| 423 | + | return Ok(Control::Redraw); |
|
| 424 | + | } |
|
| 425 | + | // Ctrl+Enter submits; the enhanced keyboard protocol reports it as |
|
| 426 | + | // a control Return distinct from a plain Enter. |
|
| 427 | + | Event::Key(Key::Ctrl('\r')) => { |
|
| 428 | + | self.save_comment()?; |
|
| 429 | + | return Ok(Control::Redraw); |
|
| 430 | + | } |
|
| 431 | + | _ => {} |
|
| 432 | + | } |
|
| 433 | + | let Mode::Hunk(view) = &mut self.mode else { |
|
| 434 | + | return Ok(Control::Continue); |
|
| 435 | + | }; |
|
| 436 | + | let changed = match event { |
|
| 437 | + | Event::Key(Key::Enter) => view.input.newline(), |
|
| 438 | + | Event::Key(key) => view.input.input(key), |
|
| 439 | + | Event::Resize(_) => true, |
|
| 440 | + | _ => false, |
|
| 441 | + | }; |
|
| 442 | + | Ok(if changed { |
|
| 443 | + | Control::Redraw |
|
| 444 | + | } else { |
|
| 445 | + | Control::Continue |
|
| 446 | + | }) |
|
| 447 | + | } |
|
| 448 | + | ||
| 449 | + | /// Stores the authored comment, if any, and clears the input box. |
|
| 450 | + | fn save_comment(&mut self) -> Result<(), Error> { |
|
| 451 | + | let Mode::Hunk(view) = &mut self.mode else { |
|
| 452 | + | return Ok(()); |
|
| 453 | + | }; |
|
| 454 | + | if view.input.is_empty() { |
|
| 455 | + | return Ok(()); |
|
| 456 | + | } |
|
| 457 | + | let Some(loaded) = &mut self.commits[self.current].loaded else { |
|
| 458 | + | return Ok(()); |
|
| 459 | + | }; |
|
| 460 | + | let body = view.input.value().to_owned(); |
|
| 461 | + | if loaded.comments.author(&mut self.comments, view.hunk, body) { |
|
| 462 | + | self.brain.write_comments(&self.comments.encode())?; |
|
| 463 | + | loaded.refresh_decorations(); |
|
| 464 | + | view.input = TextInput::new(); |
|
| 465 | + | } |
|
| 466 | + | Ok(()) |
|
| 467 | + | } |
|
| 468 | + | ||
| 469 | + | /// Applies current visibility and starts workers for the active commit. |
|
| 470 | + | /// |
|
| 471 | + | /// Every activation increments `generation`. Highlight and context results |
|
| 472 | + | /// carry that value back through the event channel, which prevents output |
|
| 473 | + | /// from an older commit viewer from mutating the newly active viewer. |
|
| 474 | + | fn activate(&mut self) -> Result<(), Error> { |
|
| 475 | + | self.refresh_visibility()?; |
|
| 476 | + | self.generation += 1; |
|
| 477 | + | ||
| 478 | + | let generation = self.generation; |
|
| 479 | + | let tx = self.events_tx.clone(); |
|
| 480 | + | let repo = Some(self.backend.repo(&self.commits[self.current].commit)); |
|
| 481 | + | let loaded = self.current()?; |
|
| 482 | + | let highlighter = spawn_highlighter(loaded.viewer.document(), repo, move |output| { |
|
| 483 | + | let _ = tx.send(TerminalEvent::Highlight(generation, output)); |
|
| 484 | + | }); |
|
| 485 | + | self.highlighter = Some(highlighter); |
|
| 486 | + | self.context_fetch = ContextFetch::Idle; |
|
| 487 | + | ||
| 488 | + | Ok(()) |
|
| 489 | + | } |
|
| 490 | + | ||
| 491 | + | /// Rebuilds the current commit's files to match accepted-hunk visibility. |
|
| 492 | + | /// |
|
| 493 | + | /// The original decoded files are kept in `CommitReview::files`; the viewer |
|
| 494 | + | /// receives a filtered copy when accepted hunks are hidden. Collapsed-file |
|
| 495 | + | /// state is preserved across the replacement and extended for fully |
|
| 496 | + | /// accepted files. |
|
| 497 | + | fn refresh_visibility(&mut self) -> Result<(), Error> { |
|
| 498 | + | let visibility = self.visibility; |
|
| 499 | + | let loaded = self.current()?; |
|
| 500 | + | let mut collapsed = loaded.viewer.state().collapsed_files.clone(); |
|
| 501 | + | collapsed.extend(loaded.accepted_files()); |
|
| 502 | + | ||
| 503 | + | let files: Vec<FileDiff> = if visibility.show_accepted { |
|
| 504 | + | loaded.files.clone() |
|
| 505 | + | } else { |
|
| 506 | + | loaded |
|
| 507 | + | .files |
|
| 508 | + | .iter() |
|
| 509 | + | .map(|file| { |
|
| 510 | + | let mut file = file.clone(); |
|
| 511 | + | file.hunks |
|
| 512 | + | .retain(|hunk| !loaded.review.is_accepted(hunk.id)); |
|
| 513 | + | file |
|
| 514 | + | }) |
|
| 515 | + | .collect() |
|
| 516 | + | }; |
|
| 517 | + | loaded.viewer.replace_file_diffs(files); |
|
| 518 | + | loaded.viewer.set_collapsed_files(collapsed); |
|
| 519 | + | ||
| 520 | + | Ok(()) |
|
| 521 | + | } |
|
| 522 | + | ||
| 523 | + | /// Reconciles per-commit review state from the hidden tree. |
|
| 524 | + | /// |
|
| 525 | + | /// This is the only place that replaces `Review` sets and reviewed marks. |
|
| 526 | + | /// Keeping it as a full recomputation avoids subtle drift between the |
|
| 527 | + | /// persistent accepted tree, the current commit list, and per-viewer |
|
| 528 | + | /// decorations. Commits that have not been decoded yet still receive their |
|
| 529 | + | /// reviewed mark, which needs no hunk data. |
|
| 530 | + | fn reconcile_reviews(&mut self) -> Result<(), Error> { |
|
| 531 | + | let commits = self |
|
| 532 | + | .commits |
|
| 533 | + | .iter() |
|
| 534 | + | .map(|slot| CommitHunks { |
|
| 535 | + | commit: &slot.commit, |
|
| 536 | + | hunks: slot.loaded.as_ref().map(|loaded| &loaded.patch_ids), |
|
| 537 | + | }) |
|
| 538 | + | .collect::<Vec<_>>(); |
|
| 539 | + | let reconciled = self.brain.reconcile(&commits)?; |
|
| 540 | + | for (slot, reconciled) in self.commits.iter_mut().zip(reconciled) { |
|
| 541 | + | slot.reviewed = reconciled.reviewed; |
|
| 542 | + | if let Some(loaded) = &mut slot.loaded { |
|
| 543 | + | loaded.review.replace(reconciled.accepted); |
|
| 544 | + | loaded.refresh_decorations(); |
|
| 545 | + | } |
|
| 546 | + | } |
|
| 547 | + | self.refresh_visibility()?; |
|
| 548 | + | Ok(()) |
|
| 549 | + | } |
|
| 550 | + | ||
| 551 | + | /// Draws a frame, requesting highlights for visible rows before it and |
|
| 552 | + | /// lookahead rows after it. |
|
| 553 | + | fn redraw(&mut self) -> io::Result<()> { |
|
| 554 | + | let area = viewer_area(self.terminal.area()); |
|
| 555 | + | if let Some(loaded) = &mut self.commits[self.current].loaded { |
|
| 556 | + | let requests = loaded.viewer.visible_highlight_requests(area); |
|
| 557 | + | self.queue_highlights(requests); |
|
| 558 | + | } |
|
| 559 | + | self.draw_frame()?; |
|
| 560 | + | if let Some(loaded) = &mut self.commits[self.current].loaded { |
|
| 561 | + | let requests = loaded.viewer.lookahead_highlight_requests(area); |
|
| 562 | + | self.queue_highlights(requests); |
|
| 563 | + | } |
|
| 564 | + | Ok(()) |
|
| 565 | + | } |
|
| 566 | + | ||
| 567 | + | /// Queues highlight work, cancelling rows the worker cannot accept. |
|
| 568 | + | /// |
|
| 569 | + | /// The worker may drop requests when its queue is full or stale. Dropped |
|
| 570 | + | /// rows are removed from the viewer's pending cache so they can be requested |
|
| 571 | + | /// again on a later redraw. |
|
| 572 | + | fn queue_highlights(&mut self, requests: Vec<HighlightRequest>) { |
|
| 573 | + | if requests.is_empty() { |
|
| 574 | + | return; |
|
| 575 | + | } |
|
| 576 | + | let dropped = self |
|
| 577 | + | .highlighter |
|
| 578 | + | .as_ref() |
|
| 579 | + | .and_then(|highlighter| highlighter.highlight(requests)); |
|
| 580 | + | if let Some(dropped) = dropped |
|
| 581 | + | && let Some(loaded) = &mut self.commits[self.current].loaded |
|
| 582 | + | { |
|
| 583 | + | loaded.viewer.cancel_highlights(dropped); |
|
| 584 | + | } |
|
| 585 | + | } |
|
| 586 | + | ||
| 587 | + | /// Requests context refetch work for one context change. |
|
| 588 | + | /// |
|
| 589 | + | /// Only one context request is in flight per active commit. Requests are |
|
| 590 | + | /// tied to the current highlighter generation by `activate`, so stale |
|
| 591 | + | /// context updates are ignored in [`Session::update`]. |
|
| 592 | + | fn request_context(&mut self, change: ContextChange) { |
|
| 593 | + | if self.context_fetch == ContextFetch::Pending { |
|
| 594 | + | return; |
|
| 595 | + | } |
|
| 596 | + | let Some(loaded) = &mut self.commits[self.current].loaded else { |
|
| 597 | + | return; |
|
| 598 | + | }; |
|
| 599 | + | let Some(request) = loaded.viewer.context_request(change) else { |
|
| 600 | + | return; |
|
| 601 | + | }; |
|
| 602 | + | let queued = self |
|
| 603 | + | .highlighter |
|
| 604 | + | .as_ref() |
|
| 605 | + | .is_some_and(|highlighter| highlighter.context(request)); |
|
| 606 | + | if queued { |
|
| 607 | + | self.context_fetch = ContextFetch::Pending; |
|
| 608 | + | } |
|
| 609 | + | } |
|
| 610 | + | ||
| 611 | + | /// Draws one terminal frame without scheduling highlight work. |
|
| 612 | + | fn draw_frame(&mut self) -> io::Result<()> { |
|
| 613 | + | let mut footer = self.footer(); |
|
| 614 | + | let current = self.current; |
|
| 615 | + | match &mut self.mode { |
|
| 616 | + | Mode::Hunk(view) => { |
|
| 617 | + | let comments = self.commits[current] |
|
| 618 | + | .loaded |
|
| 619 | + | .as_ref() |
|
| 620 | + | .map_or(&[][..], |loaded| loaded.comments.for_hunk(view.hunk)); |
|
| 621 | + | let mut comment_lines = comment_block_lines(comments); |
|
| 622 | + | self.terminal.draw(|frame| { |
|
| 623 | + | let (body, footer_area) = Status::areas(frame.area); |
|
| 624 | + | frame.render_stateful_widget(&mut **view, body, &mut comment_lines); |
|
| 625 | + | frame.render_widget(&mut footer, footer_area); |
|
| 626 | + | })?; |
|
| 627 | + | } |
|
| 628 | + | Mode::Commits => { |
|
| 629 | + | let rows: Vec<Line> = self.commits.iter().map(commit_row).collect(); |
|
| 630 | + | self.terminal.draw(|frame| { |
|
| 631 | + | let (body, footer_area) = Status::areas(frame.area); |
|
| 632 | + | frame.render_stateful_widget(List::new(rows), body, &mut self.list); |
|
| 633 | + | frame.render_widget(&mut footer, footer_area); |
|
| 634 | + | })?; |
|
| 635 | + | } |
|
| 636 | + | Mode::Diff => { |
|
| 637 | + | self.terminal.draw(|frame| { |
|
| 638 | + | let (body, footer_area) = Status::areas(frame.area); |
|
| 639 | + | if let Some(loaded) = &mut self.commits[current].loaded { |
|
| 640 | + | frame.render_widget(&mut loaded.viewer, body); |
|
| 641 | + | } |
|
| 642 | + | frame.render_widget(&mut footer, footer_area); |
|
| 643 | + | })?; |
|
| 644 | + | } |
|
| 645 | + | } |
|
| 646 | + | // The terminal caret is a pure function of the active view: only the |
|
| 647 | + | // hunk view's comment editor shows it. |
|
| 648 | + | self.terminal |
|
| 649 | + | .set_cursor_visible(matches!(self.mode, Mode::Hunk(_))) |
|
| 650 | + | } |
|
| 651 | + | ||
| 652 | + | /// Returns the footer status line for the current commit. |
|
| 653 | + | fn footer(&self) -> Status { |
|
| 654 | + | let slot = &self.commits[self.current]; |
|
| 655 | + | Status { |
|
| 656 | + | position: (self.current + 1, self.commits.len()), |
|
| 657 | + | short: slot.commit.id.short(), |
|
| 658 | + | summary: slot.commit.summary.clone(), |
|
| 659 | + | accepted: slot |
|
| 660 | + | .loaded |
|
| 661 | + | .as_ref() |
|
| 662 | + | .map_or(0, |loaded| loaded.review.count()), |
|
| 663 | + | visibility: self.visibility, |
|
| 664 | + | } |
|
| 665 | + | } |
|
| 666 | + | } |
crates/brain/src/session/commit.rs
added
+145 -0
| 1 | + | //! Per-commit review state for the session. |
|
| 2 | + | ||
| 3 | + | use std::collections::{BTreeMap, BTreeSet}; |
|
| 4 | + | ||
| 5 | + | use rustik_diff::{DiffDocument, DiffOptions, DiffViewer, Encode as _, FileDiff, FileId, HunkId}; |
|
| 6 | + | use rustik_repo::PatchId; |
|
| 7 | + | ||
| 8 | + | use crate::backend::{Brain, Commit}; |
|
| 9 | + | use crate::comments::{CommentTarget, Comments, ReviewComments}; |
|
| 10 | + | use crate::decorate::Decorations; |
|
| 11 | + | use crate::error::Error; |
|
| 12 | + | use crate::review::Review; |
|
| 13 | + | ||
| 14 | + | /// One commit in the reviewed range: header data plus lazily decoded state. |
|
| 15 | + | pub(super) struct CommitSlot { |
|
| 16 | + | /// Commit under review. |
|
| 17 | + | pub(super) commit: Commit, |
|
| 18 | + | /// Whether the hidden tree contains this commit's entire diff. |
|
| 19 | + | /// |
|
| 20 | + | /// Derived by [`crate::session::Session::reconcile_reviews`] from tree |
|
| 21 | + | /// state alone, so the commit list can mark reviewed commits before they |
|
| 22 | + | /// are decoded. |
|
| 23 | + | pub(super) reviewed: bool, |
|
| 24 | + | /// Decoded diff state, populated when the commit is first displayed. |
|
| 25 | + | pub(super) loaded: Option<CommitReview>, |
|
| 26 | + | } |
|
| 27 | + | ||
| 28 | + | /// Decoded review state for one commit: its viewer, accepted hunks, and the |
|
| 29 | + | /// full file diffs used to restore hidden hunks. |
|
| 30 | + | /// |
|
| 31 | + | /// Each commit keeps its own viewer so its highlight and word-diff caches |
|
| 32 | + | /// persist across commit switches, and its own [`Review`] because decoded hunk |
|
| 33 | + | /// ids restart per commit. |
|
| 34 | + | pub(super) struct CommitReview { |
|
| 35 | + | /// Viewer rendering this commit's diff, owning its caches. |
|
| 36 | + | pub(super) viewer: DiffViewer, |
|
| 37 | + | /// Accepted-hunk state, reconciled from the hidden tree. |
|
| 38 | + | pub(super) review: Review, |
|
| 39 | + | /// Per-hunk comment view for this commit. |
|
| 40 | + | pub(super) comments: Comments, |
|
| 41 | + | /// Single-hunk patch text keyed by hunk id. |
|
| 42 | + | pub(super) hunk_patches: BTreeMap<HunkId, String>, |
|
| 43 | + | /// Stable patch id of each original hunk, computed once at load. |
|
| 44 | + | pub(super) patch_ids: BTreeMap<HunkId, PatchId>, |
|
| 45 | + | /// Full, unfiltered file diffs used to restore hidden hunks. |
|
| 46 | + | pub(super) files: Vec<FileDiff>, |
|
| 47 | + | /// Original hunk ids per file, used for decoration snapshots. |
|
| 48 | + | pub(super) file_hunks: BTreeMap<FileId, Vec<HunkId>>, |
|
| 49 | + | } |
|
| 50 | + | ||
| 51 | + | impl CommitReview { |
|
| 52 | + | /// Decodes one commit's review state from its diff document. |
|
| 53 | + | /// |
|
| 54 | + | /// Single-hunk patches and their patch ids are computed here, once, so |
|
| 55 | + | /// later reconciliations only hash residual hunks and comment lookups can |
|
| 56 | + | /// match on stable ids. |
|
| 57 | + | pub(super) fn load( |
|
| 58 | + | commit: &Commit, |
|
| 59 | + | document: DiffDocument, |
|
| 60 | + | options: DiffOptions, |
|
| 61 | + | brain: &Brain, |
|
| 62 | + | store: &ReviewComments, |
|
| 63 | + | ) -> Result<Self, Error> { |
|
| 64 | + | let viewer = DiffViewer::new(document, options); |
|
| 65 | + | let files = viewer.document().files.clone(); |
|
| 66 | + | let heading = format!("{} {}", commit.id.short(), commit.summary); |
|
| 67 | + | let mut hunk_patches = BTreeMap::new(); |
|
| 68 | + | let mut patch_ids = BTreeMap::new(); |
|
| 69 | + | let mut targets = BTreeMap::new(); |
|
| 70 | + | let mut file_hunks = BTreeMap::new(); |
|
| 71 | + | ||
| 72 | + | for file in &files { |
|
| 73 | + | let path = file.header.display_path().map(|path| path.to_path_buf()); |
|
| 74 | + | file_hunks.insert( |
|
| 75 | + | file.id, |
|
| 76 | + | file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>(), |
|
| 77 | + | ); |
|
| 78 | + | for hunk in &file.hunks { |
|
| 79 | + | let patch = DiffDocument::for_hunks(file, [hunk.clone()]).to_unified_string()?; |
|
| 80 | + | let patch_id = brain.hunk_patch_id(file, hunk)?; |
|
| 81 | + | targets.insert( |
|
| 82 | + | hunk.id, |
|
| 83 | + | CommentTarget { |
|
| 84 | + | heading: heading.clone(), |
|
| 85 | + | path: path.clone(), |
|
| 86 | + | patch_id: patch_id.clone(), |
|
| 87 | + | }, |
|
| 88 | + | ); |
|
| 89 | + | patch_ids.insert(hunk.id, patch_id); |
|
| 90 | + | hunk_patches.insert(hunk.id, patch); |
|
| 91 | + | } |
|
| 92 | + | } |
|
| 93 | + | let comments = Comments::new(store, targets); |
|
| 94 | + | let mut loaded = Self { |
|
| 95 | + | viewer, |
|
| 96 | + | review: Review::new(), |
|
| 97 | + | comments, |
|
| 98 | + | hunk_patches, |
|
| 99 | + | patch_ids, |
|
| 100 | + | files, |
|
| 101 | + | file_hunks, |
|
| 102 | + | }; |
|
| 103 | + | loaded.refresh_decorations(); |
|
| 104 | + | ||
| 105 | + | Ok(loaded) |
|
| 106 | + | } |
|
| 107 | + | ||
| 108 | + | /// Returns whether every original hunk of `file` has been accepted. |
|
| 109 | + | fn accepts_file(&self, file: &FileDiff) -> bool { |
|
| 110 | + | self.review |
|
| 111 | + | .accepts_all(file.hunks.iter().map(|hunk| hunk.id)) |
|
| 112 | + | } |
|
| 113 | + | ||
| 114 | + | /// Returns files whose original hunks have all been accepted. |
|
| 115 | + | pub(super) fn accepted_files(&self) -> BTreeSet<FileId> { |
|
| 116 | + | self.files |
|
| 117 | + | .iter() |
|
| 118 | + | .filter(|file| self.accepts_file(file)) |
|
| 119 | + | .map(|file| file.id) |
|
| 120 | + | .collect() |
|
| 121 | + | } |
|
| 122 | + | ||
| 123 | + | /// Reinstalls a fresh decoration snapshot on the viewer. |
|
| 124 | + | /// |
|
| 125 | + | /// Decorations are immutable snapshots, so this must run after every |
|
| 126 | + | /// change to acceptance or comment state for the viewer to observe it. |
|
| 127 | + | pub(super) fn refresh_decorations(&mut self) { |
|
| 128 | + | self.viewer.set_decorator(Decorations::snapshot( |
|
| 129 | + | &self.review, |
|
| 130 | + | &self.comments, |
|
| 131 | + | &self.file_hunks, |
|
| 132 | + | )); |
|
| 133 | + | } |
|
| 134 | + | } |
|
| 135 | + | ||
| 136 | + | #[cfg(test)] |
|
| 137 | + | mod tests { |
|
| 138 | + | use super::*; |
|
| 139 | + | use rustik_diff::Decode as _; |
|
| 140 | + | ||
| 141 | + | /// Builds a two-file review for accepted-file tests. |
|
| 142 | + | fn review_with_two_files() -> CommitReview { |
|
| 143 | + | let document = DiffDocument::decode_str( |
|
| 144 | + | "\ |
|
| 145 | + |
a.rs
+0 -0
b.rs
+0 -0
crates/brain/src/session/event.rs
added
+93 -0
| 1 | + | //! Terminal and worker events for the review session. |
|
| 2 | + | ||
| 3 | + | use std::io; |
|
| 4 | + | use std::sync::mpsc::Sender; |
|
| 5 | + | use std::thread; |
|
| 6 | + | ||
| 7 | + | use rustik_diff::{ContextChange, HighlightOutput}; |
|
| 8 | + | use rustik_tui::event::Modifiers; |
|
| 9 | + | use rustik_tui::{Control, Event, Key, Mouse, MouseButton}; |
|
| 10 | + | use rustik_tui_termion as tui_termion; |
|
| 11 | + | ||
| 12 | + | /// Whether a context refetch is in flight. |
|
| 13 | + | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
|
| 14 | + | pub(super) enum ContextFetch { |
|
| 15 | + | /// No context request is currently running. |
|
| 16 | + | #[default] |
|
| 17 | + | Idle, |
|
| 18 | + | /// A context request is currently running. |
|
| 19 | + | Pending, |
|
| 20 | + | } |
|
| 21 | + | ||
| 22 | + | /// Result of applying one terminal or worker event. |
|
| 23 | + | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
|
| 24 | + | pub(super) enum Update { |
|
| 25 | + | /// Continue without repainting the frame. |
|
| 26 | + | Continue, |
|
| 27 | + | /// Continue after repainting the frame. |
|
| 28 | + | Redraw, |
|
| 29 | + | /// Exit the session loop. |
|
| 30 | + | Quit, |
|
| 31 | + | } |
|
| 32 | + | ||
| 33 | + | impl Update { |
|
| 34 | + | /// Converts a viewer control result and resize state into a session update. |
|
| 35 | + | pub(super) fn from_control(control: Control, resize: Resize) -> Self { |
|
| 36 | + | match control { |
|
| 37 | + | Control::Quit => Self::Quit, |
|
| 38 | + | Control::Redraw => Self::Redraw, |
|
| 39 | + | Control::Continue | Control::Wait if resize == Resize::Changed => Self::Redraw, |
|
| 40 | + | Control::Continue | Control::Wait => Self::Continue, |
|
| 41 | + | } |
|
| 42 | + | } |
|
| 43 | + | } |
|
| 44 | + | ||
| 45 | + | /// Whether the terminal size changed during an input event. |
|
| 46 | + | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
|
| 47 | + | pub(super) enum Resize { |
|
| 48 | + | /// The terminal size stayed the same. |
|
| 49 | + | Stable, |
|
| 50 | + | /// The terminal reported a new size. |
|
| 51 | + | Changed, |
|
| 52 | + | } |
|
| 53 | + | ||
| 54 | + | /// Event delivered to the terminal loop. |
|
| 55 | + | pub(super) enum TerminalEvent { |
|
| 56 | + | /// Terminal input event. |
|
| 57 | + | Input(io::Result<Event<()>>), |
|
| 58 | + | /// Background highlighter output, tagged with its generation. |
|
| 59 | + | Highlight(u64, HighlightOutput), |
|
| 60 | + | } |
|
| 61 | + | ||
| 62 | + | impl TerminalEvent { |
|
| 63 | + | /// Spawns the blocking input reader. |
|
| 64 | + | pub(super) fn spawn_input_worker(tx: Sender<Self>) { |
|
| 65 | + | thread::spawn(move || { |
|
| 66 | + | for event in tui_termion::term::events() { |
|
| 67 | + | if tx.send(Self::Input(event)).is_err() { |
|
| 68 | + | break; |
|
| 69 | + | } |
|
| 70 | + | } |
|
| 71 | + | }); |
|
| 72 | + | } |
|
| 73 | + | } |
|
| 74 | + | ||
| 75 | + | /// Returns the context change represented by an input event. |
|
| 76 | + | pub(super) fn context_change(event: &Event<()>) -> Option<ContextChange> { |
|
| 77 | + | match event { |
|
| 78 | + | Event::Key(Key::Char('.')) => Some(ContextChange::Increase), |
|
| 79 | + | Event::Mouse(Mouse::Press { |
|
| 80 | + | button: MouseButton::WheelUp, |
|
| 81 | + | modifiers, |
|
| 82 | + | .. |
|
| 83 | + | }) if modifiers.contains(Modifiers::CONTROL) => Some(ContextChange::Increase), |
|
| 84 | + | Event::Key(Key::Char(',')) => Some(ContextChange::Decrease), |
|
| 85 | + | Event::Mouse(Mouse::Press { |
|
| 86 | + | button: MouseButton::WheelDown, |
|
| 87 | + | modifiers, |
|
| 88 | + | .. |
|
| 89 | + | }) if modifiers.contains(Modifiers::CONTROL) => Some(ContextChange::Decrease), |
|
| 90 | + | Event::Key(Key::Char('x')) => Some(ContextChange::ToggleFile), |
|
| 91 | + | _ => None, |
|
| 92 | + | } |
|
| 93 | + | } |
crates/brain/src/session/hunk.rs
added
+97 -0
| 1 | + | //! Hunk comment editor view. |
|
| 2 | + | ||
| 3 | + | use rustik_diff::{DiffViewer, HunkId}; |
|
| 4 | + | use rustik_tui::layout::Layout; |
|
| 5 | + | use rustik_tui::{ |
|
| 6 | + | Buffer, Constraint, Direction, Length, Line, RenderResult, Size, StatefulWidget, TextField, |
|
| 7 | + | TextInput, |
|
| 8 | + | }; |
|
| 9 | + | ||
| 10 | + | use super::status::heading; |
|
| 11 | + | ||
| 12 | + | /// Maximum rows the comment input grows to. |
|
| 13 | + | const MAX_INPUT_ROWS: usize = 6; |
|
| 14 | + | /// Maximum rows used to list a hunk's existing comments. |
|
| 15 | + | const MAX_COMMENT_ROWS: usize = 8; |
|
| 16 | + | /// Hint shown above the comment input box. |
|
| 17 | + | const COMMENT_HINT: &str = |
|
| 18 | + | "comment \u{00b7} Enter newline \u{00b7} Ctrl-Enter save \u{00b7} Esc cancel"; |
|
| 19 | + | ||
| 20 | + | /// State for the hunk view: the hunk, its isolated viewer, and the in-progress |
|
| 21 | + | /// comment. |
|
| 22 | + | #[derive(Debug)] |
|
| 23 | + | pub(super) struct HunkView { |
|
| 24 | + | /// Hunk being commented on. |
|
| 25 | + | pub(super) hunk: HunkId, |
|
| 26 | + | /// Viewer rendering the single hunk in isolation. |
|
| 27 | + | pub(super) viewer: DiffViewer, |
|
| 28 | + | /// Comment text being authored. |
|
| 29 | + | pub(super) input: TextInput, |
|
| 30 | + | } |
|
| 31 | + | ||
| 32 | + | impl StatefulWidget for HunkView { |
|
| 33 | + | type State = Vec<Line>; |
|
| 34 | + | ||
| 35 | + | fn size(&self, parent: Constraint) -> Size { |
|
| 36 | + | parent.bounded_size() |
|
| 37 | + | } |
|
| 38 | + | ||
| 39 | + | fn render_with_state( |
|
| 40 | + | &mut self, |
|
| 41 | + | area: rustik_tui::Rect, |
|
| 42 | + | buf: &mut Buffer, |
|
| 43 | + | comments: &mut Self::State, |
|
| 44 | + | ) -> RenderResult { |
|
| 45 | + | if area.is_empty() { |
|
| 46 | + | return RenderResult::default(); |
|
| 47 | + | } |
|
| 48 | + | let input_rows = self |
|
| 49 | + | .input |
|
| 50 | + | .value() |
|
| 51 | + | .split('\n') |
|
| 52 | + | .count() |
|
| 53 | + | .clamp(1, MAX_INPUT_ROWS); |
|
| 54 | + | let input_h = (input_rows + 1).min(area.rows); |
|
| 55 | + | let comments_h = if comments.is_empty() { |
|
| 56 | + | 0 |
|
| 57 | + | } else { |
|
| 58 | + | (comments.len().min(MAX_COMMENT_ROWS) + 1).min(area.rows.saturating_sub(input_h)) |
|
| 59 | + | }; |
|
| 60 | + | let [hunk_area, comments_area, input_area] = Layout::new(Direction::Vertical) |
|
| 61 | + | .child(Length::Fill(1)) |
|
| 62 | + | .child(Length::Fixed(comments_h)) |
|
| 63 | + | .child(Length::Fixed(input_h)) |
|
| 64 | + | .areas(area); |
|
| 65 | + | ||
| 66 | + | self.viewer.render(hunk_area, buf); |
|
| 67 | + | ||
| 68 | + | if !comments_area.is_empty() { |
|
| 69 | + | let (heading_area, body_area) = comments_area.split_top(1); |
|
| 70 | + | ||
| 71 | + | buf.set_line( |
|
| 72 | + | heading_area.x, |
|
| 73 | + | heading_area.y, |
|
| 74 | + | &heading("comments", area.cols), |
|
| 75 | + | ); |
|
| 76 | + | Line::renders( |
|
| 77 | + | comments.iter().take(comments_h - 1).cloned(), |
|
| 78 | + | body_area, |
|
| 79 | + | buf, |
|
| 80 | + | ); |
|
| 81 | + | } |
|
| 82 | + | let (heading_area, input_area) = input_area.split_top(1); |
|
| 83 | + | ||
| 84 | + | buf.set_line( |
|
| 85 | + | heading_area.x, |
|
| 86 | + | heading_area.y, |
|
| 87 | + | &heading(COMMENT_HINT, area.cols), |
|
| 88 | + | ); |
|
| 89 | + | ||
| 90 | + | if !input_area.is_empty() { |
|
| 91 | + | return TextField::new() |
|
| 92 | + | .placeholder("Write a comment...") |
|
| 93 | + | .render_with_state(input_area, buf, &mut self.input); |
|
| 94 | + | } |
|
| 95 | + | RenderResult::default() |
|
| 96 | + | } |
|
| 97 | + | } |
crates/brain/src/session/status.rs
added
+169 -0
| 1 | + | //! Status and chrome rendering for the review session. |
|
| 2 | + | ||
| 3 | + | use rustik_tui::{Buffer, Color, Constraint, HStack, Label, Line, Rect, Size, Style, Widget}; |
|
| 4 | + | ||
| 5 | + | use crate::comments::Comment; |
|
| 6 | + | use crate::review::Visibility; |
|
| 7 | + | ||
| 8 | + | use super::commit::CommitSlot; |
|
| 9 | + | ||
| 10 | + | /// Number of rows reserved for the bottom footer when possible. |
|
| 11 | + | const FOOTER_ROWS: usize = 1; |
|
| 12 | + | /// Foreground color for dim footer text. |
|
| 13 | + | const FOOTER_FG: Color = Color::Fixed(240); |
|
| 14 | + | /// Background color for the footer row. |
|
| 15 | + | const FOOTER_BG: Color = Color::Fixed(233); |
|
| 16 | + | /// Marker prefixing a stored comment in the hunk view. |
|
| 17 | + | const COMMENT_PREFIX: &str = "\u{1F5E8}"; |
|
| 18 | + | /// Marker shown beside a commit whose hunks have all been accepted. |
|
| 19 | + | const REVIEWED_MARK: char = '\u{2713}'; |
|
| 20 | + | /// Marker shown when accepted hunks are visible in the footer. |
|
| 21 | + | const APPROVED_HUNKS_MODE_ICON: &str = "\u{2714}"; |
|
| 22 | + | /// Marker shown when full-file mode is visible in the footer. |
|
| 23 | + | const FULL_FILE_MODE_ICON: &str = "\u{2195}"; |
|
| 24 | + | ||
| 25 | + | /// Footer status describing the current commit and review progress. |
|
| 26 | + | #[derive(Debug)] |
|
| 27 | + | pub(super) struct Status { |
|
| 28 | + | /// One-based position and total commit count. |
|
| 29 | + | pub(super) position: (usize, usize), |
|
| 30 | + | /// Abbreviated current commit hash. |
|
| 31 | + | pub(super) short: String, |
|
| 32 | + | /// First line of the current commit message. |
|
| 33 | + | pub(super) summary: String, |
|
| 34 | + | /// Accepted-hunk count for the current commit. |
|
| 35 | + | pub(super) accepted: usize, |
|
| 36 | + | /// Session-wide accepted-hunk visibility. |
|
| 37 | + | pub(super) visibility: Visibility, |
|
| 38 | + | } |
|
| 39 | + | ||
| 40 | + | impl Widget for Status { |
|
| 41 | + | fn size(&self, parent: Constraint) -> Size { |
|
| 42 | + | Size::new(parent.max.cols, FOOTER_ROWS).constrain(parent) |
|
| 43 | + | } |
|
| 44 | + | ||
| 45 | + | fn render(&mut self, area: Rect, buf: &mut Buffer) { |
|
| 46 | + | if area.is_empty() { |
|
| 47 | + | return; |
|
| 48 | + | } |
|
| 49 | + | Self::background(area.cols).render(area, buf); |
|
| 50 | + | self.bar().render(area, buf); |
|
| 51 | + | } |
|
| 52 | + | } |
|
| 53 | + | ||
| 54 | + | impl Status { |
|
| 55 | + | /// Returns the content and footer areas for a full session frame. |
|
| 56 | + | pub(super) fn areas(area: Rect) -> (Rect, Rect) { |
|
| 57 | + | area.split_bottom(FOOTER_ROWS) |
|
| 58 | + | } |
|
| 59 | + | ||
| 60 | + | /// Returns the full-width status row background. |
|
| 61 | + | fn background(cols: usize) -> Line { |
|
| 62 | + | Line::blank() |
|
| 63 | + | .style(Style::default().bg(FOOTER_BG)) |
|
| 64 | + | .padded(cols) |
|
| 65 | + | } |
|
| 66 | + | ||
| 67 | + | /// Returns the bottom status row content. |
|
| 68 | + | fn bar(&self) -> HStack<'_> { |
|
| 69 | + | let action = if self.visibility.show_accepted { |
|
| 70 | + | "hide approved" |
|
| 71 | + | } else { |
|
| 72 | + | "show approved" |
|
| 73 | + | }; |
|
| 74 | + | let (index, total) = self.position; |
|
| 75 | + | let left = format!("brain [{index}/{total}] {} {}", self.short, self.summary); |
|
| 76 | + | let mut right = format!("{} accepted \u{00b7} ", self.accepted); |
|
| 77 | + | if self.visibility.show_accepted { |
|
| 78 | + | right.push_str(APPROVED_HUNKS_MODE_ICON); |
|
| 79 | + | } |
|
| 80 | + | if self.visibility.full_file { |
|
| 81 | + | if self.visibility.show_accepted { |
|
| 82 | + | right.push(' '); |
|
| 83 | + | } |
|
| 84 | + | right.push_str(FULL_FILE_MODE_ICON); |
|
| 85 | + | } |
|
| 86 | + | if self.visibility.show_accepted || self.visibility.full_file { |
|
| 87 | + | right.push_str(" \u{00b7} "); |
|
| 88 | + | } |
|
| 89 | + | right.push_str("v "); |
|
| 90 | + | right.push_str(action); |
|
| 91 | + | HStack::default() |
|
| 92 | + | .child(Line::new(Label::new(&left).fg(FOOTER_FG))) |
|
| 93 | + | .spacer() |
|
| 94 | + | .child(Line::new(Label::new(&right).fg(FOOTER_FG))) |
|
| 95 | + | } |
|
| 96 | + | } |
|
| 97 | + | ||
| 98 | + | /// Returns the viewer area above the footer chrome. |
|
| 99 | + | pub(super) fn viewer_area(area: Rect) -> Rect { |
|
| 100 | + | Status::areas(area).0 |
|
| 101 | + | } |
|
| 102 | + | ||
| 103 | + | /// Returns a dim, full-width heading bar carrying `text`. |
|
| 104 | + | pub(super) fn heading(text: &str, cols: usize) -> Line { |
|
| 105 | + | Line::new(Label::new(text).fg(FOOTER_FG)) |
|
| 106 | + | .style(Style::default().bg(FOOTER_BG)) |
|
| 107 | + | .padded(cols) |
|
| 108 | + | .truncated(cols, "") |
|
| 109 | + | } |
|
| 110 | + | ||
| 111 | + | /// Renders one commit-list row: hash, summary, and diff statistics. |
|
| 112 | + | pub(super) fn commit_row(slot: &CommitSlot) -> Line { |
|
| 113 | + | let stats = slot.commit.stats; |
|
| 114 | + | let short = slot.commit.id.short(); |
|
| 115 | + | let status = if slot.reviewed { |
|
| 116 | + | Label::from_char(REVIEWED_MARK).fg(Color::Green) |
|
| 117 | + | } else { |
|
| 118 | + | Label::space() |
|
| 119 | + | }; |
|
| 120 | + | Line::spaced([ |
|
| 121 | + | status, |
|
| 122 | + | Label::new(&short).fg(Color::Yellow), |
|
| 123 | + | Label::new(&slot.commit.summary), |
|
| 124 | + | Label::new(&format!("+{}", stats.insertions)).fg(Color::Green), |
|
| 125 | + | Label::new(&format!("-{}", stats.deletions)).fg(Color::Red), |
|
| 126 | + | Label::new(&format!("{} files", stats.files_changed)).fg(FOOTER_FG), |
|
| 127 | + | ]) |
|
| 128 | + | } |
|
| 129 | + | ||
| 130 | + | /// Renders a hunk's stored comments as styled lines for the hunk view. |
|
| 131 | + | pub(super) fn comment_block_lines(comments: &[Comment]) -> Vec<Line> { |
|
| 132 | + | let mut lines = Vec::new(); |
|
| 133 | + | for (index, comment) in comments.iter().enumerate() { |
|
| 134 | + | if index > 0 { |
|
| 135 | + | lines.push(Line::blank()); |
|
| 136 | + | } |
|
| 137 | + | for (row, body) in comment.body.split('\n').enumerate() { |
|
| 138 | + | let prefix = if row == 0 { COMMENT_PREFIX } else { " " }; |
|
| 139 | + | lines.push(Line::new(Label::new(&format!("{prefix} {body}")))); |
|
| 140 | + | } |
|
| 141 | + | } |
|
| 142 | + | lines |
|
| 143 | + | } |
|
| 144 | + | ||
| 145 | + | #[cfg(test)] |
|
| 146 | + | mod tests { |
|
| 147 | + | use super::*; |
|
| 148 | + | ||
| 149 | + | #[test] |
|
| 150 | + | fn viewer_area_reserves_footer() { |
|
| 151 | + | assert_eq!( |
|
| 152 | + | viewer_area(Rect::new(0, 0, 80, 20)), |
|
| 153 | + | Rect::new(0, 0, 80, 19) |
|
| 154 | + | ); |
|
| 155 | + | assert_eq!(viewer_area(Rect::new(0, 0, 80, 1)), Rect::new(0, 0, 80, 0)); |
|
| 156 | + | } |
|
| 157 | + | ||
| 158 | + | #[test] |
|
| 159 | + | fn status_areas_reserve_footer() { |
|
| 160 | + | assert_eq!( |
|
| 161 | + | Status::areas(Rect::new(0, 0, 80, 20)), |
|
| 162 | + | (Rect::new(0, 0, 80, 19), Rect::new(0, 19, 80, 1)) |
|
| 163 | + | ); |
|
| 164 | + | assert_eq!( |
|
| 165 | + | Status::areas(Rect::new(0, 0, 80, 1)), |
|
| 166 | + | (Rect::new(0, 0, 80, 0), Rect::new(0, 0, 80, 1)) |
|
| 167 | + | ); |
|
| 168 | + | } |
|
| 169 | + | } |
crates/repo/Cargo.toml
+3 -0
| 5 | 5 | homepage = "https://crates.io/crates/rustik-repo" |
|
| 6 | 6 | version.workspace = true |
|
| 7 | 7 | edition.workspace = true |
|
| 8 | 8 | license.workspace = true |
|
| 9 | 9 | ||
| 10 | + | [dependencies] |
|
| 11 | + | serde.workspace = true |
|
| 12 | + | ||
| 10 | 13 | [lints] |
|
| 11 | 14 | workspace = true |
crates/repo/src/git.rs
+9 -7
| 6 | 6 | use std::io::{self, Read as _, Write as _}; |
|
| 7 | 7 | use std::path::{Path, PathBuf}; |
|
| 8 | 8 | use std::process::{Command, Output, Stdio}; |
|
| 9 | 9 | use std::time::{SystemTime, UNIX_EPOCH}; |
|
| 10 | 10 | ||
| 11 | - | use self::refs::{Qualified, RefStr}; |
|
| 12 | - | use crate::{DiffRepository, DiffStat, Oid, PatchId, ReadRepository, RepoError, WriteRepository}; |
|
| 11 | + | use self::refs::Qualified; |
|
| 12 | + | use crate::{ |
|
| 13 | + | DiffRepository, DiffStat, Oid, PatchId, ReadRepository, RepoError, Rev, WriteRepository, |
|
| 14 | + | }; |
|
| 13 | 15 | ||
| 14 | 16 | /// Git reference names and refspecs. |
|
| 15 | 17 | pub mod refs; |
|
| 16 | 18 | ||
| 17 | 19 | /// Environment variable that disables Git's colored output. |
| 196 | 198 | } |
|
| 197 | 199 | } |
|
| 198 | 200 | ||
| 199 | 201 | impl ReadRepository for Repository { |
|
| 200 | 202 | /// Resolves a revision reference to a commit id. |
|
| 201 | - | fn commit_id(&self, rev: &RefStr) -> Result<Oid, RepoError> { |
|
| 202 | - | let revision = format!("{rev}^{{commit}}"); |
|
| 203 | + | fn commit_id(&self, rev: &Rev) -> Result<Oid, RepoError> { |
|
| 204 | + | let revision = format!("{}^{{commit}}", rev.as_str()); |
|
| 203 | 205 | let bytes = self.git("rev-parse", &[&revision])?; |
|
| 204 | 206 | Oid::try_from(bytes.as_slice()) |
|
| 205 | - | .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {rev}"))) |
|
| 207 | + | .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {}", rev.as_str()))) |
|
| 206 | 208 | } |
|
| 207 | 209 | ||
| 208 | 210 | /// Returns the tree id for any commit or tree object. |
|
| 209 | 211 | fn tree_id(&self, object: Oid) -> Result<Oid, RepoError> { |
|
| 210 | 212 | let object = format!("{object}^{{tree}}"); |
| 356 | 358 | Err(RepoError::Git(message)) |
|
| 357 | 359 | } |
|
| 358 | 360 | } |
|
| 359 | 361 | ||
| 360 | 362 | /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs. |
|
| 361 | - | fn commits(&self, base: &RefStr, target: &RefStr) -> Result<Vec<(Oid, String)>, RepoError> { |
|
| 362 | - | let range = format!("{base}..{target}"); |
|
| 363 | + | fn commits(&self, base: &Rev, target: &Rev) -> Result<Vec<(Oid, String)>, RepoError> { |
|
| 364 | + | let range = format!("{}..{}", base.as_str(), target.as_str()); |
|
| 363 | 365 | let bytes = self.git("log", &["--reverse", "--format=%H%x00%s", &range])?; |
|
| 364 | 366 | let text = utf8(bytes)?; |
|
| 365 | 367 | let mut commits = Vec::new(); |
|
| 366 | 368 | ||
| 367 | 369 | for line in text.lines() { |
crates/repo/src/jj.rs
+4 -5
| 1 | 1 | //! Jujutsu plumbing handle for reading workspace state. |
|
| 2 | 2 | ||
| 3 | 3 | use std::path::PathBuf; |
|
| 4 | 4 | use std::process::Command; |
|
| 5 | 5 | ||
| 6 | - | use crate::git::refs::RefStr; |
|
| 7 | - | use crate::{Oid, RepoError, git}; |
|
| 6 | + | use crate::{Oid, RepoError, Rev, git}; |
|
| 8 | 7 | ||
| 9 | 8 | /// Jujutsu repository command context. |
|
| 10 | 9 | #[derive(Clone, Debug)] |
|
| 11 | 10 | pub struct Repository { |
|
| 12 | 11 | /// Workspace directory used for `jj` invocations. |
| 18 | 17 | pub fn new(cwd: impl Into<PathBuf>) -> Self { |
|
| 19 | 18 | Self { cwd: cwd.into() } |
|
| 20 | 19 | } |
|
| 21 | 20 | ||
| 22 | 21 | /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs. |
|
| 23 | - | pub fn commits(&self, base: &RefStr, target: &RefStr) -> Result<Vec<(Oid, String)>, RepoError> { |
|
| 24 | - | let revset = format!("{base}..{target}"); |
|
| 22 | + | pub fn commits(&self, base: &Rev, target: &Rev) -> Result<Vec<(Oid, String)>, RepoError> { |
|
| 23 | + | let revset = format!("{}..{}", base.as_str(), target.as_str()); |
|
| 25 | 24 | let stdout = self.jj_bytes(&[ |
|
| 26 | 25 | "log", |
|
| 27 | 26 | "--no-graph", |
|
| 28 | 27 | "--reverse", |
|
| 29 | 28 | "-r", |
| 58 | 57 | let root = self.git_root()?; |
|
| 59 | 58 | Ok(git::Repository::from_git_dir(self.cwd.clone(), root)) |
|
| 60 | 59 | } |
|
| 61 | 60 | ||
| 62 | 61 | /// Resolves `revision` to a full commit hash. |
|
| 63 | - | pub fn resolve(&self, revision: &RefStr) -> Result<Oid, RepoError> { |
|
| 62 | + | pub fn resolve(&self, revision: &Rev) -> Result<Oid, RepoError> { |
|
| 64 | 63 | let text = self.jj_text(&[ |
|
| 65 | 64 | "log", |
|
| 66 | 65 | "--no-graph", |
|
| 67 | 66 | "-r", |
|
| 68 | 67 | revision.as_str(), |
crates/repo/src/lib.rs
+65 -4
| 5 | 5 | ||
| 6 | 6 | #![deny(unsafe_code)] |
|
| 7 | 7 | #![warn(missing_docs)] |
|
| 8 | 8 | #![warn(clippy::unwrap_used)] |
|
| 9 | 9 | ||
| 10 | + | // `serde` is the local alias for the `microserde` crate; the derive macro |
|
| 11 | + | // emits `microserde::*` paths so the original crate name must remain in scope. |
|
| 12 | + | extern crate serde as microserde; |
|
| 13 | + | ||
| 10 | 14 | pub mod git; |
|
| 11 | 15 | pub mod jj; |
|
| 12 | 16 | pub mod oid; |
|
| 13 | 17 | ||
| 14 | 18 | pub use oid::{Oid, OidError}; |
|
| 15 | 19 | ||
| 20 | + | use std::convert::Infallible; |
|
| 16 | 21 | use std::fmt; |
|
| 17 | 22 | use std::io; |
|
| 18 | 23 | use std::path::Path; |
|
| 19 | 24 | use std::process::Output; |
|
| 25 | + | use std::str::FromStr; |
|
| 20 | 26 | ||
| 21 | - | use git::refs::{Qualified, RefStr}; |
|
| 27 | + | use git::refs::Qualified; |
|
| 28 | + | use serde::{Deserialize, Serialize}; |
|
| 22 | 29 | ||
| 23 | 30 | /// Stable patch identifier returned by `git patch-id`. |
|
| 24 | - | #[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] |
|
| 31 | + | #[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] |
|
| 32 | + | #[serde(transparent)] |
|
| 25 | 33 | pub struct PatchId(String); |
|
| 26 | 34 | ||
| 27 | 35 | impl PatchId { |
|
| 28 | 36 | /// Returns the patch identifier text. |
|
| 29 | 37 | pub fn as_str(&self) -> &str { |
|
| 30 | 38 | &self.0 |
|
| 31 | 39 | } |
|
| 32 | 40 | } |
|
| 33 | 41 | ||
| 42 | + | impl From<String> for PatchId { |
|
| 43 | + | fn from(value: String) -> Self { |
|
| 44 | + | Self(value) |
|
| 45 | + | } |
|
| 46 | + | } |
|
| 47 | + | ||
| 48 | + | impl FromStr for PatchId { |
|
| 49 | + | type Err = Infallible; |
|
| 50 | + | ||
| 51 | + | fn from_str(input: &str) -> Result<Self, Self::Err> { |
|
| 52 | + | Ok(Self(input.to_owned())) |
|
| 53 | + | } |
|
| 54 | + | } |
|
| 55 | + | ||
| 34 | 56 | impl fmt::Display for PatchId { |
|
| 35 | 57 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
|
| 36 | 58 | f.write_str(&self.0) |
|
| 37 | 59 | } |
|
| 38 | 60 | } |
| 73 | 95 | } |
|
| 74 | 96 | stat |
|
| 75 | 97 | } |
|
| 76 | 98 | } |
|
| 77 | 99 | ||
| 100 | + | /// User-supplied Git revision or Jujutsu revset selector. |
|
| 101 | + | #[derive(Clone, Debug, Eq, PartialEq)] |
|
| 102 | + | pub struct Rev(String); |
|
| 103 | + | ||
| 104 | + | impl Rev { |
|
| 105 | + | /// Returns the selector text. |
|
| 106 | + | pub fn as_str(&self) -> &str { |
|
| 107 | + | &self.0 |
|
| 108 | + | } |
|
| 109 | + | } |
|
| 110 | + | ||
| 111 | + | impl TryFrom<&str> for Rev { |
|
| 112 | + | type Error = &'static str; |
|
| 113 | + | ||
| 114 | + | fn try_from(value: &str) -> Result<Self, Self::Error> { |
|
| 115 | + | if value.is_empty() { |
|
| 116 | + | return Err("must not be empty"); |
|
| 117 | + | } |
|
| 118 | + | if value.starts_with('-') { |
|
| 119 | + | return Err("must not start with '-'"); |
|
| 120 | + | } |
|
| 121 | + | Ok(Self(value.to_owned())) |
|
| 122 | + | } |
|
| 123 | + | } |
|
| 124 | + | ||
| 78 | 125 | /// Repository operations that read commits, objects, refs, and derived data. |
|
| 79 | 126 | pub trait ReadRepository { |
|
| 80 | 127 | /// Resolves a revision reference to a commit id. |
|
| 81 | - | fn commit_id(&self, rev: &RefStr) -> Result<Oid, RepoError>; |
|
| 128 | + | fn commit_id(&self, rev: &Rev) -> Result<Oid, RepoError>; |
|
| 82 | 129 | ||
| 83 | 130 | /// Returns the tree id for any commit or tree object. |
|
| 84 | 131 | fn tree_id(&self, object: Oid) -> Result<Oid, RepoError>; |
|
| 85 | 132 | ||
| 86 | 133 | /// Returns the current commit stored in `reference`, if the ref exists. |
| 106 | 153 | ||
| 107 | 154 | /// Computes a three-way merge tree and returns the resulting tree id. |
|
| 108 | 155 | fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result<Oid, RepoError>; |
|
| 109 | 156 | ||
| 110 | 157 | /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs. |
|
| 111 | - | fn commits(&self, base: &RefStr, target: &RefStr) -> Result<Vec<(Oid, String)>, RepoError>; |
|
| 158 | + | fn commits(&self, base: &Rev, target: &Rev) -> Result<Vec<(Oid, String)>, RepoError>; |
|
| 112 | 159 | ||
| 113 | 160 | /// Returns the unified diff for `commit` against its parent. |
|
| 114 | 161 | fn commit_diff(&self, commit: Oid) -> Result<Vec<u8>, RepoError>; |
|
| 115 | 162 | } |
|
| 116 | 163 |
| 208 | 255 | deletions: 0 |
|
| 209 | 256 | } |
|
| 210 | 257 | ); |
|
| 211 | 258 | assert_eq!(DiffStat::from_shortstat("nonsense"), DiffStat::default()); |
|
| 212 | 259 | } |
|
| 260 | + | ||
| 261 | + | #[test] |
|
| 262 | + | fn rev_accepts_revision_syntax() { |
|
| 263 | + | assert_eq!(Rev::try_from("HEAD~3").unwrap().as_str(), "HEAD~3"); |
|
| 264 | + | assert_eq!(Rev::try_from("main^").unwrap().as_str(), "main^"); |
|
| 265 | + | assert_eq!(Rev::try_from("@").unwrap().as_str(), "@"); |
|
| 266 | + | assert_eq!(Rev::try_from("trunk()").unwrap().as_str(), "trunk()"); |
|
| 267 | + | } |
|
| 268 | + | ||
| 269 | + | #[test] |
|
| 270 | + | fn rev_rejects_option_like_selectors() { |
|
| 271 | + | assert!(Rev::try_from("").is_err()); |
|
| 272 | + | assert!(Rev::try_from("--help").is_err()); |
|
| 273 | + | } |
|
| 213 | 274 | } |
crates/repo/src/oid.rs
+33 -0
| 1 | 1 | //! Object identifier parsing and formatting. |
|
| 2 | 2 | ||
| 3 | 3 | use std::str::FromStr; |
|
| 4 | 4 | use std::{fmt, str}; |
|
| 5 | 5 | ||
| 6 | + | use serde::de::{Deserialize, Scalar, Visitor}; |
|
| 7 | + | use serde::ser::{Fragment, Serialize}; |
|
| 8 | + | ||
| 6 | 9 | /// Number of bytes in a SHA-1 object digest. |
|
| 7 | 10 | const SHA1_LEN: usize = 20; |
|
| 8 | 11 | /// Number of bytes in a SHA-256 object digest. |
|
| 9 | 12 | const SHA256_LEN: usize = 32; |
|
| 10 | 13 | /// Number of leading hash characters shown as an abbreviated object id. |
| 44 | 47 | _ => Err(OidError), |
|
| 45 | 48 | } |
|
| 46 | 49 | } |
|
| 47 | 50 | } |
|
| 48 | 51 | ||
| 52 | + | impl Serialize for Oid { |
|
| 53 | + | fn begin(&self) -> Fragment<'_> { |
|
| 54 | + | Fragment::Str(self.to_string().into()) |
|
| 55 | + | } |
|
| 56 | + | } |
|
| 57 | + | ||
| 58 | + | /// Visitor that parses an object identifier from its hexadecimal string form. |
|
| 59 | + | pub struct OidVisitor<'a> { |
|
| 60 | + | /// Output slot the parsed object identifier is written into. |
|
| 61 | + | out: &'a mut Option<Oid>, |
|
| 62 | + | } |
|
| 63 | + | ||
| 64 | + | impl Visitor for OidVisitor<'_> { |
|
| 65 | + | fn scalar(&mut self, s: &Scalar) -> serde::Result<()> { |
|
| 66 | + | let Scalar::Str(value) = s else { |
|
| 67 | + | return Err(serde::Error); |
|
| 68 | + | }; |
|
| 69 | + | *self.out = Some(value.parse().map_err(|_| serde::Error)?); |
|
| 70 | + | Ok(()) |
|
| 71 | + | } |
|
| 72 | + | } |
|
| 73 | + | ||
| 74 | + | impl Deserialize for Oid { |
|
| 75 | + | type Visitor<'a> = OidVisitor<'a>; |
|
| 76 | + | ||
| 77 | + | fn begin(out: &mut Option<Self>) -> Self::Visitor<'_> { |
|
| 78 | + | OidVisitor { out } |
|
| 79 | + | } |
|
| 80 | + | } |
|
| 81 | + | ||
| 49 | 82 | impl TryFrom<&[u8]> for Oid { |
|
| 50 | 83 | type Error = OidError; |
|
| 51 | 84 | ||
| 52 | 85 | fn try_from(input: &[u8]) -> Result<Self, Self::Error> { |
|
| 53 | 86 | let input = str::from_utf8(input).map_err(|_| OidError)?; |
crates/tui-core/src/frame.rs
+52 -1
| 2 | 2 | //! |
|
| 3 | 3 | //! A frame exposes the current drawing area and mutable buffer for one render |
|
| 4 | 4 | //! pass. Applications render widgets into this frame; terminal diffing and |
|
| 5 | 5 | //! backend flushing happen after the frame is complete. |
|
| 6 | 6 | ||
| 7 | - | use crate::Widget; |
|
| 8 | 7 | use crate::buffer::Buffer; |
|
| 9 | 8 | use crate::layout::{Point, Rect}; |
|
| 9 | + | use crate::{StatefulWidget, Widget}; |
|
| 10 | 10 | ||
| 11 | 11 | /// Frame passed to application render methods. |
|
| 12 | 12 | #[derive(Debug)] |
|
| 13 | 13 | pub struct Frame<'a> { |
|
| 14 | 14 | /// Area available for this frame. |
| 32 | 32 | /// Renders a widget into an area. |
|
| 33 | 33 | pub fn render_widget<W: Widget>(&mut self, mut widget: W, area: Rect) { |
|
| 34 | 34 | widget.render(area, self.buffer); |
|
| 35 | 35 | } |
|
| 36 | 36 | ||
| 37 | + | /// Renders a stateful widget into an area. |
|
| 38 | + | pub fn render_stateful_widget<W: StatefulWidget>( |
|
| 39 | + | &mut self, |
|
| 40 | + | mut widget: W, |
|
| 41 | + | area: Rect, |
|
| 42 | + | state: &mut W::State, |
|
| 43 | + | ) { |
|
| 44 | + | let result = widget.render_with_state(area, self.buffer, state); |
|
| 45 | + | ||
| 46 | + | if let Some(point) = result.cursor { |
|
| 47 | + | self.set_cursor_position(point); |
|
| 48 | + | } |
|
| 49 | + | } |
|
| 50 | + | ||
| 37 | 51 | /// Sets the terminal cursor. |
|
| 38 | 52 | pub fn set_cursor_position(&mut self, point: Point) { |
|
| 39 | 53 | self.cursor = Some(point); |
|
| 40 | 54 | } |
|
| 41 | 55 | } |
| 51 | 65 | struct LayoutProbe { |
|
| 52 | 66 | laid_out: Cell<bool>, |
|
| 53 | 67 | area: Cell<Rect>, |
|
| 54 | 68 | } |
|
| 55 | 69 | ||
| 70 | + | #[derive(Debug)] |
|
| 71 | + | struct CursorProbe; |
|
| 72 | + | ||
| 56 | 73 | impl Default for LayoutProbe { |
|
| 57 | 74 | fn default() -> Self { |
|
| 58 | 75 | Self { |
|
| 59 | 76 | laid_out: Cell::new(false), |
|
| 60 | 77 | area: Cell::new(Rect::default()), |
| 72 | 89 | self.area.set(area); |
|
| 73 | 90 | buf.set_str(area.x, area.y, "R", Style::default()); |
|
| 74 | 91 | } |
|
| 75 | 92 | } |
|
| 76 | 93 | ||
| 94 | + | impl StatefulWidget for CursorProbe { |
|
| 95 | + | type State = Point; |
|
| 96 | + | ||
| 97 | + | fn size(&self, parent: Constraint) -> Size { |
|
| 98 | + | parent.bounded_size() |
|
| 99 | + | } |
|
| 100 | + | ||
| 101 | + | fn render_with_state( |
|
| 102 | + | &mut self, |
|
| 103 | + | area: Rect, |
|
| 104 | + | buf: &mut Buffer, |
|
| 105 | + | state: &mut Self::State, |
|
| 106 | + | ) -> crate::RenderResult { |
|
| 107 | + | buf.set_str(area.x, area.y, "C", Style::default()); |
|
| 108 | + | *state = Point::new(area.x, area.y); |
|
| 109 | + | crate::RenderResult { |
|
| 110 | + | cursor: Some(*state), |
|
| 111 | + | } |
|
| 112 | + | } |
|
| 113 | + | } |
|
| 114 | + | ||
| 77 | 115 | #[test] |
|
| 78 | 116 | fn render_widget_renders_into_area() { |
|
| 79 | 117 | let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 2)); |
|
| 80 | 118 | let area = Rect::new(1, 1, 2, 1); |
|
| 81 | 119 | let mut frame = Frame::new(buffer.area(), &mut buffer); |
|
| 82 | 120 | ||
| 83 | 121 | frame.render_widget(LayoutProbe::default(), area); |
|
| 84 | 122 | ||
| 85 | 123 | assert_eq!(buffer.lines(), vec![" ", " R "]); |
|
| 86 | 124 | } |
|
| 125 | + | ||
| 126 | + | #[test] |
|
| 127 | + | fn render_stateful_widget_sets_requested_cursor() { |
|
| 128 | + | let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 2)); |
|
| 129 | + | let area = Rect::new(1, 1, 2, 1); |
|
| 130 | + | let mut state = Point::new(0, 0); |
|
| 131 | + | let mut frame = Frame::new(buffer.area(), &mut buffer); |
|
| 132 | + | ||
| 133 | + | frame.render_stateful_widget(CursorProbe, area, &mut state); |
|
| 134 | + | ||
| 135 | + | assert_eq!(frame.cursor, Some(Point::new(1, 1))); |
|
| 136 | + | assert_eq!(buffer.lines(), vec![" ", " C "]); |
|
| 137 | + | } |
|
| 87 | 138 | } |
crates/tui-core/src/layout.rs
+46 -0
| 138 | 138 | self.rows - inset, |
|
| 139 | 139 | ) |
|
| 140 | 140 | } |
|
| 141 | 141 | } |
|
| 142 | 142 | ||
| 143 | + | /// Splits this rectangle into top rows and the remaining rows. |
|
| 144 | + | pub const fn split_top(self, rows: usize) -> (Self, Self) { |
|
| 145 | + | let rows = if rows > self.rows { self.rows } else { rows }; |
|
| 146 | + | ( |
|
| 147 | + | Self::new(self.x, self.y, self.cols, rows), |
|
| 148 | + | Self::new(self.x, self.y + rows, self.cols, self.rows - rows), |
|
| 149 | + | ) |
|
| 150 | + | } |
|
| 151 | + | ||
| 152 | + | /// Splits this rectangle into remaining rows and bottom rows. |
|
| 153 | + | pub const fn split_bottom(self, rows: usize) -> (Self, Self) { |
|
| 154 | + | let rows = if rows > self.rows { self.rows } else { rows }; |
|
| 155 | + | ( |
|
| 156 | + | Self::new(self.x, self.y, self.cols, self.rows - rows), |
|
| 157 | + | Self::new(self.x, self.bottom() - rows, self.cols, rows), |
|
| 158 | + | ) |
|
| 159 | + | } |
|
| 160 | + | ||
| 143 | 161 | /// Returns the intersection of two rectangles. |
|
| 144 | 162 | pub fn intersection(self, other: Self) -> Self { |
|
| 145 | 163 | let x = self.x.max(other.x); |
|
| 146 | 164 | let y = self.y.max(other.y); |
|
| 147 | 165 | let right = self.right().min(other.right()); |
| 295 | 313 | assert_eq!(rect.inner(1), Rect::new(3, 4, 8, 6)); |
|
| 296 | 314 | assert!(rect.contains(Point::new(2, 3))); |
|
| 297 | 315 | assert!(!rect.contains(Point::new(12, 3))); |
|
| 298 | 316 | } |
|
| 299 | 317 | ||
| 318 | + | #[test] |
|
| 319 | + | fn rect_split_top_clamps_to_available_rows() { |
|
| 320 | + | let rect: Rect = Rect::new(2, 3, 10, 8); |
|
| 321 | + | ||
| 322 | + | assert_eq!( |
|
| 323 | + | rect.split_top(3), |
|
| 324 | + | (Rect::new(2, 3, 10, 3), Rect::new(2, 6, 10, 5)) |
|
| 325 | + | ); |
|
| 326 | + | assert_eq!( |
|
| 327 | + | rect.split_top(10), |
|
| 328 | + | (Rect::new(2, 3, 10, 8), Rect::new(2, 11, 10, 0)) |
|
| 329 | + | ); |
|
| 330 | + | } |
|
| 331 | + | ||
| 332 | + | #[test] |
|
| 333 | + | fn rect_split_bottom_clamps_to_available_rows() { |
|
| 334 | + | let rect: Rect = Rect::new(2, 3, 10, 8); |
|
| 335 | + | ||
| 336 | + | assert_eq!( |
|
| 337 | + | rect.split_bottom(3), |
|
| 338 | + | (Rect::new(2, 3, 10, 5), Rect::new(2, 8, 10, 3)) |
|
| 339 | + | ); |
|
| 340 | + | assert_eq!( |
|
| 341 | + | rect.split_bottom(10), |
|
| 342 | + | (Rect::new(2, 3, 10, 0), Rect::new(2, 3, 10, 8)) |
|
| 343 | + | ); |
|
| 344 | + | } |
|
| 345 | + | ||
| 300 | 346 | #[test] |
|
| 301 | 347 | fn horizontal_split_distributes_fill() { |
|
| 302 | 348 | let area: Rect = Rect::new(0, 0, 10, 3); |
|
| 303 | 349 | let layout = Layout::new(Direction::Horizontal) |
|
| 304 | 350 | .child(Length::Fixed(2)) |
crates/tui-core/src/lib.rs
+1 -1
| 72 | 72 | pub use primitive::{Constraint, Line, Size, StyledLine}; |
|
| 73 | 73 | pub use table::{Table, TableOptions}; |
|
| 74 | 74 | pub use terminal::Terminal; |
|
| 75 | 75 | pub use textarea::{TextArea, textarea}; |
|
| 76 | 76 | pub use vstack::{VStack, VStackOptions}; |
|
| 77 | - | pub use widget::{Block, Clear, Fill, StatefulWidget, Widget}; |
|
| 77 | + | pub use widget::{Block, Clear, Fill, RenderResult, StatefulWidget, Widget}; |
crates/tui-core/src/widget.rs
+40 -4
| 8 | 8 | use std::fmt; |
|
| 9 | 9 | use std::fmt::Write as _; |
|
| 10 | 10 | use std::ops::{Deref, DerefMut}; |
|
| 11 | 11 | ||
| 12 | 12 | use crate::layout::Rect; |
|
| 13 | - | use crate::{Border, Buffer, Cell, Color, Constraint, Line, Paint, Size, Style}; |
|
| 13 | + | use crate::{Border, Buffer, Cell, Color, Constraint, Line, Paint, Point, Size, Style}; |
|
| 14 | 14 | ||
| 15 | 15 | /// Something that can render into a [`Buffer`]. |
|
| 16 | 16 | pub trait Widget: fmt::Debug + Send { |
|
| 17 | 17 | /// Returns the widget size under a parent constraint. |
|
| 18 | 18 | fn size(&self, parent: Constraint) -> Size; |
| 105 | 105 | ||
| 106 | 106 | /// Returns the widget size under a parent constraint. |
|
| 107 | 107 | fn size(&self, parent: Constraint) -> Size; |
|
| 108 | 108 | ||
| 109 | 109 | /// Renders the widget into an area with caller-owned state. |
|
| 110 | - | fn render_with_state(&mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State); |
|
| 110 | + | fn render_with_state( |
|
| 111 | + | &mut self, |
|
| 112 | + | area: Rect, |
|
| 113 | + | buf: &mut Buffer, |
|
| 114 | + | state: &mut Self::State, |
|
| 115 | + | ) -> RenderResult; |
|
| 116 | + | } |
|
| 117 | + | ||
| 118 | + | /// Result produced by one stateful widget render pass. |
|
| 119 | + | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
|
| 120 | + | pub struct RenderResult { |
|
| 121 | + | /// Requested terminal cursor position after rendering. |
|
| 122 | + | pub cursor: Option<Point>, |
|
| 111 | 123 | } |
|
| 112 | 124 | ||
| 113 | 125 | impl Widget for Box<dyn Widget + '_> { |
|
| 114 | 126 | fn size(&self, parent: Constraint) -> Size { |
|
| 115 | 127 | self.deref().size(parent) |
| 128 | 140 | fn render(&mut self, area: Rect, buf: &mut Buffer) { |
|
| 129 | 141 | (**self).render(area, buf); |
|
| 130 | 142 | } |
|
| 131 | 143 | } |
|
| 132 | 144 | ||
| 145 | + | impl<T: StatefulWidget + ?Sized> StatefulWidget for &mut T { |
|
| 146 | + | type State = T::State; |
|
| 147 | + | ||
| 148 | + | fn size(&self, parent: Constraint) -> Size { |
|
| 149 | + | (**self).size(parent) |
|
| 150 | + | } |
|
| 151 | + | ||
| 152 | + | fn render_with_state( |
|
| 153 | + | &mut self, |
|
| 154 | + | area: Rect, |
|
| 155 | + | buf: &mut Buffer, |
|
| 156 | + | state: &mut Self::State, |
|
| 157 | + | ) -> RenderResult { |
|
| 158 | + | (**self).render_with_state(area, buf, state) |
|
| 159 | + | } |
|
| 160 | + | } |
|
| 161 | + | ||
| 133 | 162 | /// Clears an area. |
|
| 134 | 163 | #[derive(Debug, Clone, Copy, Default)] |
|
| 135 | 164 | pub struct Clear; |
|
| 136 | 165 | ||
| 137 | 166 | impl Widget for Clear { |
| 259 | 288 | ||
| 260 | 289 | fn size(&self, parent: Constraint) -> Size { |
|
| 261 | 290 | self.outer_size(self.child.size(parent), parent) |
|
| 262 | 291 | } |
|
| 263 | 292 | ||
| 264 | - | fn render_with_state(&mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { |
|
| 293 | + | fn render_with_state( |
|
| 294 | + | &mut self, |
|
| 295 | + | area: Rect, |
|
| 296 | + | buf: &mut Buffer, |
|
| 297 | + | state: &mut Self::State, |
|
| 298 | + | ) -> RenderResult { |
|
| 265 | 299 | if let Some(inner) = self.frame(area, buf) { |
|
| 266 | - | self.child.render_with_state(inner, buf, state); |
|
| 300 | + | self.child.render_with_state(inner, buf, state) |
|
| 301 | + | } else { |
|
| 302 | + | RenderResult::default() |
|
| 267 | 303 | } |
|
| 268 | 304 | } |
|
| 269 | 305 | } |
|
| 270 | 306 | ||
| 271 | 307 | impl From<Paint<String>> for Fill { |
crates/tui-widgets/src/input.rs
+14 -4
| 7 | 7 | //! |
|
| 8 | 8 | //! Columns are measured in characters, so caret placement assumes single-width glyphs; wide |
|
| 9 | 9 | //! characters shift the rendered caret by one cell each. |
|
| 10 | 10 | ||
| 11 | 11 | use rustik_tui_core as tui_core; |
|
| 12 | - | use tui_core::{Buffer, Constraint, Key, Point, Rect, Size, StatefulWidget, Style}; |
|
| 12 | + | use tui_core::{Buffer, Constraint, Key, Point, Rect, RenderResult, Size, StatefulWidget, Style}; |
|
| 13 | 13 | ||
| 14 | 14 | /// Editable text buffer with a caret and viewport offsets. |
|
| 15 | 15 | #[derive(Clone, Debug)] |
|
| 16 | 16 | pub struct TextInput { |
|
| 17 | 17 | /// Edited text, with `\n` separating logical lines. |
| 282 | 282 | ||
| 283 | 283 | fn size(&self, parent: Constraint) -> Size { |
|
| 284 | 284 | parent.bounded_size() |
|
| 285 | 285 | } |
|
| 286 | 286 | ||
| 287 | - | fn render_with_state(&mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { |
|
| 287 | + | fn render_with_state( |
|
| 288 | + | &mut self, |
|
| 289 | + | area: Rect, |
|
| 290 | + | buf: &mut Buffer, |
|
| 291 | + | state: &mut Self::State, |
|
| 292 | + | ) -> RenderResult { |
|
| 288 | 293 | if area.is_empty() { |
|
| 289 | - | return; |
|
| 294 | + | return RenderResult::default(); |
|
| 290 | 295 | } |
|
| 291 | 296 | if state.value.is_empty() { |
|
| 292 | 297 | if let Some(placeholder) = &self.placeholder { |
|
| 293 | 298 | let text: String = placeholder.chars().take(area.cols).collect(); |
|
| 294 | 299 | buf.set_str(area.x, area.y, &text, self.placeholder_style); |
|
| 295 | 300 | } |
|
| 296 | 301 | state.scroll = 0; |
|
| 297 | 302 | state.hscroll = 0; |
|
| 298 | 303 | state.caret = Point::new(area.x, area.y); |
|
| 299 | - | return; |
|
| 304 | + | return RenderResult { |
|
| 305 | + | cursor: Some(state.caret()), |
|
| 306 | + | }; |
|
| 300 | 307 | } |
|
| 301 | 308 | let (row, col) = state.row_col(); |
|
| 302 | 309 | if row < state.scroll { |
|
| 303 | 310 | state.scroll = row; |
|
| 304 | 311 | } else if row >= state.scroll + area.rows { |
| 326 | 333 | } |
|
| 327 | 334 | state.caret = Point::new( |
|
| 328 | 335 | area.x + col.saturating_sub(state.hscroll), |
|
| 329 | 336 | area.y + row.saturating_sub(state.scroll), |
|
| 330 | 337 | ); |
|
| 338 | + | RenderResult { |
|
| 339 | + | cursor: Some(state.caret()), |
|
| 340 | + | } |
|
| 331 | 341 | } |
|
| 332 | 342 | } |
|
| 333 | 343 | ||
| 334 | 344 | #[cfg(test)] |
|
| 335 | 345 | mod tests { |
crates/tui-widgets/src/list.rs
+11 -3
| 6 | 6 | //! [`ListState`] combines selection with a persistent viewport for lists that |
|
| 7 | 7 | //! need manual scrolling to survive redraws. |
|
| 8 | 8 | ||
| 9 | 9 | use crate::{Placement, Scroll, ScrollView, ScrollbarStyle, View, Viewport}; |
|
| 10 | 10 | use rustik_tui_core as tui_core; |
|
| 11 | - | use tui_core::{Buffer, Color, Constraint, Line, Rect, Size, StatefulWidget, Style, Widget}; |
|
| 11 | + | use tui_core::{ |
|
| 12 | + | Buffer, Color, Constraint, Line, Rect, RenderResult, Size, StatefulWidget, Style, Widget, |
|
| 13 | + | }; |
|
| 12 | 14 | ||
| 13 | 15 | /// Default selected-row style for an active list. |
|
| 14 | 16 | pub const DEFAULT_SELECTED_STYLE_ACTIVE: Style = Style::new(Color::Unset).bg(Color::Blue); |
|
| 15 | 17 | /// Default selected-row style for an inactive list. |
|
| 16 | 18 | pub const DEFAULT_SELECTED_STYLE_INACTIVE: Style = Style::new(Color::Unset).bg(Color::Fixed(238)); |
| 308 | 310 | ||
| 309 | 311 | fn size(&self, parent: Constraint) -> Size { |
|
| 310 | 312 | Widget::size(self, parent) |
|
| 311 | 313 | } |
|
| 312 | 314 | ||
| 313 | - | fn render_with_state(&mut self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { |
|
| 315 | + | fn render_with_state( |
|
| 316 | + | &mut self, |
|
| 317 | + | area: Rect, |
|
| 318 | + | buf: &mut Buffer, |
|
| 319 | + | state: &mut Self::State, |
|
| 320 | + | ) -> RenderResult { |
|
| 314 | 321 | if area.is_empty() { |
|
| 315 | - | return; |
|
| 322 | + | return RenderResult::default(); |
|
| 316 | 323 | } |
|
| 317 | 324 | let view = state.view(self.lines.len(), area.rows, self.placement); |
|
| 318 | 325 | if let Some(mut scroll) = self.scroll_view(area, view, state.selected()) { |
|
| 319 | 326 | scroll.render(area, buf); |
|
| 320 | 327 | } else if let Some(line) = self.empty.clone() { |
|
| 321 | 328 | let x = area.x + 1.min(area.cols); |
|
| 322 | 329 | let y = area.y + 1.min(area.rows.saturating_sub(1)); |
|
| 323 | 330 | buf.set_line(x, y, &line.padded(area.right().saturating_sub(x))); |
|
| 324 | 331 | } |
|
| 332 | + | RenderResult::default() |
|
| 325 | 333 | } |
|
| 326 | 334 | } |
|
| 327 | 335 | ||
| 328 | 336 | #[cfg(test)] |
|
| 329 | 337 | mod tests { |