brain: Persist exact hunk acceptance
e09690ca12bfbfa3ec73a3dbcf12112290e6177e
Store accepted hunk identities in the synthetic state commit and derive review progress from that set. Keep the state tree as an ordered best-effort content projection so coincidental content and patch dependencies cannot change logical acceptance. Assisted-by: Codex:gpt-5
1 parent
f98127d9
crates/brain/src/backend.rs
+561 -234
| 8 | 8 | ||
| 9 | 9 | use std::cmp::Ordering; |
|
| 10 | 10 | use std::collections::{BTreeMap, BTreeSet}; |
|
| 11 | 11 | use std::ffi::OsString; |
|
| 12 | 12 | use std::path::Path; |
|
| 13 | + | use std::str::FromStr as _; |
|
| 13 | 14 | ||
| 14 | 15 | use rustik_diff::{Decode as _, DiffDocument, Encode as _, FileDiff, Hunk, HunkId, ReviewProgress}; |
|
| 15 | 16 | use rustik_repo::{ |
|
| 16 | 17 | AheadBehind, CommitTime, DiffStat, MergeStatus, Oid, PatchId, ReadRepository, Rev, |
|
| 17 | 18 | WriteRepository, |
| 26 | 27 | ||
| 27 | 28 | /// Directory marking a Jujutsu workspace. |
|
| 28 | 29 | const JJ_DIR: &str = ".jj"; |
|
| 29 | 30 | /// Commit message used for synthetic brain state commits. |
|
| 30 | 31 | const SYNTHETIC_BRAIN_MESSAGE: &str = "brain state"; |
|
| 32 | + | /// Commit-message section holding exact accepted-hunk state. |
|
| 33 | + | const ACCEPTED_SECTION: &str = "accepted-v1"; |
|
| 31 | 34 | /// Hidden Git ref category holding all review state. |
|
| 32 | 35 | const BRAIN_REF_CATEGORY: &str = "brain"; |
|
| 33 | 36 | /// Namespace under the brain category for acceptance state commits. |
|
| 34 | 37 | const STATE_REF_NAMESPACE: &str = "state"; |
|
| 35 | 38 | /// Namespace under the brain category for comment blobs. |
| 69 | 72 | .map(|((id, summary), stats)| Self { id, summary, stats }) |
|
| 70 | 73 | .collect()) |
|
| 71 | 74 | } |
|
| 72 | 75 | } |
|
| 73 | 76 | ||
| 74 | - | /// Hunk identity data for one commit during tree-state reconciliation. |
|
| 77 | + | /// Exact identity of one accepted hunk. |
|
| 78 | + | #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] |
|
| 79 | + | pub struct AcceptedHunk { |
|
| 80 | + | /// Commit containing the hunk. |
|
| 81 | + | pub commit: Oid, |
|
| 82 | + | /// Stable identity of the hunk's change. |
|
| 83 | + | pub patch_id: PatchId, |
|
| 84 | + | /// Occurrence of this patch id within the commit. |
|
| 85 | + | pub ordinal: u32, |
|
| 86 | + | /// Total number of hunks in the commit. |
|
| 87 | + | pub commit_hunks: u32, |
|
| 88 | + | } |
|
| 89 | + | ||
| 90 | + | impl AcceptedHunk { |
|
| 91 | + | /// Remaps stored identities onto identities in the current range. |
|
| 92 | + | /// |
|
| 93 | + | /// Matching runs in three passes, each consuming stored acceptances the |
|
| 94 | + | /// earlier passes left unmatched: |
|
| 95 | + | /// |
|
| 96 | + | /// 1. exact identity, for commits the move left untouched; |
|
| 97 | + | /// 2. same commit and patch id, for commits whose hunk count changed; |
|
| 98 | + | /// 3. patch id alone, which is what carries acceptance across a rebase, |
|
| 99 | + | /// since a rewritten commit has a new id. |
|
| 100 | + | /// |
|
| 101 | + | /// The last pass is deliberately fuzzy: a change that moved between |
|
| 102 | + | /// commits keeps its acceptance. Restricting it to the patch id keeps |
|
| 103 | + | /// unrelated content from inheriting acceptance, but two commits carrying |
|
| 104 | + | /// the identical change are indistinguishable here, so the earlier passes |
|
| 105 | + | /// exist to claim the unambiguous matches first. |
|
| 106 | + | fn remap<'a>( |
|
| 107 | + | stored: &Accepted, |
|
| 108 | + | current: impl IntoIterator<Item = &'a AcceptedHunk>, |
|
| 109 | + | ) -> Accepted { |
|
| 110 | + | let current = current.into_iter().cloned().collect::<Vec<_>>(); |
|
| 111 | + | let live = current.iter().collect::<BTreeSet<_>>(); |
|
| 112 | + | let mut accepted = Accepted::new(); |
|
| 113 | + | let mut remaining = Vec::new(); |
|
| 114 | + | for identity in stored { |
|
| 115 | + | if live.contains(identity) { |
|
| 116 | + | accepted.insert(identity.clone()); |
|
| 117 | + | } else { |
|
| 118 | + | remaining.push(identity.clone()); |
|
| 119 | + | } |
|
| 120 | + | } |
|
| 121 | + | Self::claim(&mut remaining, ¤t, &mut accepted, |identity| { |
|
| 122 | + | (identity.commit, identity.patch_id.clone()) |
|
| 123 | + | }); |
|
| 124 | + | Self::claim(&mut remaining, ¤t, &mut accepted, |identity| { |
|
| 125 | + | identity.patch_id.clone() |
|
| 126 | + | }); |
|
| 127 | + | ||
| 128 | + | accepted |
|
| 129 | + | } |
|
| 130 | + | ||
| 131 | + | /// Matches still-unaccepted current identities against `remaining` by `key`. |
|
| 132 | + | /// |
|
| 133 | + | /// Each stored acceptance grants one match for its key, consumed by current |
|
| 134 | + | /// identities in range order; consumed acceptances leave `remaining` so a |
|
| 135 | + | /// later, fuzzier pass cannot spend them a second time. |
|
| 136 | + | fn claim<K: Ord>( |
|
| 137 | + | remaining: &mut Vec<Self>, |
|
| 138 | + | current: &[Self], |
|
| 139 | + | accepted: &mut Accepted, |
|
| 140 | + | key: impl Fn(&Self) -> K, |
|
| 141 | + | ) { |
|
| 142 | + | let mut budget = BTreeMap::<K, Vec<usize>>::new(); |
|
| 143 | + | for (index, identity) in remaining.iter().enumerate() { |
|
| 144 | + | budget.entry(key(identity)).or_default().push(index); |
|
| 145 | + | } |
|
| 146 | + | let mut consumed = BTreeSet::new(); |
|
| 147 | + | for identity in current { |
|
| 148 | + | if accepted.contains(identity) { |
|
| 149 | + | continue; |
|
| 150 | + | } |
|
| 151 | + | let Some(index) = budget.get_mut(&key(identity)).and_then(Vec::pop) else { |
|
| 152 | + | continue; |
|
| 153 | + | }; |
|
| 154 | + | accepted.insert(identity.clone()); |
|
| 155 | + | consumed.insert(index); |
|
| 156 | + | } |
|
| 157 | + | let mut index = 0; |
|
| 158 | + | remaining.retain(|_| { |
|
| 159 | + | let keep = !consumed.contains(&index); |
|
| 160 | + | index += 1; |
|
| 161 | + | keep |
|
| 162 | + | }); |
|
| 163 | + | } |
|
| 164 | + | } |
|
| 165 | + | ||
| 166 | + | /// Authoritative accepted-hunk state for one review. |
|
| 167 | + | type Accepted = BTreeSet<AcceptedHunk>; |
|
| 168 | + | ||
| 169 | + | /// Accepted hunks of one file, ready to apply to the projected tree. |
|
| 170 | + | pub struct FilePatches { |
|
| 171 | + | /// Every hunk of the file in one patch. |
|
| 172 | + | pub combined: String, |
|
| 173 | + | /// The same hunks as individual patches, used when `combined` fails. |
|
| 174 | + | pub hunks: Vec<String>, |
|
| 175 | + | } |
|
| 176 | + | ||
| 177 | + | impl FilePatches { |
|
| 178 | + | /// Builds combined and per-hunk patches for `hunks` of `file`. |
|
| 179 | + | pub fn new(file: &FileDiff, hunks: Vec<Hunk>) -> Result<Self, Error> { |
|
| 180 | + | let individual = hunks |
|
| 181 | + | .iter() |
|
| 182 | + | .map(|hunk| DiffDocument::for_hunks(file, [hunk.clone()]).to_unified_string()) |
|
| 183 | + | .collect::<Result<Vec<_>, _>>()?; |
|
| 184 | + | ||
| 185 | + | Ok(Self { |
|
| 186 | + | combined: DiffDocument::for_hunks(file, hunks).to_unified_string()?, |
|
| 187 | + | hunks: individual, |
|
| 188 | + | }) |
|
| 189 | + | } |
|
| 190 | + | } |
|
| 191 | + | ||
| 192 | + | /// Hunk identity data for one commit during acceptance reconciliation. |
|
| 75 | 193 | pub struct CommitHunks<'a> { |
|
| 76 | 194 | /// Commit whose hunks are being reconciled. |
|
| 77 | - | pub commit: &'a Commit, |
|
| 78 | - | /// Stable patch id per decoded hunk, when the commit's diff is loaded. |
|
| 79 | - | pub hunks: Option<&'a BTreeMap<HunkId, PatchId>>, |
|
| 195 | + | pub commit: Oid, |
|
| 196 | + | /// Exact identity per decoded hunk, when the commit's diff is loaded. |
|
| 197 | + | pub hunks: Option<&'a BTreeMap<HunkId, AcceptedHunk>>, |
|
| 80 | 198 | } |
|
| 81 | 199 | ||
| 82 | - | /// Review state of one commit derived from the hidden tree. |
|
| 200 | + | /// Review state of one commit projected from the accepted set. |
|
| 83 | 201 | pub struct Reconciled { |
|
| 84 | - | /// Whether the commit's entire diff is contained in the accepted tree. |
|
| 202 | + | /// Whether every hunk in the commit is accepted. |
|
| 85 | 203 | pub reviewed: bool, |
|
| 86 | 204 | /// Accepted hunks, for commits whose hunk patch ids were supplied. |
|
| 87 | 205 | pub accepted: BTreeSet<HunkId>, |
|
| 88 | 206 | } |
|
| 89 | 207 | ||
| 208 | + | impl Reconciled { |
|
| 209 | + | /// Projects exact accepted identities onto commit-local hunk ids. |
|
| 210 | + | fn for_commits(accepted_state: &Accepted, commits: &[CommitHunks<'_>]) -> Vec<Self> { |
|
| 211 | + | // Accepted count and total hunk count per commit, so undecoded commits |
|
| 212 | + | // can be marked reviewed from persisted totals alone. |
|
| 213 | + | let mut totals = BTreeMap::<Oid, (usize, u32)>::new(); |
|
| 214 | + | for identity in accepted_state { |
|
| 215 | + | let entry = totals |
|
| 216 | + | .entry(identity.commit) |
|
| 217 | + | .or_insert((0, identity.commit_hunks)); |
|
| 218 | + | entry.0 += 1; |
|
| 219 | + | } |
|
| 220 | + | ||
| 221 | + | let mut reconciled = Vec::with_capacity(commits.len()); |
|
| 222 | + | for commit in commits { |
|
| 223 | + | let (reviewed, accepted) = match commit.hunks { |
|
| 224 | + | Some(hunks) => { |
|
| 225 | + | let accepted = hunks |
|
| 226 | + | .iter() |
|
| 227 | + | .filter(|(_, identity)| accepted_state.contains(identity)) |
|
| 228 | + | .map(|(id, _)| *id) |
|
| 229 | + | .collect::<BTreeSet<_>>(); |
|
| 230 | + | (!hunks.is_empty() && accepted.len() == hunks.len(), accepted) |
|
| 231 | + | } |
|
| 232 | + | None => { |
|
| 233 | + | let reviewed = totals |
|
| 234 | + | .get(&commit.commit) |
|
| 235 | + | .is_some_and(|(accepted, total)| *accepted == *total as usize); |
|
| 236 | + | (reviewed, BTreeSet::new()) |
|
| 237 | + | } |
|
| 238 | + | }; |
|
| 239 | + | reconciled.push(Self { reviewed, accepted }); |
|
| 240 | + | } |
|
| 241 | + | reconciled |
|
| 242 | + | } |
|
| 243 | + | } |
|
| 244 | + | ||
| 90 | 245 | /// Stored status for one review identity. |
|
| 91 | 246 | #[derive(Clone, Debug, Eq, PartialEq)] |
|
| 92 | 247 | pub struct BrainStatus { |
|
| 93 | 248 | /// Head name displayed to the user. |
|
| 94 | 249 | pub head: String, |
| 186 | 341 | format!("{}..{}", self.base.as_str(), self.target.as_str()) |
|
| 187 | 342 | } |
|
| 188 | 343 | ||
| 189 | 344 | /// Decodes a stored review identity from a state ref. |
|
| 190 | 345 | /// |
|
| 191 | - | /// Returns `None` for refs that do not use the `range/<base>/<target>` |
|
| 192 | - | /// layout, such as state written before range-keyed identities existed. |
|
| 346 | + | /// Returns `None` for refs outside the `range/<base>/<target>` layout. |
|
| 193 | 347 | fn from_ref(prefix: &Qualified<'_>, reference: &Qualified<'_>) -> Option<Self> { |
|
| 194 | 348 | let review = reference.strip_prefix(prefix)?; |
|
| 195 | 349 | let (base, target) = review.as_str().strip_prefix("range/")?.split_once('/')?; |
|
| 196 | 350 | if base.is_empty() || target.is_empty() || target.contains('/') { |
|
| 197 | 351 | return None; |
| 201 | 355 | ||
| 202 | 356 | Some(Self::new(base, target)) |
|
| 203 | 357 | } |
|
| 204 | 358 | } |
|
| 205 | 359 | ||
| 360 | + | /// Encodes exact accepted-hunk state in a synthetic commit message. |
|
| 361 | + | fn encode_state(accepted: &Accepted) -> String { |
|
| 362 | + | let mut message = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n"); |
|
| 363 | + | for hunk in accepted { |
|
| 364 | + | message.push_str(&format!( |
|
| 365 | + | "{} {} {} {}\n", |
|
| 366 | + | hunk.commit, hunk.patch_id, hunk.ordinal, hunk.commit_hunks |
|
| 367 | + | )); |
|
| 368 | + | } |
|
| 369 | + | message |
|
| 370 | + | } |
|
| 371 | + | ||
| 372 | + | /// Decodes exact accepted-hunk state from a synthetic commit message. |
|
| 373 | + | /// |
|
| 374 | + | /// Returns `None` for malformed state. |
|
| 375 | + | fn decode_state(message: &str) -> Option<Accepted> { |
|
| 376 | + | let header = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n"); |
|
| 377 | + | let body = message.strip_prefix(&header)?; |
|
| 378 | + | let mut accepted = BTreeSet::new(); |
|
| 379 | + | let mut commit_hunks = BTreeMap::new(); |
|
| 380 | + | ||
| 381 | + | for line in body.lines().filter(|line| !line.trim().is_empty()) { |
|
| 382 | + | let mut fields = line.split_whitespace(); |
|
| 383 | + | let hunk = AcceptedHunk { |
|
| 384 | + | commit: fields.next()?.parse().ok()?, |
|
| 385 | + | patch_id: PatchId::from_str(fields.next()?).ok()?, |
|
| 386 | + | ordinal: fields.next()?.parse().ok()?, |
|
| 387 | + | commit_hunks: fields.next()?.parse().ok()?, |
|
| 388 | + | }; |
|
| 389 | + | if fields.next().is_some() || hunk.commit_hunks == 0 { |
|
| 390 | + | return None; |
|
| 391 | + | } |
|
| 392 | + | match commit_hunks.entry(hunk.commit) { |
|
| 393 | + | std::collections::btree_map::Entry::Vacant(entry) => { |
|
| 394 | + | entry.insert(hunk.commit_hunks); |
|
| 395 | + | } |
|
| 396 | + | std::collections::btree_map::Entry::Occupied(entry) |
|
| 397 | + | if *entry.get() != hunk.commit_hunks => |
|
| 398 | + | { |
|
| 399 | + | return None; |
|
| 400 | + | } |
|
| 401 | + | std::collections::btree_map::Entry::Occupied(_) => {} |
|
| 402 | + | } |
|
| 403 | + | if !accepted.insert(hunk) { |
|
| 404 | + | return None; |
|
| 405 | + | } |
|
| 406 | + | } |
|
| 407 | + | Some(accepted) |
|
| 408 | + | } |
|
| 409 | + | ||
| 206 | 410 | /// Commit hunk identity data used to summarize stored review progress. |
|
| 207 | 411 | struct SummaryCommit { |
|
| 208 | 412 | /// Commit being summarized. |
|
| 209 | 413 | commit: Commit, |
|
| 210 | - | /// Stable patch id per hunk in the commit. |
|
| 211 | - | patch_ids: BTreeMap<HunkId, PatchId>, |
|
| 414 | + | /// Exact accepted-state identity per hunk in the commit. |
|
| 415 | + | identities: BTreeMap<HunkId, AcceptedHunk>, |
|
| 212 | 416 | } |
|
| 213 | 417 | ||
| 214 | 418 | /// Stored comment status for one review identity. |
|
| 215 | 419 | #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] |
|
| 216 | 420 | pub enum CommentStatus { |
| 242 | 446 | /// Rebases and loads the hidden review state for this backend. |
|
| 243 | 447 | fn rebase_brain(&self) -> Result<Brain, Error>; |
|
| 244 | 448 | ||
| 245 | 449 | /// Returns a repo handle for widening `commit`'s hunk context. |
|
| 246 | 450 | fn repo(&self, commit: &Commit) -> git::Repository; |
|
| 247 | - | ||
| 248 | - | /// Returns each reviewed commit's diff with hunks split for review. |
|
| 249 | - | fn documents(&self) -> Result<Vec<DiffDocument>, Error> { |
|
| 250 | - | self.commits()? |
|
| 251 | - | .iter() |
|
| 252 | - | .map(|commit| Ok(self.commit_diff(commit)?.split_hunks())) |
|
| 253 | - | .collect() |
|
| 254 | - | } |
|
| 255 | 451 | } |
|
| 256 | 452 | ||
| 257 | 453 | impl dyn Backend { |
|
| 258 | 454 | /// Returns a backend for `cwd` bound to the `base..target` range. |
|
| 259 | 455 | /// |
| 288 | 484 | /// Returns whether `cwd` is inside a Jujutsu workspace. |
|
| 289 | 485 | fn is_jj_workspace(cwd: &Path) -> bool { |
|
| 290 | 486 | cwd.ancestors().any(|path| path.join(JJ_DIR).is_dir()) |
|
| 291 | 487 | } |
|
| 292 | 488 | ||
| 293 | - | /// Hidden Git state holding one review's acceptance tree and comments. |
|
| 489 | + | /// Hidden Git state holding one review's acceptance state and comments. |
|
| 294 | 490 | /// |
|
| 295 | - | /// The acceptance tree is the persistent source of truth for accepted review |
|
| 296 | - | /// content; comments are stored as a JSONL blob under a sibling ref. Both live |
|
| 297 | - | /// entirely inside the Git object store, so review state travels with the |
|
| 298 | - | /// repository and never touches the working tree. |
|
| 491 | + | /// Exact accepted-hunk identities are stored in the state commit message. The |
|
| 492 | + | /// commit tree is a best-effort content projection. Comments are stored as a |
|
| 493 | + | /// JSONL blob under a sibling ref. All state lives inside the Git object store. |
|
| 299 | 494 | #[derive(Clone, Debug)] |
|
| 300 | 495 | pub struct Brain { |
|
| 301 | 496 | /// Git command context. |
|
| 302 | 497 | repository: git::Repository, |
|
| 303 | 498 | /// Hidden ref storing the synthetic acceptance state commit. |
| 306 | 501 | comments_ref: Qualified<'static>, |
|
| 307 | 502 | /// Base commit used as the parent of synthetic state commits. |
|
| 308 | 503 | base: Oid, |
|
| 309 | 504 | /// Current synthetic state commit. |
|
| 310 | 505 | commit: Oid, |
|
| 311 | - | /// Patch ids that matched accepted state but stayed pending after rebase. |
|
| 312 | - | rebase_pending: BTreeSet<PatchId>, |
|
| 506 | + | /// Exact hunks accepted by the reviewer. |
|
| 507 | + | accepted: Accepted, |
|
| 313 | 508 | } |
|
| 314 | 509 | ||
| 315 | 510 | impl Brain { |
|
| 316 | - | /// Creates a review state handle with no rebase-pending hunks. |
|
| 511 | + | /// Creates a review state handle. |
|
| 317 | 512 | fn new( |
|
| 318 | 513 | repository: git::Repository, |
|
| 319 | 514 | state_ref: Qualified<'static>, |
|
| 320 | 515 | comments_ref: Qualified<'static>, |
|
| 321 | 516 | base: Oid, |
|
| 322 | 517 | commit: Oid, |
|
| 518 | + | accepted: Accepted, |
|
| 323 | 519 | ) -> Self { |
|
| 324 | 520 | Self { |
|
| 325 | 521 | repository, |
|
| 326 | 522 | state_ref, |
|
| 327 | 523 | comments_ref, |
|
| 328 | 524 | base, |
|
| 329 | 525 | commit, |
|
| 330 | - | rebase_pending: BTreeSet::new(), |
|
| 526 | + | accepted, |
|
| 331 | 527 | } |
|
| 332 | 528 | } |
|
| 333 | 529 | ||
| 334 | 530 | /// Returns the hidden Git ref prefix for `namespace`. |
|
| 335 | 531 | fn prefix_for(namespace: &'static str) -> Result<Qualified<'static>, Error> { |
| 436 | 632 | if repository.commit_id(&identity.target).is_err() { |
|
| 437 | 633 | continue; |
|
| 438 | 634 | } |
|
| 439 | 635 | let base = repository.parent(state)?; |
|
| 440 | 636 | let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, &identity)?; |
|
| 441 | - | let brain = Brain::new(repository.clone(), reference, comments_ref, base, state); |
|
| 637 | + | let message = repository.commit_message(state)?; |
|
| 638 | + | let Some(accepted) = decode_state(&message) else { |
|
| 639 | + | continue; |
|
| 640 | + | }; |
|
| 641 | + | let brain = Brain::new( |
|
| 642 | + | repository.clone(), |
|
| 643 | + | reference, |
|
| 644 | + | comments_ref, |
|
| 645 | + | base, |
|
| 646 | + | state, |
|
| 647 | + | accepted, |
|
| 648 | + | ); |
|
| 442 | 649 | let comments = brain.comment_status()?; |
|
| 443 | - | let (head, progress) = brain.summary(&identity)?; |
|
| 650 | + | let head = repository.commit_id(&identity.target)?; |
|
| 651 | + | let progress = brain.summary(&identity)?.1; |
|
| 444 | 652 | let recency = repository.commit_time(head)?; |
|
| 445 | 653 | let updated = repository.commit_time(state)?; |
|
| 446 | 654 | ||
| 447 | 655 | reviews.insert( |
|
| 448 | 656 | identity, |
| 493 | 701 | Ok(status) |
|
| 494 | 702 | } |
|
| 495 | 703 | ||
| 496 | 704 | /// Returns the target commit and accepted-hunk progress for this review. |
|
| 497 | 705 | /// |
|
| 498 | - | /// Progress is derived by the same tree reconciliation used by the |
|
| 499 | - | /// interactive review, so it can handle multi-commit ranges whose accepted |
|
| 500 | - | /// tree diff no longer has the same hunk shape as the original commits. |
|
| 706 | + | /// Progress is counted from exact accepted-hunk identities. |
|
| 501 | 707 | fn summary(&self, identity: &ReviewIdentity) -> Result<(Oid, ReviewProgress), Error> { |
|
| 502 | 708 | let base = Rev::from(self.base); |
|
| 503 | 709 | let target = &identity.target; |
|
| 504 | 710 | let head = self.repository.commit_id(target)?; |
|
| 505 | 711 | let commits = self.summary_commits(&base, target)?; |
|
| 506 | 712 | let hunks = commits |
|
| 507 | 713 | .iter() |
|
| 508 | 714 | .map(|summary| CommitHunks { |
|
| 509 | - | commit: &summary.commit, |
|
| 510 | - | hunks: Some(&summary.patch_ids), |
|
| 715 | + | commit: summary.commit.id, |
|
| 716 | + | hunks: Some(&summary.identities), |
|
| 511 | 717 | }) |
|
| 512 | 718 | .collect::<Vec<_>>(); |
|
| 513 | - | let reconciled = self.reconcile(&hunks)?; |
|
| 719 | + | let reconciled = self.reconcile(&hunks); |
|
| 514 | 720 | let accepted = reconciled.iter().map(|state| state.accepted.len()).sum(); |
|
| 515 | 721 | let total = hunks |
|
| 516 | 722 | .iter() |
|
| 517 | 723 | .filter_map(|commit| commit.hunks) |
|
| 518 | 724 | .map(BTreeMap::len) |
|
| 519 | 725 | .sum(); |
|
| 520 | 726 | ||
| 521 | 727 | Ok((head, ReviewProgress { accepted, total })) |
|
| 522 | 728 | } |
|
| 523 | 729 | ||
| 524 | - | /// Returns commits and stable hunk patch ids for status progress. |
|
| 730 | + | /// Returns commits and exact hunk identities for status progress. |
|
| 525 | 731 | fn summary_commits(&self, base: &Rev, target: &Rev) -> Result<Vec<SummaryCommit>, Error> { |
|
| 526 | 732 | let commits = self |
|
| 527 | 733 | .repository |
|
| 528 | 734 | .commits(base, target)? |
|
| 529 | 735 | .into_iter() |
| 535 | 741 | let mut summaries = Vec::with_capacity(commits.len()); |
|
| 536 | 742 | ||
| 537 | 743 | for commit in commits { |
|
| 538 | 744 | let bytes = self.repository.commit_diff(commit.id)?; |
|
| 539 | 745 | let document = DiffDocument::decode_bytes(&bytes)?.split_hunks(); |
|
| 540 | - | let patch_ids = self.patch_ids(&document)?; |
|
| 541 | - | summaries.push(SummaryCommit { commit, patch_ids }); |
|
| 746 | + | let identities = self.hunk_identities(&document, commit.id)?; |
|
| 747 | + | summaries.push(SummaryCommit { commit, identities }); |
|
| 542 | 748 | } |
|
| 543 | 749 | ||
| 544 | 750 | Ok(summaries) |
|
| 545 | 751 | } |
|
| 546 | 752 | ||
| 547 | - | /// Returns patch ids present in the stored accepted-state diff. |
|
| 548 | - | fn accepted_patch_ids(&self) -> Result<BTreeSet<PatchId>, Error> { |
|
| 549 | - | let patch = self.repository.diff(self.base, self.commit)?; |
|
| 550 | - | let document = DiffDocument::decode_str(&patch)?.split_hunks(); |
|
| 551 | - | let patch_ids = self.patch_ids(&document)?; |
|
| 552 | - | ||
| 553 | - | Ok(patch_ids.into_values().collect()) |
|
| 554 | - | } |
|
| 555 | - | ||
| 556 | - | /// Returns per-hunk patch ids from a decoded review document. |
|
| 753 | + | /// Returns exact accepted-state identities in document order. |
|
| 557 | 754 | /// |
|
| 558 | - | /// All hunk patches are hashed by one `git patch-id` invocation. |
|
| 559 | - | fn patch_ids(&self, document: &DiffDocument) -> Result<BTreeMap<HunkId, PatchId>, Error> { |
|
| 755 | + | /// `document` must be `commit`'s own split-hunk diff: the identities carry |
|
| 756 | + | /// `commit` verbatim and count its hunks, so passing a document from any |
|
| 757 | + | /// other commit yields identities that silently name the wrong change. |
|
| 758 | + | pub fn hunk_identities( |
|
| 759 | + | &self, |
|
| 760 | + | document: &DiffDocument, |
|
| 761 | + | commit: Oid, |
|
| 762 | + | ) -> Result<BTreeMap<HunkId, AcceptedHunk>, Error> { |
|
| 560 | 763 | let (ids, patches): (Vec<_>, Vec<_>) = hunk_identity_patches(document)?.into_iter().unzip(); |
|
| 764 | + | let commit_hunks = u32::try_from(ids.len()) |
|
| 765 | + | .map_err(|_| Error::Git("commit contains too many review hunks".to_owned()))?; |
|
| 561 | 766 | let patch_ids = self.repository.patch_ids(&patches)?; |
|
| 562 | - | ||
| 563 | - | Ok(ids.into_iter().zip(patch_ids).collect()) |
|
| 767 | + | let mut seen = BTreeMap::<PatchId, u32>::new(); |
|
| 768 | + | let mut identities = BTreeMap::new(); |
|
| 769 | + | ||
| 770 | + | for (id, patch_id) in ids.into_iter().zip(patch_ids) { |
|
| 771 | + | let ordinal = seen.entry(patch_id.clone()).or_default(); |
|
| 772 | + | let identity = AcceptedHunk { |
|
| 773 | + | commit, |
|
| 774 | + | patch_id, |
|
| 775 | + | ordinal: *ordinal, |
|
| 776 | + | commit_hunks, |
|
| 777 | + | }; |
|
| 778 | + | *ordinal += 1; |
|
| 779 | + | identities.insert(id, identity); |
|
| 780 | + | } |
|
| 781 | + | Ok(identities) |
|
| 564 | 782 | } |
|
| 565 | 783 | ||
| 566 | 784 | /// Loads or initializes the hidden review state for one review. |
|
| 567 | 785 | fn load( |
|
| 568 | 786 | repository: git::Repository, |
|
| 569 | 787 | base: Oid, |
|
| 570 | 788 | identity: &ReviewIdentity, |
|
| 571 | 789 | ) -> Result<Self, Error> { |
|
| 572 | 790 | let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?; |
|
| 573 | 791 | let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?; |
|
| 574 | - | let commit = match repository.optional_ref(&state_ref)? { |
|
| 792 | + | let (commit, accepted) = match repository.optional_ref(&state_ref)? { |
|
| 575 | 793 | Some(existing) => { |
|
| 576 | 794 | let parent = repository.parent(existing)?; |
|
| 577 | - | if parent == base { |
|
| 578 | - | existing |
|
| 579 | - | } else { |
|
| 795 | + | if parent != base { |
|
| 580 | 796 | return Err(Error::StaleReviewState { |
|
| 581 | 797 | stored_base: parent, |
|
| 582 | 798 | current_base: base, |
|
| 583 | 799 | }); |
|
| 584 | 800 | } |
|
| 801 | + | let message = repository.commit_message(existing)?; |
|
| 802 | + | let accepted = decode_state(&message).ok_or(Error::InvalidReviewState)?; |
|
| 803 | + | (existing, accepted) |
|
| 585 | 804 | } |
|
| 586 | - | None => Brain::write_fresh_state(&repository, base, &state_ref)?, |
|
| 805 | + | None => ( |
|
| 806 | + | Brain::write_fresh_state(&repository, base, &state_ref)?, |
|
| 807 | + | Accepted::new(), |
|
| 808 | + | ), |
|
| 587 | 809 | }; |
|
| 588 | - | Ok(Self::new(repository, state_ref, comments_ref, base, commit)) |
|
| 810 | + | Ok(Self::new( |
|
| 811 | + | repository, |
|
| 812 | + | state_ref, |
|
| 813 | + | comments_ref, |
|
| 814 | + | base, |
|
| 815 | + | commit, |
|
| 816 | + | accepted, |
|
| 817 | + | )) |
|
| 589 | 818 | } |
|
| 590 | 819 | ||
| 591 | 820 | /// Replaces the hidden review state for one review and returns it. |
|
| 592 | 821 | fn reset( |
|
| 593 | 822 | repository: git::Repository, |
| 596 | 825 | ) -> Result<Self, Error> { |
|
| 597 | 826 | let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?; |
|
| 598 | 827 | let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?; |
|
| 599 | 828 | let commit = Brain::write_fresh_state(&repository, base, &state_ref)?; |
|
| 600 | 829 | ||
| 601 | - | Ok(Self::new(repository, state_ref, comments_ref, base, commit)) |
|
| 830 | + | Ok(Self::new( |
|
| 831 | + | repository, |
|
| 832 | + | state_ref, |
|
| 833 | + | comments_ref, |
|
| 834 | + | base, |
|
| 835 | + | commit, |
|
| 836 | + | Accepted::new(), |
|
| 837 | + | )) |
|
| 602 | 838 | } |
|
| 603 | 839 | ||
| 604 | 840 | /// Carries accepted hunks from stored state onto the current base. |
|
| 605 | 841 | fn rebase( |
|
| 606 | 842 | repository: git::Repository, |
|
| 607 | 843 | base: Oid, |
|
| 608 | 844 | identity: &ReviewIdentity, |
|
| 845 | + | commits: &[Commit], |
|
| 609 | 846 | documents: &[DiffDocument], |
|
| 610 | 847 | ) -> Result<Self, Error> { |
|
| 611 | 848 | let state_ref = Brain::ref_for_identity(STATE_REF_NAMESPACE, identity)?; |
|
| 612 | 849 | let comments_ref = Brain::ref_for_identity(COMMENTS_REF_NAMESPACE, identity)?; |
|
| 613 | - | let accepted = match repository.optional_ref(&state_ref)? { |
|
| 850 | + | let stored = match repository.optional_ref(&state_ref)? { |
|
| 614 | 851 | Some(existing) => { |
|
| 615 | 852 | let parent = repository.parent(existing)?; |
|
| 853 | + | let message = repository.commit_message(existing)?; |
|
| 854 | + | let accepted = decode_state(&message).ok_or(Error::InvalidReviewState)?; |
|
| 616 | 855 | if parent == base { |
|
| 617 | 856 | return Ok(Self::new( |
|
| 618 | 857 | repository, |
|
| 619 | 858 | state_ref, |
|
| 620 | 859 | comments_ref, |
|
| 621 | 860 | base, |
|
| 622 | 861 | existing, |
|
| 862 | + | accepted, |
|
| 623 | 863 | )); |
|
| 624 | 864 | } |
|
| 625 | - | let stored = Self::new( |
|
| 626 | - | repository.clone(), |
|
| 627 | - | state_ref.clone(), |
|
| 628 | - | comments_ref.clone(), |
|
| 629 | - | parent, |
|
| 630 | - | existing, |
|
| 631 | - | ); |
|
| 632 | - | stored.accepted_patch_ids()? |
|
| 865 | + | accepted |
|
| 633 | 866 | } |
|
| 634 | - | None => BTreeSet::new(), |
|
| 867 | + | None => Accepted::new(), |
|
| 635 | 868 | }; |
|
| 636 | 869 | let commit = Brain::write_fresh_state(&repository, base, &state_ref)?; |
|
| 637 | - | let mut brain = Self::new(repository, state_ref, comments_ref, base, commit); |
|
| 638 | - | brain.rebase_pending = brain.rebase_accepted_patches(documents, &accepted)?; |
|
| 870 | + | let mut brain = Self::new( |
|
| 871 | + | repository, |
|
| 872 | + | state_ref, |
|
| 873 | + | comments_ref, |
|
| 874 | + | base, |
|
| 875 | + | commit, |
|
| 876 | + | Accepted::new(), |
|
| 877 | + | ); |
|
| 878 | + | brain.remap(commits, documents, &stored)?; |
|
| 639 | 879 | ||
| 640 | 880 | Ok(brain) |
|
| 641 | 881 | } |
|
| 642 | 882 | ||
| 643 | 883 | /// Writes an empty accepted-state commit at `base`. |
| 650 | 890 | let fresh = repository.commit( |
|
| 651 | 891 | tree, |
|
| 652 | 892 | base, |
|
| 653 | 893 | "brain", |
|
| 654 | 894 | "brain@example.invalid", |
|
| 655 | - | SYNTHETIC_BRAIN_MESSAGE, |
|
| 895 | + | &encode_state(&Accepted::new()), |
|
| 656 | 896 | )?; |
|
| 657 | 897 | repository.update_ref(state_ref, fresh)?; |
|
| 658 | 898 | ||
| 659 | 899 | Ok(fresh) |
|
| 660 | 900 | } |
| 674 | 914 | /// Reads one source blob for file metadata derived from complete contents. |
|
| 675 | 915 | pub fn read_blob(&self, oid: Oid) -> Result<Vec<u8>, Error> { |
|
| 676 | 916 | Ok(self.repository.cat_blob(oid)?) |
|
| 677 | 917 | } |
|
| 678 | 918 | ||
| 679 | - | /// Returns whether `patch_id` needs review after a review rebase. |
|
| 680 | - | pub fn is_rebase_pending(&self, patch_id: &PatchId) -> bool { |
|
| 681 | - | self.rebase_pending.contains(patch_id) |
|
| 682 | - | } |
|
| 683 | - | ||
| 684 | 919 | /// Reads the review's persisted comments blob, if any. |
|
| 685 | 920 | pub fn read_comments(&self) -> Result<Option<String>, Error> { |
|
| 686 | 921 | let Some(blob) = self.repository.optional_ref(&self.comments_ref)? else { |
|
| 687 | 922 | return Ok(None); |
|
| 688 | 923 | }; |
| 695 | 930 | let blob = self.repository.write_blob(text.as_bytes())?; |
|
| 696 | 931 | self.repository.update_ref(&self.comments_ref, blob)?; |
|
| 697 | 932 | Ok(()) |
|
| 698 | 933 | } |
|
| 699 | 934 | ||
| 700 | - | /// Applies selected hunk patches to the hidden tree and persists them. |
|
| 701 | - | /// |
|
| 702 | - | /// The hidden tree is the source of truth for accepted review content. Each |
|
| 703 | - | /// acceptance update produces a new synthetic commit whose parent remains |
|
| 704 | - | /// the exact review base, so later loads can reject state from a different |
|
| 705 | - | /// base instead of trying to reinterpret it. |
|
| 706 | - | pub fn apply_patches<'a>( |
|
| 935 | + | /// Marks hunks accepted and updates the derived tree. |
|
| 936 | + | pub fn accept( |
|
| 707 | 937 | &mut self, |
|
| 708 | - | patches: impl IntoIterator<Item = &'a str>, |
|
| 938 | + | hunks: impl IntoIterator<Item = (AcceptedHunk, String)>, |
|
| 709 | 939 | ) -> Result<(), Error> { |
|
| 710 | 940 | let mut tree = self.repository.tree_id(self.commit)?; |
|
| 711 | - | for patch in patches { |
|
| 712 | - | tree = self.repository.apply_patch_to_tree(tree, patch)?; |
|
| 941 | + | let mut accepted = self.accepted.clone(); |
|
| 942 | + | for (identity, patch) in hunks { |
|
| 943 | + | accepted.insert(identity); |
|
| 944 | + | tree = self.project(tree, &patch)?; |
|
| 713 | 945 | } |
|
| 714 | - | self.advance_to_tree(tree) |
|
| 946 | + | self.persist(tree, accepted) |
|
| 715 | 947 | } |
|
| 716 | 948 | ||
| 717 | - | /// Rebuilds the hidden tree from patches that should remain accepted. |
|
| 718 | - | /// |
|
| 719 | - | /// Patches that depended on a removed patch are omitted when they no |
|
| 720 | - | /// longer apply to the rebuilt tree. Reconciliation then marks those hunks |
|
| 721 | - | /// unaccepted as well. |
|
| 722 | - | pub fn replace_patches<'a>( |
|
| 949 | + | /// Marks exact hunks unaccepted and rebuilds the derived tree. |
|
| 950 | + | pub fn reject( |
|
| 723 | 951 | &mut self, |
|
| 724 | - | patches: impl IntoIterator<Item = &'a str>, |
|
| 952 | + | rejected: &BTreeSet<AcceptedHunk>, |
|
| 953 | + | files: impl IntoIterator<Item = FilePatches>, |
|
| 725 | 954 | ) -> Result<(), Error> { |
|
| 955 | + | let mut accepted = self.accepted.clone(); |
|
| 956 | + | accepted.retain(|hunk| !rejected.contains(hunk)); |
|
| 726 | 957 | let mut tree = self.repository.tree_id(self.base)?; |
|
| 727 | - | for patch in patches { |
|
| 728 | - | match self.repository.apply_patch_to_tree(tree, patch) { |
|
| 729 | - | Ok(next) => tree = next, |
|
| 730 | - | Err(rustik_repo::RepoError::Git(_)) => continue, |
|
| 731 | - | Err(error) => return Err(error.into()), |
|
| 732 | - | } |
|
| 958 | + | for file in files { |
|
| 959 | + | tree = self.project_file(tree, &file)?; |
|
| 960 | + | } |
|
| 961 | + | self.persist(tree, accepted) |
|
| 962 | + | } |
|
| 963 | + | ||
| 964 | + | /// Applies `patch` to `tree`, keeping `tree` when it does not apply. |
|
| 965 | + | /// |
|
| 966 | + | /// The tree is only a content projection of the accepted set, so a hunk |
|
| 967 | + | /// that depends on an unaccepted one is skipped instead of failing the |
|
| 968 | + | /// update. Every other Git failure is real and propagates. |
|
| 969 | + | fn project(&self, tree: Oid, patch: &str) -> Result<Oid, Error> { |
|
| 970 | + | match self.repository.apply_patch_to_tree(tree, patch) { |
|
| 971 | + | Ok(next) => Ok(next), |
|
| 972 | + | Err(rustik_repo::RepoError::PatchApply(_)) => Ok(tree), |
|
| 973 | + | Err(error) => Err(error.into()), |
|
| 974 | + | } |
|
| 975 | + | } |
|
| 976 | + | ||
| 977 | + | /// Applies one file's accepted hunks to `tree`. |
|
| 978 | + | /// |
|
| 979 | + | /// The combined patch is tried first so a file costs one `git apply`; only |
|
| 980 | + | /// when it fails are the hunks replayed individually, so one hunk that no |
|
| 981 | + | /// longer applies cannot drop the rest of its file from the projection. |
|
| 982 | + | fn project_file(&self, tree: Oid, file: &FilePatches) -> Result<Oid, Error> { |
|
| 983 | + | match self.repository.apply_patch_to_tree(tree, &file.combined) { |
|
| 984 | + | Ok(next) => return Ok(next), |
|
| 985 | + | Err(rustik_repo::RepoError::PatchApply(_)) => {} |
|
| 986 | + | Err(error) => return Err(error.into()), |
|
| 987 | + | } |
|
| 988 | + | let mut tree = tree; |
|
| 989 | + | for patch in &file.hunks { |
|
| 990 | + | tree = self.project(tree, patch)?; |
|
| 733 | 991 | } |
|
| 734 | - | self.advance_to_tree(tree) |
|
| 992 | + | Ok(tree) |
|
| 735 | 993 | } |
|
| 736 | 994 | ||
| 737 | - | /// Carries matching accepted patches into this review state. |
|
| 738 | - | fn rebase_accepted_patches( |
|
| 995 | + | /// Remaps accepted identities onto a moved review range. |
|
| 996 | + | fn remap( |
|
| 739 | 997 | &mut self, |
|
| 998 | + | commits: &[Commit], |
|
| 740 | 999 | documents: &[DiffDocument], |
|
| 741 | - | accepted: &BTreeSet<PatchId>, |
|
| 742 | - | ) -> Result<BTreeSet<PatchId>, Error> { |
|
| 743 | - | let mut pending = BTreeSet::new(); |
|
| 1000 | + | stored: &Accepted, |
|
| 1001 | + | ) -> Result<(), Error> { |
|
| 1002 | + | debug_assert_eq!(commits.len(), documents.len(), "one document per commit"); |
|
| 744 | 1003 | ||
| 745 | - | for document in documents { |
|
| 746 | - | let patch_ids = self.patch_ids(document)?; |
|
| 1004 | + | // Hunks of the moved range in range order, grouped by file so the |
|
| 1005 | + | // projection can apply a whole file at once. |
|
| 1006 | + | let mut current = Vec::new(); |
|
| 1007 | + | for (commit, document) in commits.iter().zip(documents) { |
|
| 1008 | + | let identities = self.hunk_identities(document, commit.id)?; |
|
| 747 | 1009 | for file in &document.files { |
|
| 748 | - | for hunk in &file.hunks { |
|
| 749 | - | let Some(patch_id) = patch_ids.get(&hunk.id) else { |
|
| 750 | - | continue; |
|
| 751 | - | }; |
|
| 752 | - | if !accepted.contains(patch_id) { |
|
| 753 | - | continue; |
|
| 754 | - | } |
|
| 755 | - | let patch = |
|
| 756 | - | DiffDocument::for_hunks(file, [hunk.clone()]).to_unified_string()?; |
|
| 757 | - | match self.repository.apply_patch_to_tree(self.commit, &patch) { |
|
| 758 | - | Ok(tree) => self.advance_to_tree(tree)?, |
|
| 759 | - | Err(rustik_repo::RepoError::Git(_)) => { |
|
| 760 | - | pending.insert(patch_id.clone()); |
|
| 761 | - | } |
|
| 762 | - | Err(error) => return Err(error.into()), |
|
| 763 | - | } |
|
| 764 | - | } |
|
| 1010 | + | let hunks = file |
|
| 1011 | + | .hunks |
|
| 1012 | + | .iter() |
|
| 1013 | + | .filter_map(|hunk| Some((identities.get(&hunk.id)?.clone(), hunk.clone()))) |
|
| 1014 | + | .collect::<Vec<_>>(); |
|
| 1015 | + | current.push((file, hunks)); |
|
| 765 | 1016 | } |
|
| 766 | 1017 | } |
|
| 767 | 1018 | ||
| 768 | - | Ok(pending) |
|
| 1019 | + | let identities = current |
|
| 1020 | + | .iter() |
|
| 1021 | + | .flat_map(|(_, hunks)| hunks.iter().map(|(identity, _)| identity)); |
|
| 1022 | + | let accepted = AcceptedHunk::remap(stored, identities); |
|
| 1023 | + | ||
| 1024 | + | let mut tree = self.repository.tree_id(self.base)?; |
|
| 1025 | + | for (file, hunks) in current { |
|
| 1026 | + | let hunks = hunks |
|
| 1027 | + | .into_iter() |
|
| 1028 | + | .filter(|(identity, _)| accepted.contains(identity)) |
|
| 1029 | + | .map(|(_, hunk)| hunk) |
|
| 1030 | + | .collect::<Vec<_>>(); |
|
| 1031 | + | if hunks.is_empty() { |
|
| 1032 | + | continue; |
|
| 1033 | + | } |
|
| 1034 | + | tree = self.project_file(tree, &FilePatches::new(file, hunks)?)?; |
|
| 1035 | + | } |
|
| 1036 | + | self.persist(tree, accepted) |
|
| 769 | 1037 | } |
|
| 770 | 1038 | ||
| 771 | - | /// Persists `tree` as the current accepted review state. |
|
| 772 | - | fn advance_to_tree(&mut self, tree: Oid) -> Result<(), Error> { |
|
| 773 | - | let commit = self.repository.commit( |
|
| 774 | - | tree, |
|
| 775 | - | self.base, |
|
| 776 | - | "brain", |
|
| 777 | - | "brain@example.invalid", |
|
| 778 | - | SYNTHETIC_BRAIN_MESSAGE, |
|
| 779 | - | )?; |
|
| 1039 | + | /// Persists exact acceptance and its derived tree in one commit. |
|
| 1040 | + | fn persist(&mut self, tree: Oid, accepted: Accepted) -> Result<(), Error> { |
|
| 1041 | + | let message = encode_state(&accepted); |
|
| 1042 | + | let commit = |
|
| 1043 | + | self.repository |
|
| 1044 | + | .commit(tree, self.base, "brain", "brain@example.invalid", &message)?; |
|
| 780 | 1045 | self.repository.update_ref(&self.state_ref, commit)?; |
|
| 781 | 1046 | self.commit = commit; |
|
| 1047 | + | self.accepted = accepted; |
|
| 782 | 1048 | ||
| 783 | 1049 | Ok(()) |
|
| 784 | 1050 | } |
|
| 785 | 1051 | ||
| 786 | - | /// Reconciles per-commit review state against the current hidden tree. |
|
| 787 | - | /// |
|
| 788 | - | /// The algorithm walks reviewed commits in order and asks what would remain |
|
| 789 | - | /// if each commit were merged into the current accepted-content cursor. The |
|
| 790 | - | /// residual diff is compared against the supplied per-hunk patch ids; a |
|
| 791 | - | /// hunk is accepted when its patch id no longer appears in the residual. |
|
| 792 | - | /// Commits without supplied patch ids (not yet decoded) still report their |
|
| 793 | - | /// `reviewed` state, which needs only the residual. |
|
| 794 | - | /// |
|
| 795 | - | /// The cursor only advances through commits that are fully accepted. This |
|
| 796 | - | /// keeps later commits from being classified relative to unaccepted changes |
|
| 797 | - | /// that still belong in the pending review. |
|
| 798 | - | pub fn reconcile(&self, commits: &[CommitHunks<'_>]) -> Result<Vec<Reconciled>, Error> { |
|
| 799 | - | let mut cursor = self.commit; |
|
| 800 | - | let mut reconciled = Vec::with_capacity(commits.len()); |
|
| 801 | - | ||
| 802 | - | for commit in commits { |
|
| 803 | - | let parent = self.repository.parent(commit.commit.id)?; |
|
| 804 | - | let candidate = match self.repository.merge_tree(parent, cursor, commit.commit.id) { |
|
| 805 | - | Ok(candidate) => candidate, |
|
| 806 | - | Err(rustik_repo::RepoError::MergeConflict(_)) => { |
|
| 807 | - | // A conflict means this commit cannot be cleanly replayed on |
|
| 808 | - | // the accepted cursor, so none of its hunks can be proven |
|
| 809 | - | // accepted from tree state. |
|
| 810 | - | reconciled.push(Reconciled { |
|
| 811 | - | reviewed: false, |
|
| 812 | - | accepted: BTreeSet::new(), |
|
| 813 | - | }); |
|
| 814 | - | continue; |
|
| 815 | - | } |
|
| 816 | - | Err(error) => return Err(error.into()), |
|
| 817 | - | }; |
|
| 818 | - | let residual = self.repository.diff(cursor, candidate)?; |
|
| 819 | - | let reviewed = residual.trim().is_empty(); |
|
| 820 | - | let accepted = match commit.hunks { |
|
| 821 | - | Some(hunks) if reviewed => hunks.keys().copied().collect(), |
|
| 822 | - | Some(hunks) => self.accepted_hunks(hunks, &residual)?, |
|
| 823 | - | None => BTreeSet::new(), |
|
| 824 | - | }; |
|
| 825 | - | reconciled.push(Reconciled { reviewed, accepted }); |
|
| 826 | - | ||
| 827 | - | if reviewed { |
|
| 828 | - | // Only fully accepted commits become part of the base used to |
|
| 829 | - | // classify later commits. |
|
| 830 | - | cursor = candidate; |
|
| 831 | - | } |
|
| 832 | - | } |
|
| 833 | - | Ok(reconciled) |
|
| 834 | - | } |
|
| 835 | - | ||
| 836 | - | /// Returns hunks whose patch id is absent from `residual`. |
|
| 837 | - | /// |
|
| 838 | - | /// Patch ids make the comparison insensitive to hunk line numbers and other |
|
| 839 | - | /// context drift in the residual diff. Only the residual's hunks are hashed |
|
| 840 | - | /// here; the original ids were computed once when the commit was loaded. |
|
| 841 | - | fn accepted_hunks( |
|
| 842 | - | &self, |
|
| 843 | - | original: &BTreeMap<HunkId, PatchId>, |
|
| 844 | - | residual: &str, |
|
| 845 | - | ) -> Result<BTreeSet<HunkId>, Error> { |
|
| 846 | - | let residual = DiffDocument::decode_str(residual)?; |
|
| 847 | - | let residual_ids: BTreeSet<_> = self.patch_ids(&residual)?.into_values().collect(); |
|
| 848 | - | ||
| 849 | - | Ok(accepted_hunks_from_patch_ids(original, &residual_ids)) |
|
| 1052 | + | /// Projects exact acceptance onto the current commit list. |
|
| 1053 | + | pub fn reconcile(&self, commits: &[CommitHunks<'_>]) -> Vec<Reconciled> { |
|
| 1054 | + | Reconciled::for_commits(&self.accepted, commits) |
|
| 850 | 1055 | } |
|
| 851 | 1056 | } |
|
| 852 | 1057 | ||
| 853 | 1058 | /// Returns the patch text used to identify `hunk` across base movement. |
|
| 854 | 1059 | fn hunk_identity_patch(file: &FileDiff, hunk: &Hunk) -> Result<String, Error> { |
| 864 | 1069 | } |
|
| 865 | 1070 | } |
|
| 866 | 1071 | Ok(patches) |
|
| 867 | 1072 | } |
|
| 868 | 1073 | ||
| 869 | - | /// Returns original hunks whose patch ids are absent from the residual set. |
|
| 870 | - | fn accepted_hunks_from_patch_ids<P: Ord>( |
|
| 871 | - | original: &BTreeMap<HunkId, P>, |
|
| 872 | - | residual: &BTreeSet<P>, |
|
| 873 | - | ) -> BTreeSet<HunkId> { |
|
| 874 | - | original |
|
| 875 | - | .iter() |
|
| 876 | - | .filter_map(|(hunk, patch_id)| (!residual.contains(patch_id)).then_some(*hunk)) |
|
| 877 | - | .collect() |
|
| 878 | - | } |
|
| 879 | - | ||
| 880 | 1074 | /// Returns trunk relation and merge status for `target`. |
|
| 881 | 1075 | /// |
|
| 882 | 1076 | /// A branch that is only ahead or only behind merges trivially, so the merge |
|
| 883 | 1077 | /// check only runs for diverged branches. |
|
| 884 | 1078 | fn relation_to_trunk( |
| 965 | 1159 | Brain::reset(self.repository.clone(), base, &self.review) |
|
| 966 | 1160 | } |
|
| 967 | 1161 | ||
| 968 | 1162 | fn rebase_brain(&self) -> Result<Brain, Error> { |
|
| 969 | 1163 | let base = self.repository.commit_id(&self.review.base)?; |
|
| 970 | - | let documents = self.documents()?; |
|
| 971 | - | Brain::rebase(self.repository.clone(), base, &self.review, &documents) |
|
| 1164 | + | let commits = self.commits()?; |
|
| 1165 | + | let documents = commits |
|
| 1166 | + | .iter() |
|
| 1167 | + | .map(|commit| Ok(self.commit_diff(commit)?.split_hunks())) |
|
| 1168 | + | .collect::<Result<Vec<_>, Error>>()?; |
|
| 1169 | + | Brain::rebase( |
|
| 1170 | + | self.repository.clone(), |
|
| 1171 | + | base, |
|
| 1172 | + | &self.review, |
|
| 1173 | + | &commits, |
|
| 1174 | + | &documents, |
|
| 1175 | + | ) |
|
| 972 | 1176 | } |
|
| 973 | 1177 | ||
| 974 | 1178 | fn repo(&self, commit: &Commit) -> git::Repository { |
|
| 975 | 1179 | self.repository.with_selector_args(commit.selectors()) |
|
| 976 | 1180 | } |
| 1021 | 1225 | Brain::reset(self.repository.clone(), base, &self.review) |
|
| 1022 | 1226 | } |
|
| 1023 | 1227 | ||
| 1024 | 1228 | fn rebase_brain(&self) -> Result<Brain, Error> { |
|
| 1025 | 1229 | let base = self.jj.resolve(&self.review.base)?; |
|
| 1026 | - | let documents = self.documents()?; |
|
| 1027 | - | Brain::rebase(self.repository.clone(), base, &self.review, &documents) |
|
| 1230 | + | let commits = self.commits()?; |
|
| 1231 | + | let documents = commits |
|
| 1232 | + | .iter() |
|
| 1233 | + | .map(|commit| Ok(self.commit_diff(commit)?.split_hunks())) |
|
| 1234 | + | .collect::<Result<Vec<_>, Error>>()?; |
|
| 1235 | + | Brain::rebase( |
|
| 1236 | + | self.repository.clone(), |
|
| 1237 | + | base, |
|
| 1238 | + | &self.review, |
|
| 1239 | + | &commits, |
|
| 1240 | + | &documents, |
|
| 1241 | + | ) |
|
| 1028 | 1242 | } |
|
| 1029 | 1243 | ||
| 1030 | 1244 | fn repo(&self, commit: &Commit) -> git::Repository { |
|
| 1031 | 1245 | self.repository.with_selector_args(commit.selectors()) |
|
| 1032 | 1246 | } |
| 1034 | 1248 | ||
| 1035 | 1249 | #[cfg(test)] |
|
| 1036 | 1250 | mod tests { |
|
| 1037 | 1251 | use super::*; |
|
| 1038 | 1252 | ||
| 1039 | - | /// Returns a set of hunk ids from raw indexes. |
|
| 1040 | - | fn hunk_set(ids: impl IntoIterator<Item = usize>) -> BTreeSet<HunkId> { |
|
| 1041 | - | ids.into_iter().map(HunkId::new).collect() |
|
| 1253 | + | /// Returns an accepted identity for one test commit and hunk. |
|
| 1254 | + | fn accepted_hunk(commit: &str, patch: &str, ordinal: u32, total: u32) -> AcceptedHunk { |
|
| 1255 | + | AcceptedHunk { |
|
| 1256 | + | commit: commit.parse().unwrap(), |
|
| 1257 | + | patch_id: PatchId::from(patch.to_owned()), |
|
| 1258 | + | ordinal, |
|
| 1259 | + | commit_hunks: total, |
|
| 1260 | + | } |
|
| 1042 | 1261 | } |
|
| 1043 | 1262 | ||
| 1044 | 1263 | #[test] |
|
| 1045 | - | fn accepted_hunks_from_patch_ids_excludes_residual_patches() { |
|
| 1046 | - | let original = BTreeMap::from([ |
|
| 1047 | - | (HunkId::new(0), "alpha"), |
|
| 1048 | - | (HunkId::new(1), "beta"), |
|
| 1049 | - | (HunkId::new(2), "gamma"), |
|
| 1264 | + | fn accepted_state_roundtrips_through_commit_message() { |
|
| 1265 | + | let accepted = Accepted::from([ |
|
| 1266 | + | accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 2), |
|
| 1267 | + | accepted_hunk("1111111111111111111111111111111111111111", "beta", 0, 2), |
|
| 1050 | 1268 | ]); |
|
| 1051 | - | let residual = BTreeSet::from(["beta"]); |
|
| 1052 | - | let accepted = accepted_hunks_from_patch_ids(&original, &residual); |
|
| 1269 | + | let message = encode_state(&accepted); |
|
| 1053 | 1270 | ||
| 1054 | - | assert_eq!(accepted, hunk_set([0, 2])); |
|
| 1271 | + | assert_eq!(decode_state(&message), Some(accepted)); |
|
| 1272 | + | assert_eq!(decode_state(SYNTHETIC_BRAIN_MESSAGE), None); |
|
| 1055 | 1273 | } |
|
| 1056 | 1274 | ||
| 1057 | 1275 | #[test] |
|
| 1058 | - | fn accepted_hunks_from_patch_ids_accepts_all_when_residual_is_empty() { |
|
| 1059 | - | let original = BTreeMap::from([(HunkId::new(0), 10), (HunkId::new(1), 20)]); |
|
| 1060 | - | let residual = BTreeSet::new(); |
|
| 1061 | - | let accepted = accepted_hunks_from_patch_ids(&original, &residual); |
|
| 1276 | + | fn empty_accepted_state_roundtrips_through_commit_message() { |
|
| 1277 | + | let message = encode_state(&Accepted::new()); |
|
| 1278 | + | ||
| 1279 | + | assert_eq!(decode_state(&message), Some(Accepted::new())); |
|
| 1280 | + | // Git terminates `%B` output with its own newline. |
|
| 1281 | + | assert_eq!(decode_state(&format!("{message}\n")), Some(Accepted::new())); |
|
| 1282 | + | } |
|
| 1283 | + | ||
| 1284 | + | #[test] |
|
| 1285 | + | fn accepted_state_rejects_inconsistent_hunk_totals() { |
|
| 1286 | + | let commit = "1111111111111111111111111111111111111111"; |
|
| 1287 | + | let inconsistent = format!( |
|
| 1288 | + | "{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n{commit} alpha 0 2\n{commit} beta 0 3\n" |
|
| 1289 | + | ); |
|
| 1290 | + | let zero = format!("{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n{commit} alpha 0 0\n"); |
|
| 1291 | + | let duplicate = format!( |
|
| 1292 | + | "{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n{commit} alpha 0 1\n{commit} alpha 0 1\n" |
|
| 1293 | + | ); |
|
| 1294 | + | ||
| 1295 | + | assert_eq!(decode_state(&inconsistent), None); |
|
| 1296 | + | assert_eq!(decode_state(&zero), None); |
|
| 1297 | + | assert_eq!(decode_state(&duplicate), None); |
|
| 1298 | + | } |
|
| 1299 | + | ||
| 1300 | + | #[test] |
|
| 1301 | + | fn accepted_state_rejects_malformed_payload() { |
|
| 1302 | + | let message = format!( |
|
| 1303 | + | "{SYNTHETIC_BRAIN_MESSAGE}\n\n{ACCEPTED_SECTION}\n{} alpha 0 1 extra\n", |
|
| 1304 | + | "1111111111111111111111111111111111111111" |
|
| 1305 | + | ); |
|
| 1306 | + | ||
| 1307 | + | assert_eq!(decode_state(&message), None); |
|
| 1308 | + | } |
|
| 1309 | + | ||
| 1310 | + | #[test] |
|
| 1311 | + | fn reconciliation_uses_exact_accepted_identities() { |
|
| 1312 | + | let first = accepted_hunk("1111111111111111111111111111111111111111", "change", 0, 1); |
|
| 1313 | + | let second = accepted_hunk("2222222222222222222222222222222222222222", "restore", 0, 1); |
|
| 1314 | + | let first_hunks = BTreeMap::from([(HunkId::new(0), first.clone())]); |
|
| 1315 | + | let second_hunks = BTreeMap::from([(HunkId::new(0), second.clone())]); |
|
| 1316 | + | let commits = [ |
|
| 1317 | + | CommitHunks { |
|
| 1318 | + | commit: first.commit, |
|
| 1319 | + | hunks: Some(&first_hunks), |
|
| 1320 | + | }, |
|
| 1321 | + | CommitHunks { |
|
| 1322 | + | commit: second.commit, |
|
| 1323 | + | hunks: Some(&second_hunks), |
|
| 1324 | + | }, |
|
| 1325 | + | ]; |
|
| 1326 | + | ||
| 1327 | + | let fresh = Reconciled::for_commits(&Accepted::new(), &commits); |
|
| 1328 | + | assert!(fresh.iter().all(|state| state.accepted.is_empty())); |
|
| 1329 | + | assert!(fresh.iter().all(|state| !state.reviewed)); |
|
| 1330 | + | ||
| 1331 | + | let remaining = Reconciled::for_commits(&Accepted::from([second]), &commits); |
|
| 1332 | + | assert!(remaining[0].accepted.is_empty()); |
|
| 1333 | + | assert_eq!(remaining[1].accepted, BTreeSet::from([HunkId::new(0)])); |
|
| 1334 | + | assert!(remaining[1].reviewed); |
|
| 1335 | + | } |
|
| 1336 | + | ||
| 1337 | + | #[test] |
|
| 1338 | + | fn reconciliation_marks_undecoded_commits_from_persisted_totals() { |
|
| 1339 | + | let first = accepted_hunk("1111111111111111111111111111111111111111", "alpha", 0, 2); |
|
| 1340 | + | let second = accepted_hunk("1111111111111111111111111111111111111111", "beta", 0, 2); |
|
| 1341 | + | let commits = [CommitHunks { |
|
| 1342 | + | commit: first.commit, |
|
| 1343 | + | hunks: None, |
|
| 1344 | + | }]; |
|
| 1345 | + | ||
| 1346 | + | let partial = Reconciled::for_commits(&Accepted::from([first.clone()]), &commits); |
|
| 1347 | + | assert!(!partial[0].reviewed); |
|
| 1348 | + | assert!(partial[0].accepted.is_empty()); |
|
| 1349 | + | ||
| 1350 | + | let full = Reconciled::for_commits(&Accepted::from([first, second]), &commits); |
|
| 1351 | + | assert!(full[0].reviewed); |
|
| 1352 | + | assert!(full[0].accepted.is_empty()); |
|
| 1353 | + | } |
|
| 1354 | + | ||
| 1355 | + | #[test] |
|
| 1356 | + | fn rebase_remaps_within_a_commit_before_across_commits() { |
|
| 1357 | + | let moved = accepted_hunk("1111111111111111111111111111111111111111", "same", 0, 1); |
|
| 1358 | + | // The commit still exists, but gained a hunk, so its stored identity no |
|
| 1359 | + | // longer matches exactly. |
|
| 1360 | + | let kept = accepted_hunk("2222222222222222222222222222222222222222", "same", 0, 1); |
|
| 1361 | + | let stored = Accepted::from([kept.clone()]); |
|
| 1362 | + | let elsewhere = accepted_hunk("3333333333333333333333333333333333333333", "same", 0, 1); |
|
| 1363 | + | let same_commit = AcceptedHunk { |
|
| 1364 | + | commit_hunks: 2, |
|
| 1365 | + | ..kept |
|
| 1366 | + | }; |
|
| 1367 | + | let current = [elsewhere, same_commit.clone()]; |
|
| 1368 | + | ||
| 1369 | + | let remapped = AcceptedHunk::remap(&stored, ¤t); |
|
| 1370 | + | ||
| 1371 | + | assert_eq!(remapped, Accepted::from([same_commit])); |
|
| 1372 | + | // With no same-commit candidate, the patch id alone carries acceptance. |
|
| 1373 | + | let remapped = AcceptedHunk::remap(&stored, [&moved]); |
|
| 1374 | + | assert_eq!(remapped, Accepted::from([moved])); |
|
| 1375 | + | } |
|
| 1376 | + | ||
| 1377 | + | #[test] |
|
| 1378 | + | fn rebase_remaps_duplicate_patch_ids_by_occurrence() { |
|
| 1379 | + | let stored = Accepted::from([ |
|
| 1380 | + | accepted_hunk("1111111111111111111111111111111111111111", "same", 0, 2), |
|
| 1381 | + | accepted_hunk("1111111111111111111111111111111111111111", "same", 1, 2), |
|
| 1382 | + | ]); |
|
| 1383 | + | let first = accepted_hunk("2222222222222222222222222222222222222222", "same", 0, 3); |
|
| 1384 | + | let second = accepted_hunk("2222222222222222222222222222222222222222", "same", 1, 3); |
|
| 1385 | + | let third = accepted_hunk("2222222222222222222222222222222222222222", "same", 2, 3); |
|
| 1386 | + | let current = [first.clone(), second.clone(), third]; |
|
| 1387 | + | ||
| 1388 | + | let remapped = AcceptedHunk::remap(&stored, ¤t); |
|
| 1062 | 1389 | ||
| 1063 | - | assert_eq!(accepted, hunk_set([0, 1])); |
|
| 1390 | + | assert_eq!(remapped, Accepted::from([first, second])); |
|
| 1064 | 1391 | } |
|
| 1065 | 1392 | ||
| 1066 | 1393 | #[test] |
|
| 1067 | 1394 | fn review_identity_roundtrips_through_ref() { |
|
| 1068 | 1395 | let base = Rev::try_from("HEAD^^^^").unwrap(); |
| 1078 | 1405 | "refs/brain/state/range/HEAD%5e%5e%5e%5e/HEAD" |
|
| 1079 | 1406 | ); |
|
| 1080 | 1407 | } |
|
| 1081 | 1408 | ||
| 1082 | 1409 | #[test] |
|
| 1083 | - | fn review_identity_ignores_unrecognized_refs() { |
|
| 1410 | + | fn review_identity_rejects_unrecognized_refs() { |
|
| 1084 | 1411 | let prefix = Brain::prefix_for(STATE_REF_NAMESPACE).unwrap(); |
|
| 1085 | - | let legacy = prefix.join(component("HEAD".to_owned()).unwrap()); |
|
| 1412 | + | let unrecognized = prefix.join(component("HEAD".to_owned()).unwrap()); |
|
| 1086 | 1413 | ||
| 1087 | - | assert_eq!(ReviewIdentity::from_ref(&prefix, &legacy), None); |
|
| 1414 | + | assert_eq!(ReviewIdentity::from_ref(&prefix, &unrecognized), None); |
|
| 1088 | 1415 | } |
|
| 1089 | 1416 | ||
| 1090 | 1417 | #[test] |
|
| 1091 | 1418 | fn hunk_identity_patch_omits_context_lines() { |
|
| 1092 | 1419 | let document = DiffDocument::decode_str( |
f
+0 -0
crates/brain/src/decorate.rs
+1 -14
| 24 | 24 | const ACCEPTED_MARK: char = 'โ'; |
|
| 25 | 25 | /// Vertical rule drawn in the gutter beside accepted hunks: โ. |
|
| 26 | 26 | const ACCEPTED_GUTTER: char = 'โ'; |
|
| 27 | 27 | /// Marker drawn beside a hunk that has comments: ๐ฉ. |
|
| 28 | 28 | const COMMENT_MARK: char = '๐ฉ'; |
|
| 29 | - | /// Marker drawn beside a hunk that was pending after a review rebase. |
|
| 30 | - | const REBASE_PENDING_MARK: char = 'โป'; |
|
| 31 | 29 | ||
| 32 | 30 | /// Immutable decoration snapshot of one commit's review state. |
|
| 33 | 31 | #[derive(Clone, Debug)] |
|
| 34 | 32 | pub struct Decorations { |
|
| 35 | 33 | /// Hunks accepted at snapshot time. |
|
| 36 | 34 | accepted: BTreeSet<HunkId>, |
|
| 37 | - | /// Pending hunks that were accepted before a review rebase. |
|
| 38 | - | rebase_pending: BTreeSet<HunkId>, |
|
| 39 | 35 | /// Per-hunk comment counts at snapshot time. |
|
| 40 | 36 | comments: BTreeMap<HunkId, usize>, |
|
| 41 | 37 | /// Original hunk ids for each file in the commit. |
|
| 42 | 38 | file_hunks: BTreeMap<FileId, Vec<HunkId>>, |
|
| 43 | 39 | /// Original addition and deletion counts for each hunk. |
| 55 | 51 | hunk_stats: &BTreeMap<HunkId, FileStats>, |
|
| 56 | 52 | palette: DiffPalette, |
|
| 57 | 53 | ) -> Self { |
|
| 58 | 54 | Self { |
|
| 59 | 55 | accepted: review.accepted().clone(), |
|
| 60 | - | rebase_pending: review.rebase_pending().clone(), |
|
| 61 | 56 | comments: comments.counts(), |
|
| 62 | 57 | file_hunks: file_hunks.clone(), |
|
| 63 | 58 | hunk_stats: hunk_stats.clone(), |
|
| 64 | 59 | palette, |
|
| 65 | 60 | } |
| 108 | 103 | decoration |
|
| 109 | 104 | } |
|
| 110 | 105 | ||
| 111 | 106 | fn hunk(&self, _file: FileId, hunk: HunkId) -> HunkDecoration { |
|
| 112 | 107 | let accepted = self.accepted.contains(&hunk); |
|
| 113 | - | let rebase_pending = self.rebase_pending.contains(&hunk); |
|
| 114 | 108 | let comments = self.comments.get(&hunk).copied().unwrap_or_default(); |
|
| 115 | - | if !accepted && !rebase_pending && comments == 0 { |
|
| 109 | + | if !accepted && comments == 0 { |
|
| 116 | 110 | return HunkDecoration::default(); |
|
| 117 | 111 | } |
|
| 118 | 112 | ||
| 119 | 113 | let mut corner = Line::blank(); |
|
| 120 | - | if rebase_pending { |
|
| 121 | - | corner = corner.item(Label::from_char(REBASE_PENDING_MARK).fg(colors::rgb::ORANGE)); |
|
| 122 | - | } |
|
| 123 | 114 | if comments > 0 { |
|
| 124 | - | if rebase_pending { |
|
| 125 | - | corner = corner.item(Label::space()); |
|
| 126 | - | } |
|
| 127 | 115 | corner = |
|
| 128 | 116 | corner.item(Label::new(&format!("{comments} {COMMENT_MARK}")).fg(colors::rgb::DIM)); |
|
| 129 | 117 | } |
|
| 130 | 118 | ||
| 131 | 119 | HunkDecoration { |
| 144 | 132 | fn file_diffstat_excludes_accepted_hunks() { |
|
| 145 | 133 | let first = HunkId::new(0); |
|
| 146 | 134 | let second = HunkId::new(1); |
|
| 147 | 135 | let decorations = Decorations { |
|
| 148 | 136 | accepted: BTreeSet::from([first]), |
|
| 149 | - | rebase_pending: BTreeSet::new(), |
|
| 150 | 137 | comments: BTreeMap::new(), |
|
| 151 | 138 | file_hunks: BTreeMap::from([(FileId::new(0), vec![first, second])]), |
|
| 152 | 139 | hunk_stats: BTreeMap::from([ |
|
| 153 | 140 | ( |
|
| 154 | 141 | first, |
crates/brain/src/error.rs
+6 -0
| 21 | 21 | /// Base commit recorded by the persisted state commit. |
|
| 22 | 22 | stored_base: Oid, |
|
| 23 | 23 | /// Base commit requested by the current review. |
|
| 24 | 24 | current_base: Oid, |
|
| 25 | 25 | }, |
|
| 26 | + | /// Persisted review state is not valid. |
|
| 27 | + | InvalidReviewState, |
|
| 26 | 28 | /// Diff parsing failed. |
|
| 27 | 29 | Parse(DecodeError), |
|
| 28 | 30 | /// Highlighting asset setup failed, carrying the backend message. |
|
| 29 | 31 | Highlight(String), |
|
| 30 | 32 | /// The command-line arguments were invalid, carrying a usage message. |
| 56 | 58 | match error { |
|
| 57 | 59 | RepoError::Io(e) => Self::Io(e), |
|
| 58 | 60 | RepoError::Status(code) => Self::Backend(code), |
|
| 59 | 61 | RepoError::Git(msg) => Self::Git(msg), |
|
| 60 | 62 | RepoError::MergeConflict(msg) => Self::MergeConflict(msg), |
|
| 63 | + | RepoError::PatchApply(msg) => Self::Git(msg), |
|
| 61 | 64 | } |
|
| 62 | 65 | } |
|
| 63 | 66 | } |
|
| 64 | 67 | ||
| 65 | 68 | impl std::fmt::Display for Error { |
| 74 | 77 | current_base, |
|
| 75 | 78 | } => write!( |
|
| 76 | 79 | f, |
|
| 77 | 80 | "stored review state is for base {stored_base}, but current base is {current_base}" |
|
| 78 | 81 | ), |
|
| 82 | + | Self::InvalidReviewState => { |
|
| 83 | + | f.write_str("stored review state is invalid; reset the review to continue") |
|
| 84 | + | } |
|
| 79 | 85 | Self::Parse(error) => write!(f, "{error}"), |
|
| 80 | 86 | Self::Highlight(error) => write!(f, "{error}"), |
|
| 81 | 87 | Self::Usage(message) => write!(f, "{message}"), |
|
| 82 | 88 | Self::Empty => write!(f, "no changes to review between base and target"), |
|
| 83 | 89 | } |
crates/brain/src/review.rs
+0 -13
| 22 | 22 | /// Per-hunk acceptance state for one commit. |
|
| 23 | 23 | #[derive(Clone, Debug, Default)] |
|
| 24 | 24 | pub struct Review { |
|
| 25 | 25 | /// Hunks the reviewer has accepted. |
|
| 26 | 26 | accepted: BTreeSet<HunkId>, |
|
| 27 | - | /// Pending hunks that were accepted before a review rebase. |
|
| 28 | - | rebase_pending: BTreeSet<HunkId>, |
|
| 29 | 27 | } |
|
| 30 | 28 | ||
| 31 | 29 | impl Review { |
|
| 32 | 30 | /// Creates empty review state with no accepted hunks. |
|
| 33 | 31 | pub fn new() -> Self { |
| 42 | 40 | /// Returns the set of accepted hunks. |
|
| 43 | 41 | pub fn accepted(&self) -> &BTreeSet<HunkId> { |
|
| 44 | 42 | &self.accepted |
|
| 45 | 43 | } |
|
| 46 | 44 | ||
| 47 | - | /// Returns the hunks that need review after a review rebase. |
|
| 48 | - | pub fn rebase_pending(&self) -> &BTreeSet<HunkId> { |
|
| 49 | - | &self.rebase_pending |
|
| 50 | - | } |
|
| 51 | - | ||
| 52 | - | /// Marks `hunk` as needing review after a review rebase. |
|
| 53 | - | pub fn mark_rebase_pending(&mut self, hunk: HunkId) { |
|
| 54 | - | self.rebase_pending.insert(hunk); |
|
| 55 | - | } |
|
| 56 | - | ||
| 57 | 45 | /// Replaces the accepted hunk set. |
|
| 58 | 46 | pub fn replace(&mut self, accepted: BTreeSet<HunkId>) { |
|
| 59 | - | self.rebase_pending.retain(|hunk| !accepted.contains(hunk)); |
|
| 60 | 47 | self.accepted = accepted; |
|
| 61 | 48 | } |
|
| 62 | 49 | ||
| 63 | 50 | /// Returns whether every hunk in `hunks` has been accepted. |
|
| 64 | 51 | pub fn accepts_all(&self, hunks: impl IntoIterator<Item = HunkId>) -> bool { |
crates/brain/src/session.rs
+36 -25
| 4 | 4 | use std::io; |
|
| 5 | 5 | use std::mem; |
|
| 6 | 6 | use std::sync::mpsc::{self, Receiver, Sender}; |
|
| 7 | 7 | ||
| 8 | 8 | use rustik_diff::{ |
|
| 9 | - | ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffViewer, Encode as _, |
|
| 10 | - | FileDiff, FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ReviewProgress, |
|
| 11 | - | ViewChange, spawn_highlighter, |
|
| 9 | + | ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffViewer, FileDiff, |
|
| 10 | + | FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ReviewProgress, ViewChange, |
|
| 11 | + | spawn_highlighter, |
|
| 12 | 12 | }; |
|
| 13 | 13 | use rustik_repo::DiffStat; |
|
| 14 | 14 | use rustik_tui::{Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, Terminal}; |
|
| 15 | 15 | use rustik_tui_termion as tui_termion; |
|
| 16 | 16 | ||
| 17 | - | use crate::backend::{Backend, Brain, Commit, CommitHunks}; |
|
| 17 | + | use crate::backend::{Backend, Brain, Commit, CommitHunks, FilePatches}; |
|
| 18 | 18 | use crate::comments::ReviewComments; |
|
| 19 | 19 | use crate::error::Error; |
|
| 20 | 20 | use crate::review::Visibility; |
|
| 21 | 21 | ||
| 22 | 22 | mod commit; |
| 179 | 179 | list: ListState, |
|
| 180 | 180 | /// Viewer options used to build commit and per-hunk viewers. |
|
| 181 | 181 | options: DiffOptions, |
|
| 182 | 182 | /// Revision backend used for lazy commit loads and context refetches. |
|
| 183 | 183 | backend: Box<dyn Backend>, |
|
| 184 | - | /// Hidden review state storing accepted content and comments. |
|
| 184 | + | /// Hidden review state storing accepted identities, derived content, and comments. |
|
| 185 | 185 | brain: Brain, |
|
| 186 | 186 | /// Review-wide persistent comment store. |
|
| 187 | 187 | comments: ReviewComments, |
|
| 188 | 188 | /// Sender used to respawn the highlighter for the current commit. |
|
| 189 | 189 | events_tx: Sender<TerminalEvent>, |
| 354 | 354 | ||
| 355 | 355 | let newly_loaded = self.commits[index].loaded.is_none(); |
|
| 356 | 356 | self.current()?; |
|
| 357 | 357 | ||
| 358 | 358 | if newly_loaded { |
|
| 359 | - | // Classify the freshly decoded hunks against the accepted tree. |
|
| 359 | + | // Project exact acceptance onto the freshly decoded hunks. |
|
| 360 | 360 | self.reconcile_reviews()?; |
|
| 361 | 361 | } |
|
| 362 | 362 | self.activate()?; |
|
| 363 | 363 | if newly_loaded { |
|
| 364 | 364 | self.focus_initial_hunk(viewer_area(self.terminal.area()))?; |
| 403 | 403 | } |
|
| 404 | 404 | } |
|
| 405 | 405 | ||
| 406 | 406 | /// Persists acceptance of the focused hunk, or focuses one when none is. |
|
| 407 | 407 | /// |
|
| 408 | - | /// Accepting updates the hidden tree first, then rebuilds all per-commit |
|
| 409 | - | /// accepted hunk sets from that tree. The visible commit state is derived |
|
| 410 | - | /// rather than patched locally so overlapping commits stay consistent. |
|
| 408 | + | /// Acceptance updates exact persisted identity state before reconciliation. |
|
| 411 | 409 | fn toggle_focused_hunk(&mut self, area: Rect) -> Result<(), Error> { |
|
| 412 | 410 | let loaded = self.current()?; |
|
| 413 | 411 | let Some(DiffFocus::Hunk(hunk)) = loaded.viewer.state().focus else { |
|
| 414 | 412 | // No hunk is focused yet: move focus to the first hunk so the next |
|
| 415 | 413 | // toggle has an unambiguous target. |
| 417 | 415 | return Ok(()); |
|
| 418 | 416 | }; |
|
| 419 | 417 | let Some(patch) = loaded.hunk_patches.get(&hunk).cloned() else { |
|
| 420 | 418 | return Ok(()); |
|
| 421 | 419 | }; |
|
| 420 | + | let Some(identity) = loaded.identities.get(&hunk).cloned() else { |
|
| 421 | + | return Ok(()); |
|
| 422 | + | }; |
|
| 422 | 423 | let accepted = loaded.review.is_accepted(hunk); |
|
| 423 | 424 | if accepted { |
|
| 424 | 425 | self.reject_hunks(BTreeSet::from([(self.current, hunk)]))?; |
|
| 425 | 426 | } else { |
|
| 426 | - | self.brain.apply_patches([patch.as_str()])?; |
|
| 427 | + | self.brain.accept([(identity, patch)])?; |
|
| 427 | 428 | } |
|
| 428 | 429 | self.reconcile_reviews()?; |
|
| 429 | 430 | if !accepted && !self.visibility.show_accepted { |
|
| 430 | 431 | self.current()?.viewer.apply(DiffAction::NextHunk, area); |
|
| 431 | 432 | } |
| 443 | 444 | let Some(file) = loaded.files.iter().find(|candidate| candidate.id == file) else { |
|
| 444 | 445 | return Ok(()); |
|
| 445 | 446 | }; |
|
| 446 | 447 | let hunk_ids = file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>(); |
|
| 447 | 448 | let accepted = loaded.review.accepts_all(hunk_ids.iter().copied()); |
|
| 448 | - | let patches = hunk_ids |
|
| 449 | + | let hunks = hunk_ids |
|
| 449 | 450 | .iter() |
|
| 450 | 451 | .copied() |
|
| 451 | 452 | .filter(|hunk| loaded.review.is_accepted(*hunk) == accepted) |
|
| 452 | - | .filter_map(|hunk| loaded.hunk_patches.get(&hunk).cloned()) |
|
| 453 | + | .filter_map(|hunk| { |
|
| 454 | + | let identity = loaded.identities.get(&hunk)?.clone(); |
|
| 455 | + | let patch = loaded.hunk_patches.get(&hunk)?.clone(); |
|
| 456 | + | Some((identity, patch)) |
|
| 457 | + | }) |
|
| 453 | 458 | .collect::<Vec<_>>(); |
|
| 454 | 459 | if accepted { |
|
| 455 | 460 | let rejected = hunk_ids |
|
| 456 | 461 | .into_iter() |
|
| 457 | 462 | .map(|hunk| (self.current, hunk)) |
|
| 458 | 463 | .collect(); |
|
| 459 | 464 | self.reject_hunks(rejected)?; |
|
| 460 | 465 | } else { |
|
| 461 | - | self.brain |
|
| 462 | - | .apply_patches(patches.iter().map(String::as_str))?; |
|
| 466 | + | self.brain.accept(hunks)?; |
|
| 463 | 467 | } |
|
| 464 | 468 | self.reconcile_reviews()?; |
|
| 465 | 469 | Ok(()) |
|
| 466 | 470 | } |
|
| 467 | 471 |
| 472 | 476 | ) -> Result<(), Error> { |
|
| 473 | 477 | for index in 0..self.commits.len() { |
|
| 474 | 478 | self.load(index)?; |
|
| 475 | 479 | } |
|
| 476 | 480 | self.reconcile_reviews()?; |
|
| 481 | + | let mut rejected_identities = BTreeSet::new(); |
|
| 482 | + | for (index, hunk) in &rejected { |
|
| 483 | + | let Some(loaded) = &self.commits[*index].loaded else { |
|
| 484 | + | continue; |
|
| 485 | + | }; |
|
| 486 | + | if let Some(identity) = loaded.identities.get(hunk) { |
|
| 487 | + | rejected_identities.insert(identity.clone()); |
|
| 488 | + | } |
|
| 489 | + | } |
|
| 477 | 490 | let mut patches = Vec::new(); |
|
| 478 | 491 | for (index, slot) in self.commits.iter().enumerate() { |
|
| 479 | 492 | let Some(loaded) = &slot.loaded else { |
|
| 480 | 493 | continue; |
|
| 481 | 494 | }; |
| 487 | 500 | loaded.review.is_accepted(hunk.id) && !rejected.contains(&(index, hunk.id)) |
|
| 488 | 501 | }) |
|
| 489 | 502 | .cloned() |
|
| 490 | 503 | .collect::<Vec<_>>(); |
|
| 491 | 504 | if !hunks.is_empty() { |
|
| 492 | - | patches.push(DiffDocument::for_hunks(file, hunks).to_unified_string()?); |
|
| 505 | + | patches.push(FilePatches::new(file, hunks)?); |
|
| 493 | 506 | } |
|
| 494 | 507 | } |
|
| 495 | 508 | } |
|
| 496 | - | self.brain |
|
| 497 | - | .replace_patches(patches.iter().map(String::as_str)) |
|
| 509 | + | self.brain.reject(&rejected_identities, patches) |
|
| 498 | 510 | } |
|
| 499 | 511 | ||
| 500 | 512 | /// Opens the hunk view for the focused hunk to author a comment. |
|
| 501 | 513 | fn enter_hunk_view(&mut self, area: Rect) -> Result<(), Error> { |
|
| 502 | 514 | if !matches!( |
| 805 | 817 | loaded.viewer.replace_file_diffs_anchored(files, area); |
|
| 806 | 818 | ||
| 807 | 819 | Ok(()) |
|
| 808 | 820 | } |
|
| 809 | 821 | ||
| 810 | - | /// Reconciles per-commit review state from the hidden tree. |
|
| 822 | + | /// Reconciles per-commit review state from exact accepted identities. |
|
| 811 | 823 | /// |
|
| 812 | 824 | /// This is the only place that replaces `Review` sets and reviewed marks. |
|
| 813 | - | /// Keeping it as a full recomputation avoids subtle drift between the |
|
| 814 | - | /// persistent accepted tree, the current commit list, and per-viewer |
|
| 815 | - | /// decorations. Commits that have not been decoded yet still receive their |
|
| 816 | - | /// reviewed mark, which needs no hunk data. |
|
| 825 | + | /// Keeping it as a full recomputation keeps the persisted accepted set, |
|
| 826 | + | /// current commit list, and per-viewer decorations consistent. Persisted |
|
| 827 | + | /// hunk totals provide the reviewed mark for commits not yet decoded. |
|
| 817 | 828 | fn reconcile_reviews(&mut self) -> Result<(), Error> { |
|
| 818 | 829 | let commits = self |
|
| 819 | 830 | .commits |
|
| 820 | 831 | .iter() |
|
| 821 | 832 | .map(|slot| CommitHunks { |
|
| 822 | - | commit: &slot.commit, |
|
| 823 | - | hunks: slot.loaded.as_ref().map(|loaded| &loaded.patch_ids), |
|
| 833 | + | commit: slot.commit.id, |
|
| 834 | + | hunks: slot.loaded.as_ref().map(|loaded| &loaded.identities), |
|
| 824 | 835 | }) |
|
| 825 | 836 | .collect::<Vec<_>>(); |
|
| 826 | - | let reconciled = self.brain.reconcile(&commits)?; |
|
| 837 | + | let reconciled = self.brain.reconcile(&commits); |
|
| 827 | 838 | for (slot, reconciled) in self.commits.iter_mut().zip(reconciled) { |
|
| 828 | 839 | slot.reviewed = reconciled.reviewed; |
|
| 829 | 840 | if let Some(loaded) = &mut slot.loaded { |
|
| 830 | 841 | loaded.review.replace(reconciled.accepted); |
|
| 831 | 842 | loaded.refresh_decorations(); |
crates/brain/src/session/commit.rs
+20 -19
| 4 | 4 | ||
| 5 | 5 | use rustik_diff::{ |
|
| 6 | 6 | ContextUpdate, DiffDocument, DiffOptions, DiffViewer, Encode as _, FileDiff, FileId, FileStats, |
|
| 7 | 7 | HunkId, |
|
| 8 | 8 | }; |
|
| 9 | - | use rustik_repo::{DiffStat, PatchId}; |
|
| 9 | + | use rustik_repo::DiffStat; |
|
| 10 | 10 | use rustik_tui::Rect; |
|
| 11 | 11 | ||
| 12 | - | use crate::backend::{Brain, Commit}; |
|
| 12 | + | use crate::backend::{AcceptedHunk, Brain, Commit}; |
|
| 13 | 13 | use crate::comments::{CommentTarget, Comments, ReviewComments}; |
|
| 14 | 14 | use crate::decorate::Decorations; |
|
| 15 | 15 | use crate::error::Error; |
|
| 16 | 16 | use crate::review::Review; |
|
| 17 | 17 | ||
| 18 | 18 | /// One commit in the reviewed range: header data plus lazily decoded state. |
|
| 19 | 19 | pub(super) struct CommitSlot { |
|
| 20 | 20 | /// Commit under review. |
|
| 21 | 21 | pub(super) commit: Commit, |
|
| 22 | - | /// Whether the hidden tree contains this commit's entire diff. |
|
| 22 | + | /// Whether every hunk in this commit is accepted. |
|
| 23 | 23 | /// |
|
| 24 | - | /// Derived by [`crate::session::Session::reconcile_reviews`] from tree |
|
| 25 | - | /// state alone, so the commit list can mark reviewed commits before they |
|
| 26 | - | /// are decoded. |
|
| 24 | + | /// Persisted hunk totals let the commit list mark reviewed commits before |
|
| 25 | + | /// they are decoded. |
|
| 27 | 26 | pub(super) reviewed: bool, |
|
| 28 | 27 | /// Decoded diff state, populated when the commit is first displayed. |
|
| 29 | 28 | pub(super) loaded: Option<CommitReview>, |
|
| 30 | 29 | } |
|
| 31 | 30 |
| 36 | 35 | /// persist across commit switches, and its own [`Review`] because decoded hunk |
|
| 37 | 36 | /// ids restart per commit. |
|
| 38 | 37 | pub(super) struct CommitReview { |
|
| 39 | 38 | /// Viewer rendering this commit's diff, owning its caches. |
|
| 40 | 39 | pub(super) viewer: DiffViewer, |
|
| 41 | - | /// Accepted-hunk state, reconciled from the hidden tree. |
|
| 40 | + | /// Accepted-hunk state projected from exact persisted identities. |
|
| 42 | 41 | pub(super) review: Review, |
|
| 43 | 42 | /// Per-hunk comment view for this commit. |
|
| 44 | 43 | pub(super) comments: Comments, |
|
| 45 | 44 | /// Single-hunk patch text keyed by hunk id. |
|
| 46 | 45 | pub(super) hunk_patches: BTreeMap<HunkId, String>, |
|
| 47 | - | /// Stable patch id of each original hunk, computed once at load. |
|
| 48 | - | pub(super) patch_ids: BTreeMap<HunkId, PatchId>, |
|
| 46 | + | /// Exact accepted-state identity of each original hunk. |
|
| 47 | + | pub(super) identities: BTreeMap<HunkId, AcceptedHunk>, |
|
| 49 | 48 | /// Full, unfiltered file diffs used to restore hidden hunks. |
|
| 50 | 49 | pub(super) files: Vec<FileDiff>, |
|
| 51 | 50 | /// Original hunk ids per file, used for decoration snapshots. |
|
| 52 | 51 | pub(super) file_hunks: BTreeMap<FileId, Vec<HunkId>>, |
|
| 53 | 52 | /// Original diff stats per hunk, used for file-level remaining diffstats. |
| 90 | 89 | ) -> Result<Self, Error> { |
|
| 91 | 90 | let document = document.split_hunks(); |
|
| 92 | 91 | let mut viewer = DiffViewer::new(document, options); |
|
| 93 | 92 | viewer.load_file_locs(|oid| brain.read_blob(oid))?; |
|
| 94 | 93 | let files = viewer.document().files.clone(); |
|
| 94 | + | let identities = brain.hunk_identities(viewer.document(), commit.id)?; |
|
| 95 | 95 | let heading = format!("{} {}", commit.id.short(), commit.summary); |
|
| 96 | 96 | let mut hunk_patches = BTreeMap::new(); |
|
| 97 | - | let mut patch_ids = BTreeMap::new(); |
|
| 98 | - | let mut review = Review::new(); |
|
| 97 | + | let review = Review::new(); |
|
| 99 | 98 | let mut targets = BTreeMap::new(); |
|
| 100 | 99 | let mut file_hunks = BTreeMap::new(); |
|
| 101 | 100 | let mut hunk_stats = BTreeMap::new(); |
|
| 102 | 101 | ||
| 103 | 102 | for file in &files { |
| 107 | 106 | file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>(), |
|
| 108 | 107 | ); |
|
| 109 | 108 | for hunk in &file.hunks { |
|
| 110 | 109 | hunk_stats.insert(hunk.id, hunk.stats()); |
|
| 111 | 110 | let patch = DiffDocument::for_hunks(file, [hunk.clone()]).to_unified_string()?; |
|
| 112 | - | let patch_id = brain.hunk_patch_id(file, hunk)?; |
|
| 111 | + | // `hunk_identities` covers every hunk of the same document, so |
|
| 112 | + | // a miss is a bug: the hunk could never be accepted or |
|
| 113 | + | // commented on, which is worse left silent. |
|
| 114 | + | let identity = identities |
|
| 115 | + | .get(&hunk.id) |
|
| 116 | + | .ok_or_else(|| Error::Git(format!("hunk {:?} has no identity", hunk.id)))?; |
|
| 117 | + | let patch_id = identity.patch_id.clone(); |
|
| 113 | 118 | targets.insert( |
|
| 114 | 119 | hunk.id, |
|
| 115 | 120 | CommentTarget { |
|
| 116 | 121 | heading: heading.clone(), |
|
| 117 | 122 | path: path.clone(), |
|
| 118 | 123 | patch_id: patch_id.clone(), |
|
| 119 | 124 | }, |
|
| 120 | 125 | ); |
|
| 121 | - | if brain.is_rebase_pending(&patch_id) { |
|
| 122 | - | review.mark_rebase_pending(hunk.id); |
|
| 123 | - | } |
|
| 124 | - | patch_ids.insert(hunk.id, patch_id); |
|
| 125 | 126 | hunk_patches.insert(hunk.id, patch); |
|
| 126 | 127 | } |
|
| 127 | 128 | } |
|
| 128 | 129 | let comments = Comments::new(store, targets); |
|
| 129 | 130 | let mut loaded = Self { |
|
| 130 | 131 | viewer, |
|
| 131 | 132 | review, |
|
| 132 | 133 | comments, |
|
| 133 | 134 | hunk_patches, |
|
| 134 | - | patch_ids, |
|
| 135 | + | identities, |
|
| 135 | 136 | files, |
|
| 136 | 137 | file_hunks, |
|
| 137 | 138 | hunk_stats, |
|
| 138 | 139 | }; |
|
| 139 | 140 | loaded.refresh_decorations(); |
| 163 | 164 | area: Rect, |
|
| 164 | 165 | ) -> Result<(), Error> { |
|
| 165 | 166 | let mut hunk_ids = BTreeMap::<_, Vec<_>>::new(); |
|
| 166 | 167 | for file in &self.files { |
|
| 167 | 168 | for hunk in &file.hunks { |
|
| 168 | - | if let Some(patch_id) = self.patch_ids.get(&hunk.id) { |
|
| 169 | + | if let Some(identity) = self.identities.get(&hunk.id) { |
|
| 169 | 170 | hunk_ids |
|
| 170 | - | .entry((file.id, patch_id.clone())) |
|
| 171 | + | .entry((file.id, identity.patch_id.clone())) |
|
| 171 | 172 | .or_default() |
|
| 172 | 173 | .push(hunk.id); |
|
| 173 | 174 | } |
|
| 174 | 175 | } |
|
| 175 | 176 | } |
a.rs
+0 -0
crates/repo/src/git.rs
+1 -1
| 632 | 632 | stdin: Some(patch.as_bytes()), |
|
| 633 | 633 | ..Opts::default() |
|
| 634 | 634 | }, |
|
| 635 | 635 | )?; |
|
| 636 | 636 | if !output.status.success() { |
|
| 637 | - | return Err(RepoError::git(&output)); |
|
| 637 | + | return Err(RepoError::patch_apply(&output)); |
|
| 638 | 638 | } |
|
| 639 | 639 | let output = self.run( |
|
| 640 | 640 | "write-tree", |
|
| 641 | 641 | &[], |
|
| 642 | 642 | Opts { |
crates/repo/src/lib.rs
+18 -1
| 234 | 234 | pub trait WriteRepository { |
|
| 235 | 235 | /// Writes `bytes` as a blob object and returns its id. |
|
| 236 | 236 | fn write_blob(&self, bytes: &[u8]) -> Result<Oid, RepoError>; |
|
| 237 | 237 | ||
| 238 | 238 | /// Applies a Git-format patch to a temporary index and returns its tree id. |
|
| 239 | + | /// |
|
| 240 | + | /// Returns [`RepoError::PatchApply`] when the patch does not apply to |
|
| 241 | + | /// `base`; other variants signal that the operation itself failed. |
|
| 239 | 242 | fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError>; |
|
| 240 | 243 | ||
| 241 | 244 | /// Creates a commit with `tree` and `parent`. |
|
| 242 | 245 | fn commit( |
|
| 243 | 246 | &self, |
| 269 | 272 | Status(i32), |
|
| 270 | 273 | /// A Git plumbing command failed, carrying its diagnostic. |
|
| 271 | 274 | Git(String), |
|
| 272 | 275 | /// A three-way merge produced conflicts. |
|
| 273 | 276 | MergeConflict(String), |
|
| 277 | + | /// A patch did not apply to the requested tree, carrying its diagnostic. |
|
| 278 | + | PatchApply(String), |
|
| 274 | 279 | } |
|
| 275 | 280 | ||
| 276 | 281 | impl RepoError { |
|
| 277 | 282 | /// Builds a Git error from a failed command's output. |
|
| 278 | 283 | pub(crate) fn git(output: &Output) -> Self { |
|
| 284 | + | Self::Git(Self::diagnostic(output)) |
|
| 285 | + | } |
|
| 286 | + | ||
| 287 | + | /// Builds a patch-apply error from a failed command's output. |
|
| 288 | + | pub(crate) fn patch_apply(output: &Output) -> Self { |
|
| 289 | + | Self::PatchApply(Self::diagnostic(output)) |
|
| 290 | + | } |
|
| 291 | + | ||
| 292 | + | /// Returns a failed command's combined output as a diagnostic. |
|
| 293 | + | fn diagnostic(output: &Output) -> String { |
|
| 279 | 294 | let stdout = String::from_utf8_lossy(&output.stdout); |
|
| 280 | 295 | let stderr = String::from_utf8_lossy(&output.stderr); |
|
| 281 | - | Self::Git(format!("{stdout}{stderr}").trim().to_owned()) |
|
| 296 | + | ||
| 297 | + | format!("{stdout}{stderr}").trim().to_owned() |
|
| 282 | 298 | } |
|
| 283 | 299 | } |
|
| 284 | 300 | ||
| 285 | 301 | impl From<io::Error> for RepoError { |
|
| 286 | 302 | fn from(error: io::Error) -> Self { |
| 293 | 309 | match self { |
|
| 294 | 310 | Self::Io(error) => write!(f, "{error}"), |
|
| 295 | 311 | Self::Status(code) => write!(f, "command exited with status {code}"), |
|
| 296 | 312 | Self::Git(message) => write!(f, "{message}"), |
|
| 297 | 313 | Self::MergeConflict(message) => write!(f, "merge conflict: {message}"), |
|
| 314 | + | Self::PatchApply(message) => write!(f, "patch does not apply: {message}"), |
|
| 298 | 315 | } |
|
| 299 | 316 | } |
|
| 300 | 317 | } |
|
| 301 | 318 | ||
| 302 | 319 | impl std::error::Error for RepoError {} |