forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.08.8 MiBb00f3f4Tahinli1 month ago147 commits

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