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