forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.1 MiB197fa34Tahinli1 month ago68 commits

pulls_sync.rs877 lines, 28.3 KiBHistoryRawDownload
1//! Keeps pull requests in step with their branches after a ref update.
2//!
3//! Called from `post_update::after_ref_update` for every `refs/heads/<b>` update of a repo.
4//! Work runs inline (not spawned): each step is a few git calls and a few row writes, and inline
5//! execution keeps the results deterministic for tests and for the merge route. Per-pull errors
6//! are logged and skipped so one broken pull request does not block the others or the push.
7
8use std::collections::HashMap;
9use std::path::Path;
10
11use forge_core::reviews::{ReviewComment, Side};
12use forge_core::{Mergeable, PullRequest, Repo};
13use forge_git::pulls::{
14 MergeCheck, blob_at, check_merge, fetch_into_pull_ref, is_ancestor, merge_base,
15};
16use serde_json::json;
17use similar::{ChangeTag, TextDiff};
18
19use crate::internal::is_zero_oid;
20use crate::notify::{self, Activity};
21use crate::state::AppState;
22use crate::webhooks::emit::{emit_item_action, lookup_sender};
23
24/// Syncs every open pull request affected by `refname` (old -> new) in `repo`.
25///
26/// - PRs whose head is `(repo, branch)`: the pull ref is updated, the head moves, a `head_updated`
27/// event is recorded and mergeability is refreshed. A deleted branch records `head_deleted` and
28/// keeps the last head.
29/// - PRs whose base is `(repo, branch)`: if the PR head is now contained in the new base tip and
30/// was not contained before the push, the PR is marked merged (a manual merge on the CLI).
31/// Otherwise mergeability is refreshed.
32pub async fn sync_pulls_for_ref(
33 state: &AppState,
34 repo: &Repo,
35 actor_id: &str,
36 refname: &str,
37 old: &str,
38 new: &str,
39) -> forge_core::Result<()> {
40 let Some(branch) = refname.strip_prefix("refs/heads/") else {
41 return Ok(());
42 };
43 let heads = state.store.open_pulls_for_head(&repo.id, branch).await?;
44 for (base_repo_id, number, issue_id) in heads {
45 if let Err(e) = sync_head(
46 state,
47 repo,
48 actor_id,
49 &base_repo_id,
50 number,
51 &issue_id,
52 branch,
53 old,
54 new,
55 )
56 .await
57 {
58 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: head update failed");
59 }
60 }
61 let bases = state.store.open_pulls_for_base(&repo.id, branch).await?;
62 for (number, issue_id) in bases {
63 if let Err(e) = sync_base(state, repo, actor_id, number, &issue_id, old, new).await {
64 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: base update failed");
65 }
66 }
67 Ok(())
68}
69
70/// Handles one open PR whose head branch is `branch` in `head_repo`.
71#[allow(clippy::too_many_arguments)]
72async fn sync_head(
73 state: &AppState,
74 head_repo: &Repo,
75 actor_id: &str,
76 base_repo_id: &str,
77 number: i64,
78 issue_id: &str,
79 branch: &str,
80 old: &str,
81 new: &str,
82) -> forge_core::Result<()> {
83 let actor = (!actor_id.is_empty()).then_some(actor_id);
84 let Some(pr) = state.store.pull_by_number(base_repo_id, number).await? else {
85 return Ok(());
86 };
87 if is_zero_oid(new) {
88 state
89 .store
90 .add_event(
91 issue_id,
92 actor,
93 "head_deleted",
94 json!({"branch": branch, "last_head": pr.head_oid}),
95 )
96 .await?;
97 return Ok(());
98 }
99 let Some(base_repo) = state.store.repo_by_id(base_repo_id).await? else {
100 return Ok(());
101 };
102 let base_path = forge_git::repo::repo_path(&state.git.data_dir, &base_repo.id)?;
103 let head_path = forge_git::repo::repo_path(&state.git.data_dir, &head_repo.id)?;
104 fetch_into_pull_ref(&state.git, &base_path, &head_path, new, number).await?;
105 state.store.update_pull_head(issue_id, new).await?;
106 if pr.auto_merge.is_some() {
107 // `update_pull_head` already cleared the setting; tell the timeline why.
108 state
109 .store
110 .add_event(
111 issue_id,
112 actor,
113 "auto_merge_disabled",
114 json!({"reason": "push"}),
115 )
116 .await?;
117 }
118 mark_outdated_threads(state, &base_path, issue_id, new).await;
119 state
120 .store
121 .add_event(
122 issue_id,
123 actor,
124 "head_updated",
125 json!({"from": old, "to": new}),
126 )
127 .await?;
128 let sender = lookup_sender(state, actor_id).await;
129 emit_item_action(state, &base_repo, &sender, true, number, "synchronize").await;
130 // Reload so the refresh sees the new head.
131 let Some(pr) = state.store.pull_by_number(base_repo_id, number).await? else {
132 return Ok(());
133 };
134 notify::dispatch(
135 state,
136 &base_repo,
137 &pr.issue,
138 actor_id,
139 Activity::Pushed,
140 None,
141 )
142 .await;
143 crate::ci::on_pull_event(state, &base_repo, &pr, actor_id).await;
144 refresh_mergeability(state, &base_repo, &pr).await
145}
146
147/// Largest file, in bytes, whose text is compared line by line when a moved head is checked.
148/// Bigger files, binary files and missing files fall back to outdated.
149const MAX_REMAP_BYTES: usize = 1024 * 1024;
150
151/// Handles submitted root comments after the head moved to `new_head`.
152///
153/// A root is left alone while the blob at its `path` is the same at its `commit_oid` and at
154/// `new_head`. When the blob changed, a new-side root whose line kept its content is moved to the
155/// line's new number at `new_head` (replies follow it). Every other changed root is outdated:
156/// its line was deleted or modified, or the file vanished, grew past `MAX_REMAP_BYTES` or became
157/// binary. Blob lookups are cached per `(commit, path)`. Failures are logged and leave the
158/// comments as they were, so they never fail the push.
159async fn mark_outdated_threads(state: &AppState, base_path: &Path, issue_id: &str, new_head: &str) {
160 let threads = match state.store.review_threads(issue_id, None).await {
161 Ok(threads) => threads,
162 Err(e) => {
163 tracing::error!(error = %e, issue_id, "pull sync: loading review threads failed");
164 return;
165 }
166 };
167 let mut cache = HashMap::new();
168 let mut texts = HashMap::new();
169 let mut outdated = Vec::new();
170 let mut moved = Vec::new();
171 for thread in threads {
172 let root = thread.root;
173 if root.outdated {
174 continue;
175 }
176 let old = cached_blob(state, base_path, &mut cache, &root.commit_oid, &root.path).await;
177 let new = cached_blob(state, base_path, &mut cache, new_head, &root.path).await;
178 let (old, new) = match (old, new) {
179 (Ok(old), Ok(new)) => (old, new),
180 (Err(e), _) | (_, Err(e)) => {
181 tracing::error!(error = %e, comment_id = %root.id, "pull sync: blob lookup failed");
182 continue;
183 }
184 };
185 if old == new {
186 continue;
187 }
188 let target = if root.side == Side::New && old.is_some() && new.is_some() {
189 match remap_root_line(base_path, &mut texts, &root, new_head) {
190 Ok(target) => target,
191 Err(e) => {
192 tracing::error!(error = %e, comment_id = %root.id, "pull sync: text lookup failed");
193 continue;
194 }
195 }
196 } else {
197 None
198 };
199 match target {
200 Some(line) => moved.push((root.id.clone(), line)),
201 None => outdated.push(root.id.clone()),
202 }
203 }
204 for (id, line) in &moved {
205 if let Err(e) = state
206 .store
207 .relocate_review_comment(id, *line, new_head)
208 .await
209 {
210 tracing::error!(error = %e, comment_id = %id, "pull sync: relocating comment failed");
211 }
212 }
213 if outdated.is_empty() {
214 return;
215 }
216 if let Err(e) = state.store.mark_outdated(issue_id, &outdated).await {
217 tracing::error!(error = %e, issue_id, "pull sync: marking comments outdated failed");
218 }
219}
220
221/// The line a changed root moves to at `new_head`, or None when it must be outdated. The root's
222/// line is looked up in the text at its own commit and at `new_head`; a missing or oversized text
223/// gives None.
224fn remap_root_line(
225 base_path: &Path,
226 texts: &mut HashMap<(String, String), Option<String>>,
227 root: &ReviewComment,
228 new_head: &str,
229) -> forge_core::Result<Option<u32>> {
230 let old = cached_text(base_path, texts, &root.commit_oid, &root.path)?;
231 let new = cached_text(base_path, texts, new_head, &root.path)?;
232 Ok(match (old, new) {
233 (Some(old), Some(new)) => unchanged_line(&old, &new, root.line),
234 _ => None,
235 })
236}
237
238/// The new line number of `old_line` (1-based) when its content is unchanged in `new`, or None
239/// when the line was deleted or modified.
240fn unchanged_line(old: &str, new: &str, old_line: u32) -> Option<u32> {
241 let index = usize::try_from(old_line).ok()?.checked_sub(1)?;
242 TextDiff::from_lines(old, new)
243 .iter_all_changes()
244 .find(|change| change.tag() == ChangeTag::Equal && change.old_index() == Some(index))
245 .and_then(|change| change.new_index())
246 .and_then(|index| u32::try_from(index + 1).ok())
247}
248
249/// The text of the file at `path` in `commit`, looked up once per `(commit, path)`.
250fn cached_text(
251 base_path: &Path,
252 cache: &mut HashMap<(String, String), Option<String>>,
253 commit: &str,
254 path: &str,
255) -> forge_core::Result<Option<String>> {
256 let key = (commit.to_owned(), path.to_owned());
257 if let Some(text) = cache.get(&key) {
258 return Ok(text.clone());
259 }
260 let text = forge_git::browse::read_text_blob(base_path, commit, path, MAX_REMAP_BYTES)?;
261 cache.insert(key, text.clone());
262 Ok(text)
263}
264
265/// The blob at `path` in `commit`, looked up once per `(commit, path)`.
266async fn cached_blob(
267 state: &AppState,
268 base_path: &Path,
269 cache: &mut HashMap<(String, String), Option<String>>,
270 commit: &str,
271 path: &str,
272) -> forge_core::Result<Option<String>> {
273 let key = (commit.to_owned(), path.to_owned());
274 if let Some(blob) = cache.get(&key) {
275 return Ok(blob.clone());
276 }
277 let blob = blob_at(&state.git, base_path, commit, path).await?;
278 cache.insert(key, blob.clone());
279 Ok(blob)
280}
281
282/// Handles one open PR whose base branch was just updated in `repo`.
283async fn sync_base(
284 state: &AppState,
285 repo: &Repo,
286 actor_id: &str,
287 number: i64,
288 issue_id: &str,
289 old: &str,
290 new: &str,
291) -> forge_core::Result<()> {
292 if is_zero_oid(new) {
293 // The base branch was deleted; there is nothing to compare against.
294 return Ok(());
295 }
296 let Some(pr) = state.store.pull_by_number(&repo.id, number).await? else {
297 return Ok(());
298 };
299 let base_path = forge_git::repo::repo_path(&state.git.data_dir, &repo.id)?;
300 if is_ancestor(&state.git, &base_path, &pr.head_oid, new).await? {
301 let was_contained =
302 !is_zero_oid(old) && is_ancestor(&state.git, &base_path, &pr.head_oid, old).await?;
303 if !was_contained {
304 // The push brought the head into base: a merge done outside the web UI.
305 state.store.mark_merged(issue_id, actor_id, new).await?;
306 let sender = lookup_sender(state, actor_id).await;
307 emit_item_action(state, repo, &sender, true, number, "merged").await;
308 notify::dispatch(state, repo, &pr.issue, actor_id, Activity::Merged, None).await;
309 return Ok(());
310 }
311 }
312 refresh_mergeability(state, repo, &pr).await
313}
314
315/// Recomputes whether `pr` merges cleanly into the current tip of its base branch in `base_repo`,
316/// and stores the result (base tip, merge base, mergeability, conflicting files).
317///
318/// A missing base branch leaves the stored result untouched. Git failures are returned; callers
319/// that must not fail a push log them.
320pub async fn refresh_mergeability(
321 state: &AppState,
322 base_repo: &Repo,
323 pr: &PullRequest,
324) -> forge_core::Result<()> {
325 let base_path = forge_git::repo::repo_path(&state.git.data_dir, &base_repo.id)?;
326 let Some(base_tip) = forge_git::browse::default_branch_commit(&base_path, &pr.base_branch)?
327 else {
328 return Ok(());
329 };
330 let (mergeable, files) =
331 match check_merge(&state.git, &base_path, &base_tip, &pr.head_oid).await? {
332 MergeCheck::Clean { .. } => (Mergeable::Clean, Vec::new()),
333 MergeCheck::Conflict { files } => (Mergeable::Conflict, files),
334 MergeCheck::UpToDate => (Mergeable::UpToDate, Vec::new()),
335 };
336 let base_of_head = merge_base(&state.git, &base_path, &base_tip, &pr.head_oid).await?;
337 state
338 .store
339 .set_mergeability(
340 &pr.issue.id,
341 &base_tip,
342 base_of_head.as_deref(),
343 mergeable,
344 &files,
345 )
346 .await?;
347 Ok(())
348}
349
350#[cfg(test)]
351mod tests {
352 use std::path::{Path, PathBuf};
353
354 use forge_core::{IssueState, Visibility};
355 use forge_git::repo::{init_bare, repo_path};
356 use tempfile::TempDir;
357
358 use super::*;
359 use crate::post_update::after_ref_update;
360 use crate::test_support::test_state;
361
362 fn git(dir: &Path, args: &[&str]) -> String {
363 let out = std::process::Command::new("git")
364 .arg("-C")
365 .arg(dir)
366 .args(args)
367 .env("GIT_AUTHOR_NAME", "test")
368 .env("GIT_AUTHOR_EMAIL", "test@example.com")
369 .env("GIT_COMMITTER_NAME", "test")
370 .env("GIT_COMMITTER_EMAIL", "test@example.com")
371 .env("GIT_CONFIG_NOSYSTEM", "1")
372 .env("GIT_CONFIG_GLOBAL", "/dev/null")
373 .output()
374 .expect("git runs");
375 assert!(
376 out.status.success(),
377 "git {args:?} failed: {}",
378 String::from_utf8_lossy(&out.stderr)
379 );
380 String::from_utf8_lossy(&out.stdout).trim().to_string()
381 }
382
383 /// Writes `contents` to `file` in the work tree, commits it and returns the new HEAD.
384 fn commit(work: &Path, file: &str, contents: &str) -> String {
385 std::fs::write(work.join(file), contents).expect("write file");
386 git(work, &["add", file]);
387 git(
388 work,
389 &[
390 "-c",
391 "commit.gpgsign=false",
392 "commit",
393 "-q",
394 "-m",
395 &format!("update {file}"),
396 ],
397 );
398 git(work, &["rev-parse", "HEAD"])
399 }
400
401 struct Fixture {
402 _tmp: TempDir,
403 state: AppState,
404 repo: Repo,
405 owner_id: String,
406 bare: PathBuf,
407 work: PathBuf,
408 }
409
410 /// A private repo with a bare copy on disk and an empty work tree that pushes to it.
411 async fn fixture() -> Fixture {
412 let tmp = tempfile::tempdir().expect("tempdir");
413 let state = test_state(tmp.path()).await;
414 let owner = state
415 .store
416 .create_user("tahinli", None, "unused", false)
417 .await
418 .expect("user");
419 let repo = state
420 .store
421 .create_repo(&owner.id, "proj", "", Visibility::Private, "main")
422 .await
423 .expect("repo");
424 let bare = repo_path(&state.git.data_dir, &repo.id).expect("repo path");
425 init_bare(&state.git, &bare, "main")
426 .await
427 .expect("init bare");
428 let work = tmp.path().join("work");
429 git(tmp.path(), &["init", "-b", "main", "work"]);
430 Fixture {
431 _tmp: tmp,
432 state,
433 repo,
434 owner_id: owner.id,
435 bare,
436 work,
437 }
438 }
439
440 impl Fixture {
441 fn bare_str(&self) -> &str {
442 self.bare.to_str().expect("utf8 path")
443 }
444
445 fn push(&self, refspec: &str) {
446 git(&self.work, &["push", self.bare_str(), refspec]);
447 }
448
449 /// Pushes `refspec` and runs the post-update work the hook would run.
450 async fn push_and_sync(&self, branch: &str, old: &str, new: &str) {
451 self.push(&format!("{new}:refs/heads/{branch}"));
452 after_ref_update(
453 &self.state,
454 &self.repo,
455 &self.owner_id,
456 &format!("refs/heads/{branch}"),
457 old,
458 new,
459 )
460 .await
461 .expect("post-update");
462 }
463
464 async fn pull(&self, number: i64) -> PullRequest {
465 self.state
466 .store
467 .pull_by_number(&self.repo.id, number)
468 .await
469 .expect("lookup")
470 .expect("pull exists")
471 }
472 }
473
474 #[tokio::test]
475 async fn pushing_to_head_branch_updates_the_pull() {
476 let fx = fixture().await;
477 let base = commit(&fx.work, "file.txt", "one");
478 fx.push("main");
479 git(&fx.work, &["checkout", "-b", "feature"]);
480 let f1 = commit(&fx.work, "feature.txt", "f1");
481 fx.push("feature");
482 let pr = fx
483 .state
484 .store
485 .create_pull(
486 &fx.repo.id,
487 &fx.owner_id,
488 "Feature",
489 "",
490 "main",
491 &fx.repo.id,
492 "feature",
493 &f1,
494 &base,
495 )
496 .await
497 .expect("create pull");
498 let number = pr.issue.number;
499
500 let f2 = commit(&fx.work, "feature.txt", "f2");
501 fx.push_and_sync("feature", &f1, &f2).await;
502
503 let pr = fx.pull(number).await;
504 assert_eq!(pr.head_oid, f2);
505 assert_eq!(pr.mergeable, Mergeable::Clean);
506 let pull_ref = git(
507 &fx.bare,
508 &["rev-parse", &format!("refs/pull/{number}/head")],
509 );
510 assert_eq!(pull_ref, f2);
511 let events = fx
512 .state
513 .store
514 .list_events(&pr.issue.id)
515 .await
516 .expect("events");
517 let updated = events
518 .iter()
519 .find(|e| e.kind == "head_updated")
520 .expect("head_updated event");
521 assert_eq!(updated.data["from"], f1);
522 assert_eq!(updated.data["to"], f2);
523 assert_eq!(updated.actor_id.as_deref(), Some(fx.owner_id.as_str()));
524 }
525
526 #[tokio::test]
527 async fn deleting_head_branch_keeps_last_head() {
528 let fx = fixture().await;
529 let base = commit(&fx.work, "file.txt", "one");
530 fx.push("main");
531 git(&fx.work, &["checkout", "-b", "feature"]);
532 let f1 = commit(&fx.work, "feature.txt", "f1");
533 fx.push("feature");
534 let pr = fx
535 .state
536 .store
537 .create_pull(
538 &fx.repo.id,
539 &fx.owner_id,
540 "Feature",
541 "",
542 "main",
543 &fx.repo.id,
544 "feature",
545 &f1,
546 &base,
547 )
548 .await
549 .expect("create pull");
550 let zero = "0".repeat(40);
551 git(&fx.bare, &["update-ref", "-d", "refs/heads/feature"]);
552 after_ref_update(
553 &fx.state,
554 &fx.repo,
555 &fx.owner_id,
556 "refs/heads/feature",
557 &f1,
558 &zero,
559 )
560 .await
561 .expect("post-update");
562
563 let pr = fx.pull(pr.issue.number).await;
564 assert_eq!(pr.head_oid, f1);
565 let events = fx
566 .state
567 .store
568 .list_events(&pr.issue.id)
569 .await
570 .expect("events");
571 assert!(events.iter().any(|e| e.kind == "head_deleted"));
572 }
573
574 #[tokio::test]
575 async fn pushing_conflicting_base_marks_pull_conflicting() {
576 let fx = fixture().await;
577 let base = commit(&fx.work, "file.txt", "one");
578 fx.push("main");
579 git(&fx.work, &["checkout", "-b", "feature"]);
580 let f1 = commit(&fx.work, "file.txt", "feature");
581 fx.push("feature");
582 let pr = fx
583 .state
584 .store
585 .create_pull(
586 &fx.repo.id,
587 &fx.owner_id,
588 "Feature",
589 "",
590 "main",
591 &fx.repo.id,
592 "feature",
593 &f1,
594 &base,
595 )
596 .await
597 .expect("create pull");
598 assert_eq!(pr.mergeable, Mergeable::Unknown);
599
600 git(&fx.work, &["checkout", "main"]);
601 let m1 = commit(&fx.work, "file.txt", "main");
602 fx.push_and_sync("main", &base, &m1).await;
603
604 let pr = fx.pull(pr.issue.number).await;
605 assert_eq!(pr.mergeable, Mergeable::Conflict);
606 assert_eq!(pr.conflict_files, vec!["file.txt".to_string()]);
607 assert_eq!(pr.base_oid, m1);
608 assert_eq!(pr.merge_base.as_deref(), Some(base.as_str()));
609 }
610
611 #[tokio::test]
612 async fn pushing_a_changed_file_marks_its_comments_outdated() {
613 use forge_core::reviews::Side;
614
615 let fx = fixture().await;
616 commit(&fx.work, "b.txt", "b0");
617 let base = commit(&fx.work, "a.txt", "a0");
618 fx.push("main");
619 git(&fx.work, &["checkout", "-b", "feature"]);
620 let f1 = commit(&fx.work, "a.txt", "a1");
621 fx.push("feature");
622 let pr = fx
623 .state
624 .store
625 .create_pull(
626 &fx.repo.id,
627 &fx.owner_id,
628 "Feature",
629 "",
630 "main",
631 &fx.repo.id,
632 "feature",
633 &f1,
634 &base,
635 )
636 .await
637 .expect("create pull");
638 let store = &fx.state.store;
639 store
640 .add_review_comment(
641 &pr.issue.id,
642 &fx.owner_id,
643 false,
644 "a.txt",
645 Side::New,
646 1,
647 &f1,
648 "",
649 "on a",
650 )
651 .await
652 .expect("comment on a");
653 store
654 .add_review_comment(
655 &pr.issue.id,
656 &fx.owner_id,
657 false,
658 "b.txt",
659 Side::New,
660 1,
661 &f1,
662 "",
663 "on b",
664 )
665 .await
666 .expect("comment on b");
667
668 let f2 = commit(&fx.work, "a.txt", "a2");
669 fx.push_and_sync("feature", &f1, &f2).await;
670
671 let threads = store
672 .review_threads(&pr.issue.id, None)
673 .await
674 .expect("threads");
675 let outdated_at = |path: &str| {
676 threads
677 .iter()
678 .find(|t| t.root.path == path)
679 .map(|t| t.root.outdated)
680 };
681 assert_eq!(outdated_at("a.txt"), Some(true));
682 assert_eq!(outdated_at("b.txt"), Some(false));
683 }
684
685 #[tokio::test]
686 async fn base_push_containing_head_marks_pull_merged() {
687 let fx = fixture().await;
688 let base = commit(&fx.work, "file.txt", "one");
689 fx.push("main");
690 git(&fx.work, &["checkout", "-b", "feature"]);
691 let f1 = commit(&fx.work, "feature.txt", "f1");
692 fx.push("feature");
693 let pr = fx
694 .state
695 .store
696 .create_pull(
697 &fx.repo.id,
698 &fx.owner_id,
699 "Feature",
700 "",
701 "main",
702 &fx.repo.id,
703 "feature",
704 &f1,
705 &base,
706 )
707 .await
708 .expect("create pull");
709
710 // A manual merge on the CLI: main gets a side commit, then the feature branch.
711 git(&fx.work, &["checkout", "main"]);
712 let side = commit(&fx.work, "other.txt", "other");
713 git(
714 &fx.work,
715 &["merge", "--no-ff", "feature", "-m", "merge feature"],
716 );
717 let merge = git(&fx.work, &["rev-parse", "HEAD"]);
718 assert_ne!(merge, side);
719 fx.push_and_sync("main", &side, &merge).await;
720
721 let pr = fx.pull(pr.issue.number).await;
722 assert_eq!(pr.mergeable, Mergeable::Merged);
723 assert_eq!(pr.merge_commit.as_deref(), Some(merge.as_str()));
724 assert!(pr.merged_at.is_some());
725 assert_eq!(pr.issue.state, IssueState::Closed);
726 let events = fx
727 .state
728 .store
729 .list_events(&pr.issue.id)
730 .await
731 .expect("events");
732 assert!(events.iter().any(|e| e.kind == "merged"));
733 }
734
735 #[test]
736 fn unchanged_line_follows_insertions_above() {
737 let old = "a\nb\nc\n";
738 let new = "x\na\nb\nc\n";
739 assert_eq!(unchanged_line(old, new, 1), Some(2));
740 assert_eq!(unchanged_line(old, new, 2), Some(3));
741 assert_eq!(unchanged_line(old, new, 3), Some(4));
742 assert_eq!(unchanged_line(old, new, 0), None);
743 assert_eq!(unchanged_line(old, new, 9), None);
744 }
745
746 #[test]
747 fn unchanged_line_is_none_for_modified_or_deleted_lines() {
748 assert_eq!(unchanged_line("a\nb\nc\n", "a\nB\nc\n", 2), None);
749 assert_eq!(unchanged_line("a\nb\nc\n", "a\nB\nc\n", 3), Some(3));
750 assert_eq!(unchanged_line("a\nb\n", "a\n", 2), None);
751 }
752
753 #[tokio::test]
754 async fn pushing_moved_lines_relocates_comments_and_changed_lines_go_outdated() {
755 use forge_core::reviews::Side;
756
757 let fx = fixture().await;
758 let base = commit(&fx.work, "b.txt", "b0");
759 fx.push("main");
760 git(&fx.work, &["checkout", "-b", "feature"]);
761 let f1 = commit(&fx.work, "a.txt", "a\nb\nc\n");
762 fx.push("feature");
763 let pr = fx
764 .state
765 .store
766 .create_pull(
767 &fx.repo.id,
768 &fx.owner_id,
769 "Feature",
770 "",
771 "main",
772 &fx.repo.id,
773 "feature",
774 &f1,
775 &base,
776 )
777 .await
778 .expect("create pull");
779 let store = &fx.state.store;
780 for (line, body) in [(2, "on b"), (3, "on c")] {
781 store
782 .add_review_comment(
783 &pr.issue.id,
784 &fx.owner_id,
785 false,
786 "a.txt",
787 Side::New,
788 line,
789 &f1,
790 "",
791 body,
792 )
793 .await
794 .expect("comment");
795 }
796 // Lines are inserted above "b" and "c" is rewritten.
797 let f2 = commit(&fx.work, "a.txt", "x\na\nb\nC\n");
798 fx.push_and_sync("feature", &f1, &f2).await;
799
800 let threads = store
801 .review_threads(&pr.issue.id, None)
802 .await
803 .expect("threads");
804 let on = |body: &str| {
805 threads
806 .iter()
807 .map(|t| &t.root)
808 .find(|r| r.body == body)
809 .expect("root")
810 .clone()
811 };
812 let moved = on("on b");
813 assert!(!moved.outdated);
814 assert_eq!(moved.line, 3);
815 assert_eq!(moved.commit_oid, f2);
816 assert_eq!(moved.diff_hunk, "");
817 assert!(on("on c").outdated);
818 }
819
820 #[tokio::test]
821 async fn deleting_a_file_marks_its_comments_outdated() {
822 use forge_core::reviews::Side;
823
824 let fx = fixture().await;
825 let base = commit(&fx.work, "b.txt", "b0");
826 fx.push("main");
827 git(&fx.work, &["checkout", "-b", "feature"]);
828 let f1 = commit(&fx.work, "a.txt", "a\nb\n");
829 fx.push("feature");
830 let pr = fx
831 .state
832 .store
833 .create_pull(
834 &fx.repo.id,
835 &fx.owner_id,
836 "Feature",
837 "",
838 "main",
839 &fx.repo.id,
840 "feature",
841 &f1,
842 &base,
843 )
844 .await
845 .expect("create pull");
846 fx.state
847 .store
848 .add_review_comment(
849 &pr.issue.id,
850 &fx.owner_id,
851 false,
852 "a.txt",
853 Side::New,
854 1,
855 &f1,
856 "",
857 "on a",
858 )
859 .await
860 .expect("comment");
861
862 git(&fx.work, &["rm", "a.txt"]);
863 git(&fx.work, &["commit", "-m", "remove a"]);
864 let f2 = git(&fx.work, &["rev-parse", "HEAD"]);
865 fx.push_and_sync("feature", &f1, &f2).await;
866
867 let threads = fx
868 .state
869 .store
870 .review_threads(&pr.issue.id, None)
871 .await
872 .expect("threads");
873 assert_eq!(threads.len(), 1);
874 assert!(threads[0].root.outdated);
875 assert_eq!(threads[0].root.commit_oid, f1);
876 }
877}