forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiB5bed83dTahinli1 month ago79 commits

pulls_sync.rs878 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 crate::pages::pull_live::bump_pull(state, &base_repo.id, &pr.issue.id);
348 Ok(())
349}
350
351#[cfg(test)]
352mod tests {
353 use std::path::{Path, PathBuf};
354
355 use forge_core::{IssueState, Visibility};
356 use forge_git::repo::{init_bare, repo_path};
357 use tempfile::TempDir;
358
359 use super::*;
360 use crate::post_update::after_ref_update;
361 use crate::test_support::test_state;
362
363 fn git(dir: &Path, args: &[&str]) -> String {
364 let out = std::process::Command::new("git")
365 .arg("-C")
366 .arg(dir)
367 .args(args)
368 .env("GIT_AUTHOR_NAME", "test")
369 .env("GIT_AUTHOR_EMAIL", "test@example.com")
370 .env("GIT_COMMITTER_NAME", "test")
371 .env("GIT_COMMITTER_EMAIL", "test@example.com")
372 .env("GIT_CONFIG_NOSYSTEM", "1")
373 .env("GIT_CONFIG_GLOBAL", "/dev/null")
374 .output()
375 .expect("git runs");
376 assert!(
377 out.status.success(),
378 "git {args:?} failed: {}",
379 String::from_utf8_lossy(&out.stderr)
380 );
381 String::from_utf8_lossy(&out.stdout).trim().to_string()
382 }
383
384 /// Writes `contents` to `file` in the work tree, commits it and returns the new HEAD.
385 fn commit(work: &Path, file: &str, contents: &str) -> String {
386 std::fs::write(work.join(file), contents).expect("write file");
387 git(work, &["add", file]);
388 git(
389 work,
390 &[
391 "-c",
392 "commit.gpgsign=false",
393 "commit",
394 "-q",
395 "-m",
396 &format!("update {file}"),
397 ],
398 );
399 git(work, &["rev-parse", "HEAD"])
400 }
401
402 struct Fixture {
403 _tmp: TempDir,
404 state: AppState,
405 repo: Repo,
406 owner_id: String,
407 bare: PathBuf,
408 work: PathBuf,
409 }
410
411 /// A private repo with a bare copy on disk and an empty work tree that pushes to it.
412 async fn fixture() -> Fixture {
413 let tmp = tempfile::tempdir().expect("tempdir");
414 let state = test_state(tmp.path()).await;
415 let owner = state
416 .store
417 .create_user("tahinli", None, "unused", false)
418 .await
419 .expect("user");
420 let repo = state
421 .store
422 .create_repo(&owner.id, "proj", "", Visibility::Private, "main")
423 .await
424 .expect("repo");
425 let bare = repo_path(&state.git.data_dir, &repo.id).expect("repo path");
426 init_bare(&state.git, &bare, "main")
427 .await
428 .expect("init bare");
429 let work = tmp.path().join("work");
430 git(tmp.path(), &["init", "-b", "main", "work"]);
431 Fixture {
432 _tmp: tmp,
433 state,
434 repo,
435 owner_id: owner.id,
436 bare,
437 work,
438 }
439 }
440
441 impl Fixture {
442 fn bare_str(&self) -> &str {
443 self.bare.to_str().expect("utf8 path")
444 }
445
446 fn push(&self, refspec: &str) {
447 git(&self.work, &["push", self.bare_str(), refspec]);
448 }
449
450 /// Pushes `refspec` and runs the post-update work the hook would run.
451 async fn push_and_sync(&self, branch: &str, old: &str, new: &str) {
452 self.push(&format!("{new}:refs/heads/{branch}"));
453 after_ref_update(
454 &self.state,
455 &self.repo,
456 &self.owner_id,
457 &format!("refs/heads/{branch}"),
458 old,
459 new,
460 )
461 .await
462 .expect("post-update");
463 }
464
465 async fn pull(&self, number: i64) -> PullRequest {
466 self.state
467 .store
468 .pull_by_number(&self.repo.id, number)
469 .await
470 .expect("lookup")
471 .expect("pull exists")
472 }
473 }
474
475 #[tokio::test]
476 async fn pushing_to_head_branch_updates_the_pull() {
477 let fx = fixture().await;
478 let base = commit(&fx.work, "file.txt", "one");
479 fx.push("main");
480 git(&fx.work, &["checkout", "-b", "feature"]);
481 let f1 = commit(&fx.work, "feature.txt", "f1");
482 fx.push("feature");
483 let pr = fx
484 .state
485 .store
486 .create_pull(
487 &fx.repo.id,
488 &fx.owner_id,
489 "Feature",
490 "",
491 "main",
492 &fx.repo.id,
493 "feature",
494 &f1,
495 &base,
496 )
497 .await
498 .expect("create pull");
499 let number = pr.issue.number;
500
501 let f2 = commit(&fx.work, "feature.txt", "f2");
502 fx.push_and_sync("feature", &f1, &f2).await;
503
504 let pr = fx.pull(number).await;
505 assert_eq!(pr.head_oid, f2);
506 assert_eq!(pr.mergeable, Mergeable::Clean);
507 let pull_ref = git(
508 &fx.bare,
509 &["rev-parse", &format!("refs/pull/{number}/head")],
510 );
511 assert_eq!(pull_ref, f2);
512 let events = fx
513 .state
514 .store
515 .list_events(&pr.issue.id)
516 .await
517 .expect("events");
518 let updated = events
519 .iter()
520 .find(|e| e.kind == "head_updated")
521 .expect("head_updated event");
522 assert_eq!(updated.data["from"], f1);
523 assert_eq!(updated.data["to"], f2);
524 assert_eq!(updated.actor_id.as_deref(), Some(fx.owner_id.as_str()));
525 }
526
527 #[tokio::test]
528 async fn deleting_head_branch_keeps_last_head() {
529 let fx = fixture().await;
530 let base = commit(&fx.work, "file.txt", "one");
531 fx.push("main");
532 git(&fx.work, &["checkout", "-b", "feature"]);
533 let f1 = commit(&fx.work, "feature.txt", "f1");
534 fx.push("feature");
535 let pr = fx
536 .state
537 .store
538 .create_pull(
539 &fx.repo.id,
540 &fx.owner_id,
541 "Feature",
542 "",
543 "main",
544 &fx.repo.id,
545 "feature",
546 &f1,
547 &base,
548 )
549 .await
550 .expect("create pull");
551 let zero = "0".repeat(40);
552 git(&fx.bare, &["update-ref", "-d", "refs/heads/feature"]);
553 after_ref_update(
554 &fx.state,
555 &fx.repo,
556 &fx.owner_id,
557 "refs/heads/feature",
558 &f1,
559 &zero,
560 )
561 .await
562 .expect("post-update");
563
564 let pr = fx.pull(pr.issue.number).await;
565 assert_eq!(pr.head_oid, f1);
566 let events = fx
567 .state
568 .store
569 .list_events(&pr.issue.id)
570 .await
571 .expect("events");
572 assert!(events.iter().any(|e| e.kind == "head_deleted"));
573 }
574
575 #[tokio::test]
576 async fn pushing_conflicting_base_marks_pull_conflicting() {
577 let fx = fixture().await;
578 let base = commit(&fx.work, "file.txt", "one");
579 fx.push("main");
580 git(&fx.work, &["checkout", "-b", "feature"]);
581 let f1 = commit(&fx.work, "file.txt", "feature");
582 fx.push("feature");
583 let pr = fx
584 .state
585 .store
586 .create_pull(
587 &fx.repo.id,
588 &fx.owner_id,
589 "Feature",
590 "",
591 "main",
592 &fx.repo.id,
593 "feature",
594 &f1,
595 &base,
596 )
597 .await
598 .expect("create pull");
599 assert_eq!(pr.mergeable, Mergeable::Unknown);
600
601 git(&fx.work, &["checkout", "main"]);
602 let m1 = commit(&fx.work, "file.txt", "main");
603 fx.push_and_sync("main", &base, &m1).await;
604
605 let pr = fx.pull(pr.issue.number).await;
606 assert_eq!(pr.mergeable, Mergeable::Conflict);
607 assert_eq!(pr.conflict_files, vec!["file.txt".to_string()]);
608 assert_eq!(pr.base_oid, m1);
609 assert_eq!(pr.merge_base.as_deref(), Some(base.as_str()));
610 }
611
612 #[tokio::test]
613 async fn pushing_a_changed_file_marks_its_comments_outdated() {
614 use forge_core::reviews::Side;
615
616 let fx = fixture().await;
617 commit(&fx.work, "b.txt", "b0");
618 let base = commit(&fx.work, "a.txt", "a0");
619 fx.push("main");
620 git(&fx.work, &["checkout", "-b", "feature"]);
621 let f1 = commit(&fx.work, "a.txt", "a1");
622 fx.push("feature");
623 let pr = fx
624 .state
625 .store
626 .create_pull(
627 &fx.repo.id,
628 &fx.owner_id,
629 "Feature",
630 "",
631 "main",
632 &fx.repo.id,
633 "feature",
634 &f1,
635 &base,
636 )
637 .await
638 .expect("create pull");
639 let store = &fx.state.store;
640 store
641 .add_review_comment(
642 &pr.issue.id,
643 &fx.owner_id,
644 false,
645 "a.txt",
646 Side::New,
647 1,
648 &f1,
649 "",
650 "on a",
651 )
652 .await
653 .expect("comment on a");
654 store
655 .add_review_comment(
656 &pr.issue.id,
657 &fx.owner_id,
658 false,
659 "b.txt",
660 Side::New,
661 1,
662 &f1,
663 "",
664 "on b",
665 )
666 .await
667 .expect("comment on b");
668
669 let f2 = commit(&fx.work, "a.txt", "a2");
670 fx.push_and_sync("feature", &f1, &f2).await;
671
672 let threads = store
673 .review_threads(&pr.issue.id, None)
674 .await
675 .expect("threads");
676 let outdated_at = |path: &str| {
677 threads
678 .iter()
679 .find(|t| t.root.path == path)
680 .map(|t| t.root.outdated)
681 };
682 assert_eq!(outdated_at("a.txt"), Some(true));
683 assert_eq!(outdated_at("b.txt"), Some(false));
684 }
685
686 #[tokio::test]
687 async fn base_push_containing_head_marks_pull_merged() {
688 let fx = fixture().await;
689 let base = commit(&fx.work, "file.txt", "one");
690 fx.push("main");
691 git(&fx.work, &["checkout", "-b", "feature"]);
692 let f1 = commit(&fx.work, "feature.txt", "f1");
693 fx.push("feature");
694 let pr = fx
695 .state
696 .store
697 .create_pull(
698 &fx.repo.id,
699 &fx.owner_id,
700 "Feature",
701 "",
702 "main",
703 &fx.repo.id,
704 "feature",
705 &f1,
706 &base,
707 )
708 .await
709 .expect("create pull");
710
711 // A manual merge on the CLI: main gets a side commit, then the feature branch.
712 git(&fx.work, &["checkout", "main"]);
713 let side = commit(&fx.work, "other.txt", "other");
714 git(
715 &fx.work,
716 &["merge", "--no-ff", "feature", "-m", "merge feature"],
717 );
718 let merge = git(&fx.work, &["rev-parse", "HEAD"]);
719 assert_ne!(merge, side);
720 fx.push_and_sync("main", &side, &merge).await;
721
722 let pr = fx.pull(pr.issue.number).await;
723 assert_eq!(pr.mergeable, Mergeable::Merged);
724 assert_eq!(pr.merge_commit.as_deref(), Some(merge.as_str()));
725 assert!(pr.merged_at.is_some());
726 assert_eq!(pr.issue.state, IssueState::Closed);
727 let events = fx
728 .state
729 .store
730 .list_events(&pr.issue.id)
731 .await
732 .expect("events");
733 assert!(events.iter().any(|e| e.kind == "merged"));
734 }
735
736 #[test]
737 fn unchanged_line_follows_insertions_above() {
738 let old = "a\nb\nc\n";
739 let new = "x\na\nb\nc\n";
740 assert_eq!(unchanged_line(old, new, 1), Some(2));
741 assert_eq!(unchanged_line(old, new, 2), Some(3));
742 assert_eq!(unchanged_line(old, new, 3), Some(4));
743 assert_eq!(unchanged_line(old, new, 0), None);
744 assert_eq!(unchanged_line(old, new, 9), None);
745 }
746
747 #[test]
748 fn unchanged_line_is_none_for_modified_or_deleted_lines() {
749 assert_eq!(unchanged_line("a\nb\nc\n", "a\nB\nc\n", 2), None);
750 assert_eq!(unchanged_line("a\nb\nc\n", "a\nB\nc\n", 3), Some(3));
751 assert_eq!(unchanged_line("a\nb\n", "a\n", 2), None);
752 }
753
754 #[tokio::test]
755 async fn pushing_moved_lines_relocates_comments_and_changed_lines_go_outdated() {
756 use forge_core::reviews::Side;
757
758 let fx = fixture().await;
759 let base = commit(&fx.work, "b.txt", "b0");
760 fx.push("main");
761 git(&fx.work, &["checkout", "-b", "feature"]);
762 let f1 = commit(&fx.work, "a.txt", "a\nb\nc\n");
763 fx.push("feature");
764 let pr = fx
765 .state
766 .store
767 .create_pull(
768 &fx.repo.id,
769 &fx.owner_id,
770 "Feature",
771 "",
772 "main",
773 &fx.repo.id,
774 "feature",
775 &f1,
776 &base,
777 )
778 .await
779 .expect("create pull");
780 let store = &fx.state.store;
781 for (line, body) in [(2, "on b"), (3, "on c")] {
782 store
783 .add_review_comment(
784 &pr.issue.id,
785 &fx.owner_id,
786 false,
787 "a.txt",
788 Side::New,
789 line,
790 &f1,
791 "",
792 body,
793 )
794 .await
795 .expect("comment");
796 }
797 // Lines are inserted above "b" and "c" is rewritten.
798 let f2 = commit(&fx.work, "a.txt", "x\na\nb\nC\n");
799 fx.push_and_sync("feature", &f1, &f2).await;
800
801 let threads = store
802 .review_threads(&pr.issue.id, None)
803 .await
804 .expect("threads");
805 let on = |body: &str| {
806 threads
807 .iter()
808 .map(|t| &t.root)
809 .find(|r| r.body == body)
810 .expect("root")
811 .clone()
812 };
813 let moved = on("on b");
814 assert!(!moved.outdated);
815 assert_eq!(moved.line, 3);
816 assert_eq!(moved.commit_oid, f2);
817 assert_eq!(moved.diff_hunk, "");
818 assert!(on("on c").outdated);
819 }
820
821 #[tokio::test]
822 async fn deleting_a_file_marks_its_comments_outdated() {
823 use forge_core::reviews::Side;
824
825 let fx = fixture().await;
826 let base = commit(&fx.work, "b.txt", "b0");
827 fx.push("main");
828 git(&fx.work, &["checkout", "-b", "feature"]);
829 let f1 = commit(&fx.work, "a.txt", "a\nb\n");
830 fx.push("feature");
831 let pr = fx
832 .state
833 .store
834 .create_pull(
835 &fx.repo.id,
836 &fx.owner_id,
837 "Feature",
838 "",
839 "main",
840 &fx.repo.id,
841 "feature",
842 &f1,
843 &base,
844 )
845 .await
846 .expect("create pull");
847 fx.state
848 .store
849 .add_review_comment(
850 &pr.issue.id,
851 &fx.owner_id,
852 false,
853 "a.txt",
854 Side::New,
855 1,
856 &f1,
857 "",
858 "on a",
859 )
860 .await
861 .expect("comment");
862
863 git(&fx.work, &["rm", "a.txt"]);
864 git(&fx.work, &["commit", "-m", "remove a"]);
865 let f2 = git(&fx.work, &["rev-parse", "HEAD"]);
866 fx.push_and_sync("feature", &f1, &f2).await;
867
868 let threads = fx
869 .state
870 .store
871 .review_threads(&pr.issue.id, None)
872 .await
873 .expect("threads");
874 assert_eq!(threads.len(), 1);
875 assert!(threads[0].root.outdated);
876 assert_eq!(threads[0].root.commit_oid, f1);
877 }
878}