steid

@jamesgill /

steid/src/application/pull_request.rs
Rust87.8 KBCode·Blame·History·Raw
1//! Pull requests: opening one, reading it, commenting, closing, and merging it.
2//!
3//! Authorization is [`issue`](super::issue)'s, reused rather than restated:
4//! `readable_repo` and `writable_repo` already answer "may this actor see this
5//! repository" and "may this actor write to its tracker", and a second copy of those
6//! rules would be a second chance to get them wrong. **Reading follows the repository's
7//! visibility; every write is owner-only.**
8//!
9//! Merging adds one rule the tracker does not have. Opening and commenting on a pull
10//! request are conversation, and stay available on an archived repository for the reason
11//! issues do — a release is exactly when the conversation happens. **Merging writes git
12//! objects and moves a branch**, so it goes through
13//! [`refuse_writes`](crate::domain::Repository::refuse_writes) with
14//! [`RepoWrite::Contents`], the same guard a `git push` meets, and an archived or
15//! still-importing repository refuses it in the same words.
16//!
17//! # What is stored, and what is read live
18//!
19//! Nothing about where the branches point, while the request is open. Every page
20//! resolves both refs when it renders, so a push to the source branch changes what the
21//! request proposes and a force-push is simply the new proposal. The cost is a handful
22//! of git questions per view; the alternative is a stored head that silently disagrees
23//! with the repository.
24
25use std::{collections::HashMap, time::SystemTime};
26
27use crate::domain::{
28 Actor, DomainError, IssueComment, IssueCommentId, MergeStrategy, ObjectId, OrgName,
29 PullRequest, PullRequestComment, PullRequestCommentId, PullRequestId, PullRequestState,
30 PushEvent, RefName, RepoName, RepoWrite, Repository, closes,
31 repository::{
32 IssueRepository, LabelRepository, MembershipRepository, OrgRepository, PullRequestCounts,
33 PullRequestRepository, PushEventRepository, RepoRepository, UserRepository,
34 },
35};
36
37use super::{
38 error::{Error, Result},
39 issue::{CommentView, Handles, readable_repo, writable_repo},
40 label::{LabelView, labels_by_pull},
41 paging::{Paged, clamp, offset, page_count},
42 port::{CommitTreeRequest, GitMerge, GitQuery, MergePreview},
43 push::record_push,
44};
45
46/// How many pull requests one page of a list shows.
47///
48/// The issue list's page, because a row reads the same way: two lines, read rather than
49/// scanned past.
50pub const PULL_LIMIT: usize = 50;
51
52/// How many commit subjects a squash message lists before it stops.
53///
54/// A squash of four hundred commits must not produce a four-hundred-line commit
55/// message; past this the message says how many were left out, which is the fact
56/// somebody reading `git log` a year later actually needs.
57pub const MAX_SQUASHED_COMMITS: usize = 50;
58
59/// What someone typed into the new-pull-request form. Raw — validation belongs to
60/// [`PullRequest::new`] and to the branch check in [`create_pull`].
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct NewPull {
63 pub title: String,
64 pub body: String,
65 pub source: RefName,
66 pub target: RefName,
67}
68
69/// An edit to a pull request's title and body. The branches are not editable — see
70/// [`PullRequest::edit`].
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct PullEdit {
73 pub title: String,
74 pub body: String,
75}
76
77/// A pull request as it appears in a listing.
78///
79/// The body is absent, like [`IssueSummary`](super::IssueSummary)'s; the two branches
80/// are not, because `source → target` is what distinguishes two requests with similar
81/// titles and it is the line the row is scanned by.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct PullSummary {
84 pub number: crate::domain::IssueNumber,
85 pub title: String,
86 pub state: PullRequestState,
87 /// The author's handle, or `None` if their account is gone. Rendered as "someone" —
88 /// a request outlives the account that opened it.
89 pub author: Option<OrgName>,
90 pub created_at: SystemTime,
91 pub comments: u64,
92 pub source_branch: RefName,
93 pub target_branch: RefName,
94 /// The labels this request carries — the same labels the issues wear, from the same
95 /// repository-wide set.
96 pub labels: Vec<LabelView>,
97}
98
99/// A repository's pull requests in one state, plus the counts the toolbar needs for all
100/// three.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct PullList {
103 /// Which state was asked for, carried back so a page cannot render the wrong tab as
104 /// current after a mangled query string.
105 pub state: PullRequestState,
106 pub open: u64,
107 pub merged: u64,
108 pub closed: u64,
109 /// One page of them, newest first, [`PULL_LIMIT`] to a page.
110 pub pulls: Paged<PullSummary>,
111 pub viewer_is_owner: bool,
112 /// The label `?label=` resolved to, or `None` when nothing was asked for. A filter
113 /// naming a label that has since been deleted resolves to `None` while the raw name
114 /// stays in the URL, which is what lets the page say what it is filtering on rather
115 /// than silently widening.
116 pub filter: Option<LabelView>,
117}
118
119/// Whether a pull request can be merged, and what stands in the way.
120///
121/// A parsed answer rather than an error for each way it can go nowhere, exactly as
122/// [`Compared`](super::Compared) is: a conflict, a deleted branch and a git that is too
123/// old are all real states of a real repository, and the merge box has a sentence for
124/// each. Turning any of them into a failure would put a 500 in front of an ordinary
125/// pull request.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub enum Mergeability {
128 /// The request is merged or closed, so the question does not arise.
129 NotOpen,
130 /// This server's `git` is older than [`merge_preview`](GitQuery::merge_preview)
131 /// needs. Read once at boot — see `GitFeatures` — so the box says so rather than
132 /// offering a button that cannot work.
133 Unsupported,
134 /// One of the two branches is not in the repository any more. Named, because which
135 /// one is the whole of what the reader can act on.
136 MissingBranch { branch: RefName },
137 /// Every commit on the source is already on the target: merging would do nothing.
138 NothingToMerge,
139 /// The two branches share no history, so there is no merge to compute.
140 Unrelated,
141 /// It merges. `fast_forward` is whether the target is an ancestor of the source, in
142 /// which case moving the ref is exact and no commit need be written at all.
143 Ready { fast_forward: bool },
144 /// It does not merge. The paths are what disagreed, in git's order.
145 Conflicted { paths: Vec<String> },
146}
147
148impl Mergeability {
149 pub fn is_ready(&self) -> bool {
150 matches!(self, Self::Ready { .. })
151 }
152
153 /// Which strategies the merge box may offer, in the order it should offer them.
154 ///
155 /// Empty unless the merge is actually ready. **Fast-forward leads when it is
156 /// available**: it is the exact answer there — the target simply catches up, with no
157 /// commit invented to say so — and offering a merge commit first would make the
158 /// tidier outcome the one you have to go looking for.
159 pub fn strategies(&self) -> Vec<MergeStrategy> {
160 match self {
161 Self::Ready { fast_forward: true } => vec![
162 MergeStrategy::FastForward,
163 MergeStrategy::Merge,
164 MergeStrategy::Squash,
165 ],
166 Self::Ready {
167 fast_forward: false,
168 } => vec![MergeStrategy::Merge, MergeStrategy::Squash],
169 _ => Vec::new(),
170 }
171 }
172}
173
174/// A pull request and its conversation.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct PullDetail {
177 pub number: crate::domain::IssueNumber,
178 pub title: String,
179 pub body: String,
180 pub state: PullRequestState,
181 pub author: Option<OrgName>,
182 pub created_at: SystemTime,
183 pub closed_at: Option<SystemTime>,
184 pub merged_at: Option<SystemTime>,
185 /// What landed, once it has. The page links it to the commit page.
186 pub merge_commit: Option<ObjectId>,
187 pub source_branch: RefName,
188 pub target_branch: RefName,
189 /// Oldest first — a conversation reads forwards.
190 pub comments: Vec<CommentView>,
191 pub viewer_is_owner: bool,
192 pub merge: Mergeability,
193 /// The labels this request carries.
194 pub labels: Vec<LabelView>,
195 /// Every label the repository has, for the owner's checkbox list. Empty for anyone
196 /// else, exactly as on an issue: no control to fill, no query to spend.
197 pub repo_labels: Vec<LabelView>,
198 /// Whether the source is the repository's default branch — the branch people push
199 /// to and clone into. Deleting that one after a merge is almost never what somebody
200 /// means, so the page draws the box unchecked; every other branch keeps the tidy
201 /// default. Read only when there is a merge button to draw, so an old or closed
202 /// request costs no extra `git` process.
203 pub source_is_default: bool,
204}
205
206/// What a merge did.
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct Merged {
209 /// The commit the target branch now points at.
210 pub commit: ObjectId,
211 /// Whether the source branch was deleted afterwards.
212 pub deleted_source: bool,
213 /// One per ref the merge moved, already recorded — the caller delivers the webhooks
214 /// for them, exactly as the push transport does.
215 pub events: Vec<PushEvent>,
216 /// The issues the request's `Closes #n` closed, in the order they were written.
217 /// Empty for a request that named none, and for one that named only issues already
218 /// closed.
219 pub closed: Vec<crate::domain::IssueNumber>,
220}
221
222/// Which kind of thing a repository's `#n` is.
223///
224/// Exists so `/issues/7` and `/pulls/7` can each send a visitor to the other rather than
225/// 404ing: the two share one number sequence precisely so that `#7` names one thing, and
226/// a cross-link written as `#7` cannot know which kind it found.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub enum Numbered {
229 Issue,
230 PullRequest,
231 /// Neither, or a repository the actor may not see — one answer, because telling
232 /// them apart would count the issues on a private repository.
233 Neither,
234}
235
236// --- Reads --------------------------------------------------------------------------
237
238/// A repository's pull requests in one state, optionally narrowed to one label.
239///
240/// `Ok(None)` means the repository is not there *or* the viewer may not see it, and the
241/// caller must render both identically — the rule [`view_repo`](super::view_repo) sets.
242///
243/// `filter` is a label **name**, straight off `?label=`, and behaves exactly as the
244/// issue list's does: a name the repository has no label for matches nothing, and
245/// **all three counts obey the filter**, so the toolbar cannot say "Open 12" above two
246/// rows. Paying for that costs the other two states' listings, and only when a filter is
247/// applied.
248#[allow(clippy::too_many_arguments)]
249pub async fn list_pulls(
250 actor: &Actor,
251 handle: &OrgName,
252 name: &RepoName,
253 state: PullRequestState,
254 filter: Option<&str>,
255 page: usize,
256 orgs: &impl OrgRepository,
257 memberships: &impl MembershipRepository,
258 repos: &impl RepoRepository,
259 pulls: &impl PullRequestRepository,
260 users: &impl UserRepository,
261 labels: &impl LabelRepository,
262) -> Result<Option<PullList>> {
263 let Some((repo, viewer_is_owner)) =
264 readable_repo(actor, handle, name, orgs, memberships, repos).await?
265 else {
266 return Ok(None);
267 };
268
269 // One query for every row's pills rather than one per row.
270 let on_pull = labels_by_pull(&repo, labels).await?;
271
272 let filter = match filter {
273 Some(name) => Some(labels.find_by_name(&repo.id, name).await?),
274 None => None,
275 };
276
277 let mut counts: PullRequestCounts = pulls.counts(&repo.id).await?;
278 let mut page = page;
279
280 // Two paths, the issue list's: which labels a request wears lives in a second table
281 // that is already read whole to render the pills, so a filtered list is narrowed in
282 // memory and paged from there. Unfiltered, the port pages it.
283 let mut listed = match filter.is_some() {
284 true => pulls.list_by_repo(&repo.id, state, 0, usize::MAX).await?,
285 false => {
286 let total = counts.of(state) as usize;
287 page = clamp(page, page_count(total, PULL_LIMIT));
288
289 pulls
290 .list_by_repo(&repo.id, state, offset(page, PULL_LIMIT), PULL_LIMIT)
291 .await?
292 }
293 };
294
295 if let Some(wanted) = &filter {
296 let carries = |pull: &PullRequest| {
297 wanted.as_ref().is_some_and(|wanted| {
298 on_pull
299 .get(&pull.id)
300 .is_some_and(|labels| labels.iter().any(|label| label.id == wanted.id))
301 })
302 };
303
304 let mut counted = PullRequestCounts::default();
305
306 for other in [
307 PullRequestState::Open,
308 PullRequestState::Merged,
309 PullRequestState::Closed,
310 ] {
311 let total = match other == state {
312 true => {
313 listed.retain(&carries);
314 listed.len() as u64
315 }
316 false => pulls
317 .list_by_repo(&repo.id, other, 0, usize::MAX)
318 .await?
319 .iter()
320 .filter(|pull| carries(pull))
321 .count() as u64,
322 };
323
324 match other {
325 PullRequestState::Open => counted.open = total,
326 PullRequestState::Merged => counted.merged = total,
327 PullRequestState::Closed => counted.closed = total,
328 }
329 }
330
331 counts = counted;
332 }
333
334 // The filtered list arrived whole and is cut here; the unfiltered one was cut by the
335 // port and arrives as its own page already.
336 let total = match filter.is_some() {
337 true => listed.len(),
338 false => counts.of(state) as usize,
339 };
340 let paged = match filter.is_some() {
341 true => Paged::slice(listed, page, PULL_LIMIT),
342 false => Paged::of(listed, total, page, PULL_LIMIT),
343 };
344
345 // One query for every row's comment count rather than one per row.
346 let comments: HashMap<PullRequestId, u64> =
347 pulls.comment_counts(&repo.id).await?.into_iter().collect();
348
349 let mut handles = Handles::default();
350 let mut summaries = Vec::with_capacity(paged.items.len());
351
352 for pull in paged.items {
353 summaries.push(PullSummary {
354 number: pull.number,
355 title: pull.title,
356 state: pull.state,
357 author: handles.of(&pull.author_id, orgs, users).await?,
358 created_at: pull.created_at,
359 comments: comments.get(&pull.id).copied().unwrap_or(0),
360 source_branch: pull.source_branch,
361 target_branch: pull.target_branch,
362 labels: on_pull.get(&pull.id).cloned().unwrap_or_default(),
363 });
364 }
365
366 Ok(Some(PullList {
367 state,
368 open: counts.open,
369 merged: counts.merged,
370 closed: counts.closed,
371 pulls: Paged::of(summaries, paged.total, paged.page, PULL_LIMIT),
372 viewer_is_owner,
373 filter: filter.flatten().map(LabelView::from),
374 }))
375}
376
377/// One pull request, its comments, and whether it can be merged right now.
378///
379/// `Ok(None)` covers an invisible repository, a missing one and a number that is not a
380/// pull request there. The caller 404s on all three and then asks
381/// [`numbered_thing`] whether the number is an *issue*, which is the one case where
382/// answering differently is right.
383///
384/// **Between two and four `git` questions**, and only for an open request: two
385/// resolutions (lines to the kept-alive `cat-file`, not processes), then a `merge-base`,
386/// then a `merge-tree` unless the merge base already settles it. A merged or closed
387/// request asks none — there is nothing left to decide.
388#[allow(clippy::too_many_arguments)]
389pub async fn view_pull(
390 actor: &Actor,
391 handle: &OrgName,
392 name: &RepoName,
393 number: crate::domain::IssueNumber,
394 merge_supported: bool,
395 orgs: &impl OrgRepository,
396 memberships: &impl MembershipRepository,
397 repos: &impl RepoRepository,
398 pulls: &impl PullRequestRepository,
399 users: &impl UserRepository,
400 queries: &impl GitQuery,
401 labels: &impl LabelRepository,
402) -> Result<Option<PullDetail>> {
403 let Some((repo, viewer_is_owner)) =
404 readable_repo(actor, handle, name, orgs, memberships, repos).await?
405 else {
406 return Ok(None);
407 };
408
409 let Some(pull) = pulls.find_by_number(&repo.id, number).await? else {
410 return Ok(None);
411 };
412
413 let mut handles = Handles::default();
414 let author = handles.of(&pull.author_id, orgs, users).await?;
415
416 let mut comments = Vec::new();
417 for comment in pulls.list_comments(&pull.id).await? {
418 comments.push(CommentView {
419 author: handles.of(&comment.author_id, orgs, users).await?,
420 body: comment.body,
421 created_at: comment.created_at,
422 });
423 }
424
425 let merge = mergeability(handle, name, &pull, merge_supported, queries).await?;
426
427 // One `symbolic-ref`, and only when the merge box will actually offer the checkbox
428 // this answers for. Nothing else on the page depends on it.
429 let source_is_default = if merge.strategies().is_empty() {
430 false
431 } else {
432 queries
433 .default_branch(handle, name)
434 .await?
435 .is_some_and(|branch| branch == pull.source_branch)
436 };
437
438 Ok(Some(PullDetail {
439 number: pull.number,
440 title: pull.title,
441 body: pull.body,
442 state: pull.state,
443 author,
444 created_at: pull.created_at,
445 closed_at: pull.closed_at,
446 merged_at: pull.merged_at,
447 merge_commit: pull.merge_commit,
448 source_branch: pull.source_branch,
449 target_branch: pull.target_branch,
450 comments,
451 viewer_is_owner,
452 merge,
453 labels: labels
454 .labels_for_pull(&pull.id)
455 .await?
456 .into_iter()
457 .map(LabelView::from)
458 .collect(),
459 // Only the owner has a control to fill, so only the owner pays for the query —
460 // the issue page's rule.
461 repo_labels: if viewer_is_owner {
462 labels
463 .list_by_repo(&repo.id)
464 .await?
465 .into_iter()
466 .map(LabelView::from)
467 .collect()
468 } else {
469 Vec::new()
470 },
471 source_is_default,
472 }))
473}
474
475/// What the new-request form should call a pull request between these two branches.
476///
477/// **The source's commit subject, but only when the source adds exactly one commit.**
478/// One commit is the case where the subject is already a title somebody wrote for this
479/// change, and reusing it saves retyping it. Two or more commits have no single subject
480/// that describes the whole, and picking the newest would name the change after whatever
481/// happened to be last — which is worse than an empty field, because it looks deliberate.
482///
483/// `Ok(None)` for every other case, including a repository the actor cannot read: this
484/// only ever fills in a form, so there is nothing to distinguish and nothing to leak.
485///
486/// **Three `git` questions**: two resolutions to the kept-alive `cat-file`, then one
487/// `rev-list` asked for two commits so that "exactly one" needs no separate count.
488#[allow(clippy::too_many_arguments)]
489pub async fn suggested_title(
490 actor: &Actor,
491 handle: &OrgName,
492 name: &RepoName,
493 source: &RefName,
494 target: &RefName,
495 orgs: &impl OrgRepository,
496 memberships: &impl MembershipRepository,
497 repos: &impl RepoRepository,
498 queries: &impl GitQuery,
499) -> Result<Option<String>> {
500 if readable_repo(actor, handle, name, orgs, memberships, repos)
501 .await?
502 .is_none()
503 {
504 return Ok(None);
505 }
506
507 let (target_ref, source_ref) = (branch_ref(target), branch_ref(source));
508 let (target_id, source_id) = tokio::try_join!(
509 queries.resolve(handle, name, &target_ref),
510 queries.resolve(handle, name, &source_ref),
511 )?;
512
513 let (Some(target_id), Some(source_id)) = (target_id, source_id) else {
514 return Ok(None);
515 };
516
517 // Two, so one answer covers both "how many" and "which one".
518 let commits = queries
519 .log_between(handle, name, Some(&target_id), &source_id, 0, 2)
520 .await?;
521
522 Ok(match commits.as_slice() {
523 [only] => Some(only.summary.clone()),
524 _ => None,
525 })
526}
527
528/// Whether a repository's `#n` is an issue, a pull request, or neither.
529///
530/// Asks the issues first only because that is the order they were built in; a number
531/// cannot be both, since one sequence hands it out once.
532#[allow(clippy::too_many_arguments)]
533pub async fn numbered_thing(
534 actor: &Actor,
535 handle: &OrgName,
536 name: &RepoName,
537 number: crate::domain::IssueNumber,
538 orgs: &impl OrgRepository,
539 memberships: &impl MembershipRepository,
540 repos: &impl RepoRepository,
541 issues: &impl IssueRepository,
542 pulls: &impl PullRequestRepository,
543) -> Result<Numbered> {
544 let Some((repo, _)) = readable_repo(actor, handle, name, orgs, memberships, repos).await?
545 else {
546 return Ok(Numbered::Neither);
547 };
548
549 if issues.find_by_number(&repo.id, number).await?.is_some() {
550 return Ok(Numbered::Issue);
551 }
552
553 if pulls.find_by_number(&repo.id, number).await?.is_some() {
554 return Ok(Numbered::PullRequest);
555 }
556
557 Ok(Numbered::Neither)
558}
559
560// --- Writes -------------------------------------------------------------------------
561
562/// Opens a pull request. Owner only.
563///
564/// Both branches are resolved before anything is written: a request against a branch
565/// that is not there can never do anything, and refusing it now is a message on a form
566/// rather than a broken page later. **Only the existence is checked, not the contents** —
567/// a request that turns out to conflict is an ordinary pull request and the whole point
568/// of having one.
569///
570/// The number is allocated from the repository's one sequence, shared with issues, and —
571/// like an issue's — **before** validation, so a rejected title burns one. A gap costs
572/// nothing next to a reused number.
573#[allow(clippy::too_many_arguments)]
574pub async fn create_pull(
575 actor: &Actor,
576 handle: &OrgName,
577 name: &RepoName,
578 spec: &NewPull,
579 now: SystemTime,
580 orgs: &impl OrgRepository,
581 memberships: &impl MembershipRepository,
582 repos: &impl RepoRepository,
583 issues: &impl IssueRepository,
584 pulls: &impl PullRequestRepository,
585 queries: &impl GitQuery,
586) -> Result<PullRequest> {
587 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
588
589 // Present because `writable_repo` already refused an anonymous actor; unwrapping
590 // would still be a panic waiting for the day that changes.
591 let author_id = actor.user_id().ok_or(DomainError::Forbidden)?.clone();
592
593 for (field, branch) in [
594 ("source branch", &spec.source),
595 ("target branch", &spec.target),
596 ] {
597 if queries.resolve(handle, name, branch).await?.is_none() {
598 return Err(DomainError::validation(
599 field,
600 format!("there is no branch called {branch} in this repository"),
601 )
602 .into());
603 }
604 }
605
606 let number = issues.next_number(&repo.id).await?;
607 let pull = PullRequest::new(
608 PullRequestId::generate(),
609 repo.id.clone(),
610 number,
611 spec.title.clone(),
612 spec.body.clone(),
613 author_id,
614 spec.source.clone(),
615 spec.target.clone(),
616 now,
617 )?;
618
619 pulls.save(&pull).await?;
620
621 Ok(pull)
622}
623
624/// Adds a comment. Owner only.
625///
626/// The request's `updated_at` moves with it: the conversation advanced even though what
627/// the request says did not.
628#[allow(clippy::too_many_arguments)]
629pub async fn comment_on_pull(
630 actor: &Actor,
631 handle: &OrgName,
632 name: &RepoName,
633 number: crate::domain::IssueNumber,
634 body: &str,
635 now: SystemTime,
636 orgs: &impl OrgRepository,
637 memberships: &impl MembershipRepository,
638 repos: &impl RepoRepository,
639 pulls: &impl PullRequestRepository,
640) -> Result<()> {
641 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
642 let mut pull = existing_pull(&repo, number, pulls).await?;
643 let author_id = actor.user_id().ok_or(DomainError::Forbidden)?.clone();
644
645 let comment = PullRequestComment::new(
646 PullRequestCommentId::generate(),
647 pull.id.clone(),
648 author_id,
649 body,
650 now,
651 )?;
652
653 pulls.add_comment(&comment).await?;
654
655 pull.touch(now);
656 pulls.save(&pull).await?;
657
658 Ok(())
659}
660
661/// Closes or reopens a pull request. Owner only.
662///
663/// `Merged` is not a state this can be asked for: landing a request is
664/// [`merge_pull`]'s, and a form that could set it would let somebody mark a branch as
665/// shipped without shipping it.
666#[allow(clippy::too_many_arguments)]
667pub async fn set_pull_state(
668 actor: &Actor,
669 handle: &OrgName,
670 name: &RepoName,
671 number: crate::domain::IssueNumber,
672 state: PullRequestState,
673 now: SystemTime,
674 orgs: &impl OrgRepository,
675 memberships: &impl MembershipRepository,
676 repos: &impl RepoRepository,
677 pulls: &impl PullRequestRepository,
678) -> Result<()> {
679 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
680 let mut pull = existing_pull(&repo, number, pulls).await?;
681
682 match state {
683 PullRequestState::Closed => pull.close(now),
684 PullRequestState::Open => pull.reopen(now),
685 PullRequestState::Merged => {
686 return Err(DomainError::validation(
687 "state",
688 "a pull request is merged by merging it, not by being marked merged",
689 )
690 .into());
691 }
692 }
693
694 pulls.save(&pull).await?;
695
696 Ok(())
697}
698
699/// Changes a pull request's title and body. Owner only.
700#[allow(clippy::too_many_arguments)]
701pub async fn edit_pull(
702 actor: &Actor,
703 handle: &OrgName,
704 name: &RepoName,
705 number: crate::domain::IssueNumber,
706 edit: &PullEdit,
707 now: SystemTime,
708 orgs: &impl OrgRepository,
709 memberships: &impl MembershipRepository,
710 repos: &impl RepoRepository,
711 pulls: &impl PullRequestRepository,
712) -> Result<()> {
713 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
714 let mut pull = existing_pull(&repo, number, pulls).await?;
715
716 // Validated before anything is written, so a rejected title leaves the request
717 // exactly as it was.
718 pull.edit(edit.title.clone(), edit.body.clone(), now)?;
719 pulls.save(&pull).await?;
720
721 Ok(())
722}
723
724/// Merges a pull request. Owner only, and the one write here that touches git.
725///
726/// # The order, and why it is that order
727///
728/// 1. **Authorize, and ask the repository whether it accepts contents at all.** An
729/// archived or importing repository refuses here, in the same words a `git push`
730/// gets, before a single object is written.
731/// 2. **Re-resolve both branches and re-check the merge.** Everything the page showed
732/// is a minute old; a branch may have moved or gone since. The mergeability answer
733/// used to *do* the merge is the one computed here, never the one the form was
734/// rendered from.
735/// 3. **Write the commit**, unless the strategy is a fast-forward, which needs none. A
736/// commit written and then not referenced is unreachable and costs only disk, which
737/// is why this is the step that may safely fail.
738/// 4. **Move the target**, guarded on where it was. This is the atomic step: a push
739/// that landed since step 2 makes it fail rather than overwriting what was pushed.
740/// 5. **Delete the source**, if asked, guarded the same way. A failure here leaves a
741/// merged request with a branch still on it, which is untidy and not wrong.
742/// 6. **Record the push events**, through [`record_push`] — the same function the git
743/// transport calls — so a merge reaches webhooks exactly as a push does. The caller
744/// delivers them.
745/// 7. **Mark it merged**, last, because [`PullRequest::merge`] refuses a second call and
746/// that refusal is only meaningful once the git side has actually happened.
747#[allow(clippy::too_many_arguments)]
748pub async fn merge_pull(
749 actor: &Actor,
750 handle: &OrgName,
751 name: &RepoName,
752 number: crate::domain::IssueNumber,
753 strategy: MergeStrategy,
754 delete_source: bool,
755 merge_supported: bool,
756 now: SystemTime,
757 orgs: &impl OrgRepository,
758 memberships: &impl MembershipRepository,
759 repos: &impl RepoRepository,
760 pulls: &impl PullRequestRepository,
761 events: &impl PushEventRepository,
762 issues: &impl IssueRepository,
763 queries: &impl GitQuery,
764 merges: &impl GitMerge,
765 author: &MergeAuthor,
766) -> Result<Merged> {
767 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
768
769 // The shared write guard, the one a push meets. Merging is a write to the contents,
770 // so an archived repository refuses it — while its issues and this very pull
771 // request's conversation stay open, which is the distinction `RepoWrite` exists for.
772 repo.refuse_writes(RepoWrite::Contents)?;
773
774 let mut pull = existing_pull(&repo, number, pulls).await?;
775
776 if !pull.state.is_open() {
777 return Err(DomainError::validation(
778 "state",
779 format!("this pull request is already {}", pull.state),
780 )
781 .into());
782 }
783
784 let (target_id, source_id) = resolved_ends(handle, name, &pull, queries).await?;
785 let (target_id, source_id) = match (target_id, source_id) {
786 (Some(target), Some(source)) => (target, source),
787 _ => {
788 return Err(DomainError::validation(
789 "branch",
790 "one of the branches is no longer in this repository",
791 )
792 .into());
793 }
794 };
795
796 // Recomputed rather than trusted from the form: the page that offered the button is
797 // a minute old, and a branch that moved since would otherwise be merged on stale
798 // information.
799 let ready = mergeability(handle, name, &pull, merge_supported, queries).await?;
800
801 if !ready.is_ready() {
802 return Err(DomainError::validation("merge", refusal(&ready)).into());
803 }
804
805 if !ready.strategies().contains(&strategy) {
806 return Err(DomainError::validation(
807 "strategy",
808 format!(
809 "{} is not available for this pull request",
810 strategy.label()
811 ),
812 )
813 .into());
814 }
815
816 let landed = match strategy {
817 // Nothing to write: the target simply catches up, and the commit it lands on is
818 // the source's own tip.
819 MergeStrategy::FastForward => source_id.clone(),
820 MergeStrategy::Merge | MergeStrategy::Squash => {
821 let MergePreview::Clean { tree } = queries
822 .merge_preview(handle, name, &target_id, &source_id)
823 .await?
824 else {
825 // Unreachable while `mergeability` said Ready, and cheaper to state
826 // than to reason about across two git calls.
827 return Err(DomainError::validation("merge", refusal(&ready)).into());
828 };
829
830 let (parents, message) = match strategy {
831 MergeStrategy::Squash => (
832 vec![target_id.clone()],
833 squash_message(handle, name, &pull, &target_id, &source_id, queries).await?,
834 ),
835 _ => (
836 vec![target_id.clone(), source_id.clone()],
837 merge_message(&pull),
838 ),
839 };
840
841 merges
842 .commit_tree(
843 handle,
844 name,
845 &CommitTreeRequest {
846 tree,
847 parents,
848 message,
849 author_name: author.name.clone(),
850 author_email: author.email.clone(),
851 now,
852 },
853 )
854 .await?
855 }
856 };
857
858 merges
859 .update_ref(handle, name, &pull.target_branch, &landed, &target_id)
860 .await?;
861
862 // The source is deleted only after the target has actually moved, so a guard that
863 // refuses the move cannot cost somebody their branch.
864 let deleted_source = match delete_source {
865 true => {
866 merges
867 .delete_ref(handle, name, &pull.source_branch, &source_id)
868 .await?;
869 true
870 }
871 false => false,
872 };
873
874 // Synthesised snapshots rather than two `for-each-ref` calls: this code moved the
875 // refs and knows exactly which ones and to what, where a push has to diff because
876 // receive-pack does not tell it. Going through `record_push` anyway is the point —
877 // one place decides what a ref movement means, so a merge and a push produce the
878 // same events and reach the same webhooks.
879 let mut before = vec![(branch_ref(&pull.target_branch), target_id.clone())];
880 let mut after = vec![(branch_ref(&pull.target_branch), landed.clone())];
881
882 if deleted_source {
883 before.push((branch_ref(&pull.source_branch), source_id.clone()));
884 // Absent from `after`, which is what `ref_changes` reads as a deletion.
885 }
886
887 after.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()));
888 before.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()));
889
890 let recorded = record_push(
891 actor,
892 handle,
893 name,
894 &before,
895 &after,
896 now,
897 orgs,
898 memberships,
899 repos,
900 events,
901 )
902 .await?;
903
904 pull.merge(landed.clone(), now)?;
905 pulls.save(&pull).await?;
906
907 // Last, and deliberately: closing an issue is a consequence of the merge, so it
908 // happens only once the merge is a fact. A failure here would leave the branch
909 // moved and an issue open, which is the right way round — the reverse would close
910 // issues for a merge that never landed.
911 let closed = close_referenced(&repo, &pull, actor, now, issues).await?;
912
913 Ok(Merged {
914 commit: landed,
915 deleted_source,
916 events: recorded,
917 closed,
918 })
919}
920
921/// Closes the issues a merged request said it closes, and says so on each.
922///
923/// **Issues only.** A `Closes #7` naming a pull request closes nothing: the numbers are
924/// one sequence, so `#7` may be either, and closing a *request* because another one
925/// merged is not a thing anybody means by the word.
926///
927/// An issue that is already closed is left alone rather than commented on twice, which
928/// makes a re-merge — impossible today, since merged is terminal — a no-op rather than a
929/// second announcement.
930async fn close_referenced(
931 repo: &Repository,
932 pull: &PullRequest,
933 actor: &Actor,
934 now: SystemTime,
935 issues: &impl IssueRepository,
936) -> Result<Vec<crate::domain::IssueNumber>> {
937 // The title as well as the body: a one-line request often says it there and nowhere
938 // else. Both are read at once so a number written in each is closed once.
939 let referenced = closes(&format!("{}\n{}", pull.title, pull.body));
940 let mut closed = Vec::new();
941
942 // The person who pressed Merge. `None` cannot happen — the write guard above refused
943 // an anonymous actor — and this refuses rather than inventing an author.
944 let author_id = actor.user_id().ok_or(DomainError::Forbidden)?.clone();
945
946 for number in referenced {
947 // Not the request itself, however it is written.
948 if number == pull.number {
949 continue;
950 }
951
952 let Some(mut issue) = issues.find_by_number(&repo.id, number).await? else {
953 continue;
954 };
955
956 if !issue.state.is_open() {
957 continue;
958 }
959
960 issues
961 .add_comment(&IssueComment::new(
962 IssueCommentId::generate(),
963 issue.id.clone(),
964 author_id.clone(),
965 format!(
966 "Closed by pull request #{}, merged into `{}`.",
967 pull.number, pull.target_branch
968 ),
969 now,
970 )?)
971 .await?;
972
973 issue.close(now);
974 issues.save(&issue).await?;
975
976 closed.push(number);
977 }
978
979 Ok(closed)
980}
981
982/// Who a merge commit is attributed to.
983///
984/// Passed in rather than resolved here because the caller already has it: the web layer
985/// reads an [`Identity`](super::Identity) for the top bar on every request, and asking
986/// again would be two lookups for one name.
987#[derive(Debug, Clone, PartialEq, Eq)]
988pub struct MergeAuthor {
989 pub name: String,
990 pub email: String,
991}
992
993// --- Working out whether it merges ----------------------------------------------------
994
995/// A branch name as a ref, so a **branch** is what gets resolved.
996///
997/// The bare name would let a tag or a sha answer: `git rev-parse spike` happily resolves
998/// a tag called `spike`, and a pull request whose target were a tag would have nothing to
999/// move at merge time. `refs/heads/` is also exactly what
1000/// [`GitMerge::update_ref`](super::port::GitMerge::update_ref) writes, so what is checked
1001/// and what is moved are the same ref by construction.
1002pub(super) fn branch_ref(branch: &RefName) -> RefName {
1003 RefName::from_trusted(format!("refs/heads/{branch}"))
1004}
1005
1006/// What both branches currently point at, or `None` for one that is gone.
1007async fn resolved_ends(
1008 handle: &OrgName,
1009 name: &RepoName,
1010 pull: &PullRequest,
1011 queries: &impl GitQuery,
1012) -> Result<(Option<ObjectId>, Option<ObjectId>)> {
1013 // Concurrently: two questions to a `cat-file` that is already running, so the page
1014 // waits on one round trip rather than two.
1015 // Bound before the join: a `branch_ref(..)` in an argument position is a temporary
1016 // the borrow the future holds would outlive.
1017 let (target_ref, source_ref) = (
1018 branch_ref(&pull.target_branch),
1019 branch_ref(&pull.source_branch),
1020 );
1021
1022 let (target, source) = tokio::try_join!(
1023 queries.resolve(handle, name, &target_ref),
1024 queries.resolve(handle, name, &source_ref),
1025 )?;
1026
1027 Ok((target, source))
1028}
1029
1030/// Decides what the merge box says.
1031///
1032/// The merge base does most of the work and costs one process: if it *is* the source,
1033/// everything is already on the target; if it is the target, the target can simply catch
1034/// up. Only the genuine three-way case pays for a `merge-tree`, which is the one where
1035/// the answer cannot be inferred.
1036async fn mergeability(
1037 handle: &OrgName,
1038 name: &RepoName,
1039 pull: &PullRequest,
1040 merge_supported: bool,
1041 queries: &impl GitQuery,
1042) -> Result<Mergeability> {
1043 if !pull.state.is_open() {
1044 return Ok(Mergeability::NotOpen);
1045 }
1046
1047 let (target_id, source_id) = resolved_ends(handle, name, pull, queries).await?;
1048
1049 // Reported before the version check: a branch that is gone is a fact about this
1050 // repository and stays true whatever git can do, and it is the more actionable of
1051 // the two.
1052 let Some(target_id) = target_id else {
1053 return Ok(Mergeability::MissingBranch {
1054 branch: pull.target_branch.clone(),
1055 });
1056 };
1057 let Some(source_id) = source_id else {
1058 return Ok(Mergeability::MissingBranch {
1059 branch: pull.source_branch.clone(),
1060 });
1061 };
1062
1063 let Some(base) = queries
1064 .merge_base(handle, name, &target_id, &source_id)
1065 .await?
1066 else {
1067 return Ok(Mergeability::Unrelated);
1068 };
1069
1070 if base == source_id {
1071 return Ok(Mergeability::NothingToMerge);
1072 }
1073
1074 if base == target_id {
1075 return Ok(Mergeability::Ready { fast_forward: true });
1076 }
1077
1078 if !merge_supported {
1079 return Ok(Mergeability::Unsupported);
1080 }
1081
1082 Ok(
1083 match queries
1084 .merge_preview(handle, name, &target_id, &source_id)
1085 .await?
1086 {
1087 MergePreview::Clean { .. } => Mergeability::Ready {
1088 fast_forward: false,
1089 },
1090 MergePreview::Conflicted { paths } => Mergeability::Conflicted { paths },
1091 },
1092 )
1093}
1094
1095/// The sentence a refused merge carries, built from why it was refused.
1096///
1097/// One place, so the form's refusal and the box's own line cannot disagree about what
1098/// is wrong.
1099fn refusal(ready: &Mergeability) -> String {
1100 match ready {
1101 Mergeability::NotOpen => "this pull request is not open".to_owned(),
1102 Mergeability::Unsupported => "merging needs git 2.38 or newer on the server".to_owned(),
1103 Mergeability::MissingBranch { branch } => {
1104 format!("there is no branch called {branch} in this repository any more")
1105 }
1106 Mergeability::NothingToMerge => {
1107 "there is nothing to merge — every commit is already on the target".to_owned()
1108 }
1109 Mergeability::Unrelated => {
1110 "the two branches share no history, so there is nothing to merge".to_owned()
1111 }
1112 Mergeability::Conflicted { paths } => match paths.len() {
1113 1 => format!("there is a conflict in {}", paths[0]),
1114 other => format!("there are conflicts in {other} files"),
1115 },
1116 Mergeability::Ready { .. } => "this pull request merges cleanly".to_owned(),
1117 }
1118}
1119
1120/// The message a merge commit carries.
1121///
1122/// git's own convention, which is what `git log --merges` and every tool that reads one
1123/// expects: a subject naming the request, then the title as the body. The number is in
1124/// the subject because that is the only place a merge commit can say which request it
1125/// came from once the branch is deleted.
1126fn merge_message(pull: &PullRequest) -> String {
1127 let mut message = format!(
1128 "Merge pull request #{} from {}\n\n{}",
1129 pull.number, pull.source_branch, pull.title
1130 );
1131
1132 if !pull.body.is_empty() {
1133 message.push_str("\n\n");
1134 message.push_str(&pull.body);
1135 }
1136
1137 message
1138}
1139
1140/// The message a squash commit carries.
1141///
1142/// The request's title with `(#n)` appended, in the shape a squashed commit is read in
1143/// a one-line log, then the body, then the subjects of the commits that were squashed —
1144/// which is the only surviving record of them once the branch is gone.
1145async fn squash_message(
1146 handle: &OrgName,
1147 name: &RepoName,
1148 pull: &PullRequest,
1149 target_id: &ObjectId,
1150 source_id: &ObjectId,
1151 queries: &impl GitQuery,
1152) -> Result<String> {
1153 let mut message = format!("{} (#{})", pull.title, pull.number);
1154
1155 if !pull.body.is_empty() {
1156 message.push_str("\n\n");
1157 message.push_str(&pull.body);
1158 }
1159
1160 // Asked for one more than is listed, so the message can say there were more without
1161 // a second count.
1162 let commits = queries
1163 .log_between(
1164 handle,
1165 name,
1166 Some(target_id),
1167 source_id,
1168 0,
1169 MAX_SQUASHED_COMMITS + 1,
1170 )
1171 .await?;
1172
1173 if commits.is_empty() {
1174 return Ok(message);
1175 }
1176
1177 message.push_str("\n\nSquashed commits:\n");
1178
1179 for commit in commits.iter().take(MAX_SQUASHED_COMMITS) {
1180 message.push_str(&format!("\n* {}", commit.summary));
1181 }
1182
1183 if commits.len() > MAX_SQUASHED_COMMITS {
1184 message.push_str("\n* …and more");
1185 }
1186
1187 Ok(message)
1188}
1189
1190/// The pull request a write is aimed at, or `NotFound`.
1191pub(super) async fn existing_pull(
1192 repo: &Repository,
1193 number: crate::domain::IssueNumber,
1194 pulls: &impl PullRequestRepository,
1195) -> Result<PullRequest> {
1196 pulls
1197 .find_by_number(&repo.id, number)
1198 .await?
1199 .ok_or(Error::Domain(DomainError::NotFound {
1200 entity: "pull request",
1201 }))
1202}
1203
1204#[cfg(test)]
1205mod tests {
1206 use std::time::Duration;
1207
1208 use super::*;
1209 use crate::{
1210 domain::{
1211 Email, IssueNumber, Membership, MembershipId, OrgId, Organization, PasswordHash,
1212 RepoId, Role, User, UserId, Visibility, repository::OrgRepository,
1213 },
1214 infrastructure::{
1215 git::{InMemoryGitMerge, InMemoryGitQuery},
1216 repository::{
1217 InMemoryIssueRepo, InMemoryLabelRepo, InMemoryMembershipRepo, InMemoryOrgRepo,
1218 InMemoryPullRequestRepo, InMemoryPushEventRepo, InMemoryRepoRepo, InMemoryUserRepo,
1219 },
1220 },
1221 };
1222
1223 fn at(seconds: u64) -> SystemTime {
1224 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
1225 }
1226
1227 struct Fixture {
1228 orgs: InMemoryOrgRepo,
1229 memberships: InMemoryMembershipRepo,
1230 repos: InMemoryRepoRepo,
1231 issues: InMemoryIssueRepo,
1232 pulls: InMemoryPullRequestRepo,
1233 events: InMemoryPushEventRepo,
1234 users: InMemoryUserRepo,
1235 labels: InMemoryLabelRepo,
1236 handle: OrgName,
1237 owner: Actor,
1238 member: Actor,
1239 stranger: Actor,
1240 }
1241
1242 /// One organisation with an owner and a plain member, a public repository `steid`
1243 /// and a private one `secret` — the issue fixture, so the two sets of tests are
1244 /// comparable.
1245 async fn fixture() -> Fixture {
1246 let orgs = InMemoryOrgRepo::new();
1247 let memberships = InMemoryMembershipRepo::new();
1248 let repos = InMemoryRepoRepo::new();
1249 let users = InMemoryUserRepo::new();
1250
1251 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
1252 orgs.save(&org).await.expect("save org");
1253
1254 let user_for = |email: &str| {
1255 User::new(
1256 UserId::generate(),
1257 Email::new(email).expect("valid email"),
1258 PasswordHash::from_trusted("$argon2id$test"),
1259 org.id.clone(),
1260 )
1261 };
1262
1263 let owner = user_for("owner@example.com");
1264 let member = user_for("member@example.com");
1265
1266 for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] {
1267 users.save(user).await.expect("save user");
1268 memberships
1269 .save(&Membership::new(
1270 MembershipId::generate(),
1271 org.id.clone(),
1272 user.id.clone(),
1273 role,
1274 ))
1275 .await
1276 .expect("save membership");
1277 }
1278
1279 for (name, visibility) in [
1280 ("steid", Visibility::Public),
1281 ("secret", Visibility::Private),
1282 ] {
1283 repos
1284 .save(
1285 &Repository::new(
1286 RepoId::generate(),
1287 org.id.clone(),
1288 name,
1289 None,
1290 visibility,
1291 at(1_000),
1292 )
1293 .expect("valid repo"),
1294 )
1295 .await
1296 .expect("save repo");
1297 }
1298
1299 Fixture {
1300 orgs,
1301 memberships,
1302 repos,
1303 issues: InMemoryIssueRepo::new(),
1304 pulls: InMemoryPullRequestRepo::new(),
1305 events: InMemoryPushEventRepo::new(),
1306 users,
1307 labels: InMemoryLabelRepo::new(),
1308 handle: org.name.clone(),
1309 owner: Actor::User(owner.id),
1310 member: Actor::User(member.id),
1311 stranger: Actor::Anonymous,
1312 }
1313 }
1314
1315 fn repo(name: &str) -> RepoName {
1316 RepoName::new(name).expect("valid name")
1317 }
1318
1319 fn rev(value: &str) -> RefName {
1320 RefName::new(value).expect("valid revision")
1321 }
1322
1323 fn oid(prefix: &str) -> ObjectId {
1324 ObjectId::from_trusted(format!("{prefix:0>40}"))
1325 }
1326
1327 /// What the use cases actually resolve. A pull request's ends are **branches**, so
1328 /// everything goes through `refs/heads/` — a bare name would let a tag answer.
1329 fn heads(branch: &str) -> String {
1330 format!("refs/heads/{branch}")
1331 }
1332
1333 /// A repository where `main` and `spike` are different commits, and their merge base
1334 /// is a third — the genuine three-way case, which is the one that needs a preview.
1335 fn three_way() -> InMemoryGitQuery {
1336 InMemoryGitQuery::new()
1337 .with_resolved(&heads("main"), "a")
1338 .with_resolved(&heads("spike"), "b")
1339 .with_merge_base(&oid("c").to_string())
1340 }
1341
1342 async fn open(f: &Fixture, name: &str, source: &str, target: &str) -> PullRequest {
1343 open_with(f, name, source, target, &three_way()).await
1344 }
1345
1346 async fn open_with(
1347 f: &Fixture,
1348 name: &str,
1349 source: &str,
1350 target: &str,
1351 git: &InMemoryGitQuery,
1352 ) -> PullRequest {
1353 create_pull(
1354 &f.owner,
1355 &f.handle,
1356 &repo(name),
1357 &NewPull {
1358 title: format!("Merge {source}"),
1359 body: "the body".to_owned(),
1360 source: rev(source),
1361 target: rev(target),
1362 },
1363 at(2_000),
1364 &f.orgs,
1365 &f.memberships,
1366 &f.repos,
1367 &f.issues,
1368 &f.pulls,
1369 git,
1370 )
1371 .await
1372 .expect("should open")
1373 }
1374
1375 async fn viewed(
1376 f: &Fixture,
1377 actor: &Actor,
1378 name: &str,
1379 number: IssueNumber,
1380 git: &InMemoryGitQuery,
1381 ) -> Option<PullDetail> {
1382 view_pull(
1383 actor,
1384 &f.handle,
1385 &repo(name),
1386 number,
1387 true,
1388 &f.orgs,
1389 &f.memberships,
1390 &f.repos,
1391 &f.pulls,
1392 &f.users,
1393 git,
1394 &f.labels,
1395 )
1396 .await
1397 .expect("should read")
1398 }
1399
1400 #[allow(clippy::too_many_arguments)]
1401 async fn merge(
1402 f: &Fixture,
1403 actor: &Actor,
1404 name: &str,
1405 number: IssueNumber,
1406 strategy: MergeStrategy,
1407 delete_source: bool,
1408 git: &InMemoryGitQuery,
1409 merges: &InMemoryGitMerge,
1410 ) -> Result<Merged> {
1411 merge_pull(
1412 actor,
1413 &f.handle,
1414 &repo(name),
1415 number,
1416 strategy,
1417 delete_source,
1418 true,
1419 at(5_000),
1420 &f.orgs,
1421 &f.memberships,
1422 &f.repos,
1423 &f.pulls,
1424 &f.events,
1425 &f.issues,
1426 git,
1427 merges,
1428 &MergeAuthor {
1429 name: "Ada Lovelace".to_owned(),
1430 email: "ada@example.com".to_owned(),
1431 },
1432 )
1433 .await
1434 }
1435
1436 // --- opening ----------------------------------------------------------------------
1437
1438 #[tokio::test]
1439 async fn a_pull_request_draws_from_the_same_sequence_as_issues() {
1440 // The property the whole `#n` cross-link scheme rests on: one sequence, so a
1441 // number is never handed out twice on a repository.
1442 let f = fixture().await;
1443
1444 let first = open(&f, "steid", "spike", "main").await;
1445 let second = open(&f, "steid", "spike", "main").await;
1446
1447 assert_eq!(first.number, IssueNumber::from_trusted(1));
1448 assert_eq!(second.number, IssueNumber::from_trusted(2));
1449
1450 let issue = crate::application::create_issue(
1451 &f.owner,
1452 &f.handle,
1453 &repo("steid"),
1454 &crate::application::NewIssue {
1455 title: "an issue".to_owned(),
1456 body: String::new(),
1457 },
1458 at(2_000),
1459 &f.orgs,
1460 &f.memberships,
1461 &f.repos,
1462 &f.issues,
1463 )
1464 .await
1465 .expect("should open");
1466
1467 assert_eq!(issue.number, IssueNumber::from_trusted(3));
1468 }
1469
1470 #[tokio::test]
1471 async fn a_branch_that_is_not_there_is_refused_on_the_form() {
1472 let f = fixture().await;
1473 // Everything resolves except what is named here, because the fake resolves any
1474 // revision by default — so this asks for a repository with no branches at all.
1475 let empty = InMemoryGitQuery::empty();
1476
1477 let refused = create_pull(
1478 &f.owner,
1479 &f.handle,
1480 &repo("steid"),
1481 &NewPull {
1482 title: "Merge a ghost".to_owned(),
1483 body: String::new(),
1484 source: rev("ghost"),
1485 target: rev("main"),
1486 },
1487 at(2_000),
1488 &f.orgs,
1489 &f.memberships,
1490 &f.repos,
1491 &f.issues,
1492 &f.pulls,
1493 &empty,
1494 )
1495 .await;
1496
1497 assert!(matches!(
1498 refused,
1499 Err(Error::Domain(DomainError::Validation { .. }))
1500 ));
1501 }
1502
1503 #[tokio::test]
1504 async fn only_the_owner_may_open_one() {
1505 let f = fixture().await;
1506 let git = three_way();
1507
1508 for (actor, expected_forbidden) in [(&f.member, true), (&f.stranger, true)] {
1509 let refused = create_pull(
1510 actor,
1511 &f.handle,
1512 &repo("steid"),
1513 &NewPull {
1514 title: "Merge spike".to_owned(),
1515 body: String::new(),
1516 source: rev("spike"),
1517 target: rev("main"),
1518 },
1519 at(2_000),
1520 &f.orgs,
1521 &f.memberships,
1522 &f.repos,
1523 &f.issues,
1524 &f.pulls,
1525 &git,
1526 )
1527 .await;
1528
1529 assert_eq!(
1530 matches!(refused, Err(Error::Domain(DomainError::Forbidden))),
1531 expected_forbidden,
1532 "a public repository is visible, so the refusal names permission"
1533 );
1534 }
1535 }
1536
1537 #[tokio::test]
1538 async fn a_stranger_sees_nothing_on_a_private_repository() {
1539 let f = fixture().await;
1540 let git = three_way();
1541 let pull = open(&f, "secret", "spike", "main").await;
1542
1543 assert!(
1544 viewed(&f, &f.stranger, "secret", pull.number, &git)
1545 .await
1546 .is_none()
1547 );
1548 assert!(
1549 list_pulls(
1550 &f.stranger,
1551 &f.handle,
1552 &repo("secret"),
1553 PullRequestState::Open,
1554 None,
1555 1,
1556 &f.orgs,
1557 &f.memberships,
1558 &f.repos,
1559 &f.pulls,
1560 &f.users,
1561 &f.labels,
1562 )
1563 .await
1564 .expect("should list")
1565 .is_none()
1566 );
1567 }
1568
1569 // --- mergeability -------------------------------------------------------------------
1570
1571 #[tokio::test]
1572 async fn a_three_way_merge_that_works_offers_a_merge_commit_and_a_squash() {
1573 let f = fixture().await;
1574 let git = three_way();
1575 let pull = open_with(&f, "steid", "spike", "main", &git).await;
1576
1577 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
1578 .await
1579 .expect("visible");
1580
1581 assert_eq!(
1582 detail.merge,
1583 Mergeability::Ready {
1584 fast_forward: false
1585 }
1586 );
1587 assert_eq!(
1588 detail.merge.strategies(),
1589 vec![MergeStrategy::Merge, MergeStrategy::Squash],
1590 "a fast-forward is not on offer when the target is not an ancestor"
1591 );
1592 }
1593
1594 #[tokio::test]
1595 async fn a_target_that_is_an_ancestor_leads_with_the_fast_forward() {
1596 let f = fixture().await;
1597 // The merge base *is* the target, so the target can simply catch up.
1598 let git = InMemoryGitQuery::new()
1599 .with_resolved(&heads("main"), "a")
1600 .with_resolved(&heads("spike"), "b")
1601 .with_merge_base(&oid("a").to_string());
1602 let pull = open_with(&f, "steid", "spike", "main", &git).await;
1603
1604 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
1605 .await
1606 .expect("visible");
1607
1608 assert_eq!(detail.merge, Mergeability::Ready { fast_forward: true });
1609 assert_eq!(
1610 detail.merge.strategies().first(),
1611 Some(&MergeStrategy::FastForward),
1612 "the exact answer is offered first"
1613 );
1614 }
1615
1616 #[tokio::test]
1617 async fn a_source_already_contained_in_the_target_has_nothing_to_merge() {
1618 let f = fixture().await;
1619 let git = InMemoryGitQuery::new()
1620 .with_resolved(&heads("main"), "a")
1621 .with_resolved(&heads("spike"), "b")
1622 .with_merge_base(&oid("b").to_string());
1623 let pull = open_with(&f, "steid", "spike", "main", &git).await;
1624
1625 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
1626 .await
1627 .expect("visible");
1628
1629 assert_eq!(detail.merge, Mergeability::NothingToMerge);
1630 assert!(detail.merge.strategies().is_empty());
1631 }
1632
1633 #[tokio::test]
1634 async fn a_conflict_names_the_files_and_offers_nothing() {
1635 let f = fixture().await;
1636 let git = three_way().with_conflicts(&["src/lib.rs", "Cargo.toml"]);
1637 let pull = open_with(&f, "steid", "spike", "main", &git).await;
1638
1639 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
1640 .await
1641 .expect("visible");
1642
1643 assert_eq!(
1644 detail.merge,
1645 Mergeability::Conflicted {
1646 paths: vec!["src/lib.rs".to_owned(), "Cargo.toml".to_owned()],
1647 }
1648 );
1649 assert!(detail.merge.strategies().is_empty());
1650 }
1651
1652 #[tokio::test]
1653 async fn a_deleted_source_branch_is_named_rather_than_reported_as_a_conflict() {
1654 // A force-push is fine — the request follows the branch — but a *deleted*
1655 // branch is a state the page has to say out loud.
1656 let f = fixture().await;
1657 let git = three_way();
1658 let pull = open_with(&f, "steid", "spike", "main", &git).await;
1659
1660 let gone = InMemoryGitQuery::empty().with_resolved(&heads("main"), "a");
1661 let detail = viewed(&f, &f.owner, "steid", pull.number, &gone)
1662 .await
1663 .expect("visible");
1664
1665 assert_eq!(
1666 detail.merge,
1667 Mergeability::MissingBranch {
1668 branch: rev("spike")
1669 }
1670 );
1671 }
1672
1673 #[tokio::test]
1674 async fn an_ordinary_source_branch_is_offered_for_deletion() {
1675 let f = fixture().await;
1676 let git = three_way();
1677 let pull = open_with(&f, "steid", "spike", "main", &git).await;
1678
1679 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
1680 .await
1681 .expect("visible");
1682
1683 assert!(!detail.source_is_default);
1684 }
1685
1686 #[tokio::test]
1687 async fn merging_the_default_branch_does_not_propose_deleting_it() {
1688 // `main` into a long-lived branch is a real thing to do, and the tidy default
1689 // would delete the branch everybody clones.
1690 let f = fixture().await;
1691 let git = InMemoryGitQuery::new()
1692 .with_resolved(&heads("main"), "a")
1693 .with_resolved(&heads("release"), "b")
1694 .with_merge_base(&oid("c").to_string());
1695 let pull = open_with(&f, "steid", "main", "release", &git).await;
1696
1697 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
1698 .await
1699 .expect("visible");
1700
1701 assert!(!detail.merge.strategies().is_empty());
1702 assert!(detail.source_is_default);
1703 }
1704
1705 #[tokio::test]
1706 async fn an_old_git_says_so_rather_than_offering_a_button() {
1707 let f = fixture().await;
1708 let git = three_way();
1709 let pull = open_with(&f, "steid", "spike", "main", &git).await;
1710
1711 let detail = view_pull(
1712 &f.owner,
1713 &f.handle,
1714 &repo("steid"),
1715 pull.number,
1716 false,
1717 &f.orgs,
1718 &f.memberships,
1719 &f.repos,
1720 &f.pulls,
1721 &f.users,
1722 &git,
1723 &f.labels,
1724 )
1725 .await
1726 .expect("should read")
1727 .expect("visible");
1728
1729 assert_eq!(detail.merge, Mergeability::Unsupported);
1730 assert!(detail.merge.strategies().is_empty());
1731 }
1732
1733 #[tokio::test]
1734 async fn a_merged_request_asks_git_nothing() {
1735 let f = fixture().await;
1736 let git = three_way();
1737 let merges = InMemoryGitMerge::writing("f");
1738 let pull = open_with(&f, "steid", "spike", "main", &git).await;
1739
1740 merge(
1741 &f,
1742 &f.owner,
1743 "steid",
1744 pull.number,
1745 MergeStrategy::Merge,
1746 false,
1747 &git,
1748 &merges,
1749 )
1750 .await
1751 .expect("should merge");
1752
1753 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
1754 .await
1755 .expect("visible");
1756
1757 assert_eq!(detail.merge, Mergeability::NotOpen);
1758 assert_eq!(detail.state, PullRequestState::Merged);
1759 }
1760
1761 // --- merging ---------------------------------------------------------------------
1762
1763 /// Opens an issue, so a pull request has something to close.
1764 async fn open_issue(f: &Fixture, name: &str, title: &str) -> crate::domain::Issue {
1765 crate::application::create_issue(
1766 &f.owner,
1767 &f.handle,
1768 &repo(name),
1769 &crate::application::NewIssue {
1770 title: title.to_owned(),
1771 body: String::new(),
1772 },
1773 at(1_000),
1774 &f.orgs,
1775 &f.memberships,
1776 &f.repos,
1777 &f.issues,
1778 )
1779 .await
1780 .expect("should open")
1781 }
1782
1783 async fn issue_state(
1784 f: &Fixture,
1785 name: &str,
1786 number: IssueNumber,
1787 ) -> crate::domain::IssueState {
1788 let repository = f
1789 .repos
1790 .find_by_org_and_name(
1791 &f.orgs
1792 .find_by_name(&f.handle)
1793 .await
1794 .expect("query")
1795 .expect("org")
1796 .id,
1797 &repo(name),
1798 )
1799 .await
1800 .expect("query")
1801 .expect("repo");
1802
1803 f.issues
1804 .find_by_number(&repository.id, number)
1805 .await
1806 .expect("query")
1807 .expect("issue")
1808 .state
1809 }
1810
1811 #[tokio::test]
1812 async fn merging_closes_the_issues_the_request_said_it_closes() {
1813 let f = fixture().await;
1814 let git = three_way();
1815 let merges = InMemoryGitMerge::writing("f");
1816
1817 let bug = open_issue(&f, "steid", "Blame is slow").await;
1818 let other = open_issue(&f, "steid", "Docs are thin").await;
1819
1820 let pull = create_pull(
1821 &f.owner,
1822 &f.handle,
1823 &repo("steid"),
1824 &NewPull {
1825 title: format!("Speed blame up (closes #{})", bug.number),
1826 // A bare mention is not a closure, which is what keeps `#n` usable for
1827 // pointing at context.
1828 body: format!("See #{} for the background.", other.number),
1829 source: rev("spike"),
1830 target: rev("main"),
1831 },
1832 at(2_000),
1833 &f.orgs,
1834 &f.memberships,
1835 &f.repos,
1836 &f.issues,
1837 &f.pulls,
1838 &git,
1839 )
1840 .await
1841 .expect("should open");
1842
1843 let merged = merge(
1844 &f,
1845 &f.owner,
1846 "steid",
1847 pull.number,
1848 MergeStrategy::Merge,
1849 false,
1850 &git,
1851 &merges,
1852 )
1853 .await
1854 .expect("should merge");
1855
1856 assert_eq!(merged.closed, vec![bug.number]);
1857 assert_eq!(
1858 issue_state(&f, "steid", bug.number).await,
1859 crate::domain::IssueState::Closed
1860 );
1861 assert_eq!(
1862 issue_state(&f, "steid", other.number).await,
1863 crate::domain::IssueState::Open,
1864 "a mention is not a closure"
1865 );
1866
1867 // The issue says what closed it, and links the request by number.
1868 let comments = f
1869 .issues
1870 .list_comments(&bug.id)
1871 .await
1872 .expect("should read comments");
1873 assert_eq!(comments.len(), 1);
1874 assert!(
1875 comments[0]
1876 .body
1877 .contains(&format!("pull request #{}", pull.number)),
1878 "got {:?}",
1879 comments[0].body
1880 );
1881 }
1882
1883 #[tokio::test]
1884 async fn a_closing_reference_to_a_pull_request_closes_nothing() {
1885 // The numbers are one sequence, so `#7` may be either kind — and closing a
1886 // *request* because another merged is not what anybody means by the word.
1887 let f = fixture().await;
1888 let git = three_way();
1889 let merges = InMemoryGitMerge::writing("f");
1890
1891 let first = open_with(&f, "steid", "spike", "main", &git).await;
1892 let second = create_pull(
1893 &f.owner,
1894 &f.handle,
1895 &repo("steid"),
1896 &NewPull {
1897 title: "Follow-up".to_owned(),
1898 body: format!("Closes #{}.", first.number),
1899 source: rev("tidy"),
1900 target: rev("main"),
1901 },
1902 at(2_000),
1903 &f.orgs,
1904 &f.memberships,
1905 &f.repos,
1906 &f.issues,
1907 &f.pulls,
1908 &git,
1909 )
1910 .await
1911 .expect("should open");
1912
1913 let merged = merge(
1914 &f,
1915 &f.owner,
1916 "steid",
1917 second.number,
1918 MergeStrategy::Merge,
1919 false,
1920 &git,
1921 &merges,
1922 )
1923 .await
1924 .expect("should merge");
1925
1926 assert!(merged.closed.is_empty());
1927 assert!(
1928 f.pulls
1929 .find_by_number(&second.repo_id, first.number)
1930 .await
1931 .expect("query")
1932 .expect("still there")
1933 .state
1934 .is_open()
1935 );
1936 }
1937
1938 #[tokio::test]
1939 async fn an_issue_that_is_already_closed_is_left_alone() {
1940 let f = fixture().await;
1941 let git = three_way();
1942 let merges = InMemoryGitMerge::writing("f");
1943
1944 let bug = open_issue(&f, "steid", "Blame is slow").await;
1945
1946 crate::application::set_issue_state(
1947 &f.owner,
1948 &f.handle,
1949 &repo("steid"),
1950 bug.number,
1951 crate::domain::IssueState::Closed,
1952 at(2_500),
1953 &f.orgs,
1954 &f.memberships,
1955 &f.repos,
1956 &f.issues,
1957 )
1958 .await
1959 .expect("should close");
1960
1961 let pull = create_pull(
1962 &f.owner,
1963 &f.handle,
1964 &repo("steid"),
1965 &NewPull {
1966 title: "Speed blame up".to_owned(),
1967 body: format!("Fixes #{}.", bug.number),
1968 source: rev("spike"),
1969 target: rev("main"),
1970 },
1971 at(3_000),
1972 &f.orgs,
1973 &f.memberships,
1974 &f.repos,
1975 &f.issues,
1976 &f.pulls,
1977 &git,
1978 )
1979 .await
1980 .expect("should open");
1981
1982 let merged = merge(
1983 &f,
1984 &f.owner,
1985 "steid",
1986 pull.number,
1987 MergeStrategy::Merge,
1988 false,
1989 &git,
1990 &merges,
1991 )
1992 .await
1993 .expect("should merge");
1994
1995 // No second announcement on something that was already shut.
1996 assert!(merged.closed.is_empty());
1997 assert!(
1998 f.issues
1999 .list_comments(&bug.id)
2000 .await
2001 .expect("comments")
2002 .is_empty()
2003 );
2004 }
2005
2006 #[tokio::test]
2007 async fn a_merge_commit_takes_the_target_first_and_moves_the_branch() {
2008 let f = fixture().await;
2009 let git = three_way();
2010 let merges = InMemoryGitMerge::writing("f");
2011 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2012
2013 let merged = merge(
2014 &f,
2015 &f.owner,
2016 "steid",
2017 pull.number,
2018 MergeStrategy::Merge,
2019 false,
2020 &git,
2021 &merges,
2022 )
2023 .await
2024 .expect("should merge");
2025
2026 let written = merges.commits();
2027 assert_eq!(written.len(), 1);
2028 assert_eq!(
2029 written[0].parents,
2030 vec![oid("a"), oid("b")],
2031 "the target is the first parent, so its history stays the first-parent line"
2032 );
2033 assert!(
2034 written[0]
2035 .message
2036 .starts_with("Merge pull request #1 from spike")
2037 );
2038 assert_eq!(written[0].author_name, "Ada Lovelace");
2039
2040 // The ref moved to what was written, guarded on where it was.
2041 let updates = merges.updates();
2042 assert_eq!(updates.len(), 1);
2043 assert_eq!(updates[0].branch, rev("main"));
2044 assert_eq!(updates[0].old, oid("a"));
2045 assert_eq!(updates[0].new, Some(merged.commit.clone()));
2046 assert!(!merged.deleted_source);
2047 }
2048
2049 #[tokio::test]
2050 async fn a_squash_has_one_parent_and_lists_what_it_squashed() {
2051 let f = fixture().await;
2052 let git = three_way().with_log(vec![
2053 crate::domain::CommitSummary {
2054 id: oid("b"),
2055 summary: "second thing".to_owned(),
2056 author_name: "Ada".to_owned(),
2057 committed_at: at(3_000),
2058 },
2059 crate::domain::CommitSummary {
2060 id: oid("c"),
2061 summary: "first thing".to_owned(),
2062 author_name: "Ada".to_owned(),
2063 committed_at: at(2_500),
2064 },
2065 ]);
2066 let merges = InMemoryGitMerge::writing("f");
2067 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2068
2069 merge(
2070 &f,
2071 &f.owner,
2072 "steid",
2073 pull.number,
2074 MergeStrategy::Squash,
2075 false,
2076 &git,
2077 &merges,
2078 )
2079 .await
2080 .expect("should merge");
2081
2082 let written = merges.commits();
2083 assert_eq!(written[0].parents, vec![oid("a")], "one parent, not two");
2084 assert!(written[0].message.starts_with("Merge spike (#1)"));
2085 assert!(
2086 written[0].message.contains("* second thing")
2087 && written[0].message.contains("* first thing"),
2088 "the squashed subjects are the only surviving record of them: {:?}",
2089 written[0].message
2090 );
2091 }
2092
2093 #[tokio::test]
2094 async fn a_fast_forward_writes_no_commit_at_all() {
2095 let f = fixture().await;
2096 let git = InMemoryGitQuery::new()
2097 .with_resolved(&heads("main"), "a")
2098 .with_resolved(&heads("spike"), "b")
2099 .with_merge_base(&oid("a").to_string());
2100 let merges = InMemoryGitMerge::new();
2101 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2102
2103 let merged = merge(
2104 &f,
2105 &f.owner,
2106 "steid",
2107 pull.number,
2108 MergeStrategy::FastForward,
2109 false,
2110 &git,
2111 &merges,
2112 )
2113 .await
2114 .expect("should merge");
2115
2116 assert!(merges.commits().is_empty(), "nothing to write");
2117 assert_eq!(
2118 merged.commit,
2119 oid("b"),
2120 "the target lands on the source's own tip"
2121 );
2122 }
2123
2124 #[tokio::test]
2125 async fn a_fast_forward_is_refused_where_it_would_not_be_exact() {
2126 let f = fixture().await;
2127 let git = three_way();
2128 let merges = InMemoryGitMerge::new();
2129 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2130
2131 let refused = merge(
2132 &f,
2133 &f.owner,
2134 "steid",
2135 pull.number,
2136 MergeStrategy::FastForward,
2137 false,
2138 &git,
2139 &merges,
2140 )
2141 .await;
2142
2143 assert!(matches!(
2144 refused,
2145 Err(Error::Domain(DomainError::Validation { .. }))
2146 ));
2147 assert!(merges.updates().is_empty(), "nothing moved");
2148 }
2149
2150 #[tokio::test]
2151 async fn deleting_the_source_happens_after_the_target_has_moved() {
2152 // The order matters: a guard that refuses the move must not cost somebody their
2153 // branch.
2154 let f = fixture().await;
2155 let git = three_way();
2156 let merges = InMemoryGitMerge::writing("f");
2157 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2158
2159 let merged = merge(
2160 &f,
2161 &f.owner,
2162 "steid",
2163 pull.number,
2164 MergeStrategy::Merge,
2165 true,
2166 &git,
2167 &merges,
2168 )
2169 .await
2170 .expect("should merge");
2171
2172 let updates = merges.updates();
2173 assert_eq!(updates.len(), 2);
2174 assert_eq!(updates[0].branch, rev("main"), "the target moves first");
2175 assert_eq!(updates[1].branch, rev("spike"));
2176 assert_eq!(updates[1].new, None, "the source is deleted");
2177 assert!(merged.deleted_source);
2178 }
2179
2180 #[tokio::test]
2181 async fn a_merge_records_a_push_event_for_every_ref_it_moved() {
2182 // Through `record_push`, the function the git transport calls, so a merge and a
2183 // push produce the same events and reach the same webhooks.
2184 let f = fixture().await;
2185 let git = three_way();
2186 let merges = InMemoryGitMerge::writing("f");
2187 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2188
2189 let merged = merge(
2190 &f,
2191 &f.owner,
2192 "steid",
2193 pull.number,
2194 MergeStrategy::Merge,
2195 true,
2196 &git,
2197 &merges,
2198 )
2199 .await
2200 .expect("should merge");
2201
2202 let names: Vec<&str> = merged
2203 .events
2204 .iter()
2205 .map(|event| event.ref_name.as_str())
2206 .collect();
2207 assert_eq!(names, vec!["refs/heads/main", "refs/heads/spike"]);
2208
2209 let target = &merged.events[0];
2210 assert_eq!(target.before, oid("a"));
2211 assert_eq!(target.after, merged.commit);
2212
2213 let source = &merged.events[1];
2214 assert_eq!(source.before, oid("b"));
2215 assert!(
2216 crate::domain::is_zero(&source.after),
2217 "a deleted branch is recorded as a deletion"
2218 );
2219 }
2220
2221 #[tokio::test]
2222 async fn a_branch_that_moved_since_the_page_loaded_makes_the_merge_lose_cleanly() {
2223 let f = fixture().await;
2224 let git = three_way();
2225 let merges = InMemoryGitMerge::stale();
2226 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2227
2228 let refused = merge(
2229 &f,
2230 &f.owner,
2231 "steid",
2232 pull.number,
2233 MergeStrategy::Merge,
2234 false,
2235 &git,
2236 &merges,
2237 )
2238 .await;
2239
2240 assert!(
2241 matches!(refused, Err(Error::GitMerge(error)) if error.is_stale()),
2242 "expected staleness"
2243 );
2244
2245 // Still open, so the page can be reloaded and the merge tried again.
2246 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
2247 .await
2248 .expect("visible");
2249 assert_eq!(detail.state, PullRequestState::Open);
2250 }
2251
2252 #[tokio::test]
2253 async fn merging_a_conflicted_request_is_refused_before_anything_is_written() {
2254 let f = fixture().await;
2255 let git = three_way();
2256 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2257
2258 // Conflicting only now, which is exactly the case the recheck exists for: the
2259 // page that offered the button was rendered before the conflict arrived.
2260 let conflicted = three_way().with_conflicts(&["src/lib.rs"]);
2261 let merges = InMemoryGitMerge::new();
2262
2263 let refused = merge(
2264 &f,
2265 &f.owner,
2266 "steid",
2267 pull.number,
2268 MergeStrategy::Merge,
2269 false,
2270 &conflicted,
2271 &merges,
2272 )
2273 .await;
2274
2275 assert!(matches!(
2276 refused,
2277 Err(Error::Domain(DomainError::Validation { .. }))
2278 ));
2279 assert!(merges.commits().is_empty());
2280 assert!(merges.updates().is_empty());
2281 }
2282
2283 #[tokio::test]
2284 async fn merging_twice_lands_one_commit() {
2285 let f = fixture().await;
2286 let git = three_way();
2287 let merges = InMemoryGitMerge::writing("f");
2288 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2289
2290 merge(
2291 &f,
2292 &f.owner,
2293 "steid",
2294 pull.number,
2295 MergeStrategy::Merge,
2296 false,
2297 &git,
2298 &merges,
2299 )
2300 .await
2301 .expect("should merge");
2302
2303 let again = merge(
2304 &f,
2305 &f.owner,
2306 "steid",
2307 pull.number,
2308 MergeStrategy::Merge,
2309 false,
2310 &git,
2311 &merges,
2312 )
2313 .await;
2314
2315 assert!(matches!(
2316 again,
2317 Err(Error::Domain(DomainError::Validation { .. }))
2318 ));
2319 assert_eq!(merges.commits().len(), 1, "the second submit wrote nothing");
2320 }
2321
2322 #[tokio::test]
2323 async fn an_archived_repository_refuses_a_merge_and_keeps_its_conversation() {
2324 let f = fixture().await;
2325 let git = three_way();
2326 let merges = InMemoryGitMerge::writing("f");
2327 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2328
2329 let org = f
2330 .orgs
2331 .find_by_name(&f.handle)
2332 .await
2333 .expect("should read")
2334 .expect("the org exists");
2335 let mut stored = f
2336 .repos
2337 .find_by_org_and_name(&org.id, &repo("steid"))
2338 .await
2339 .expect("should read")
2340 .expect("the repository exists");
2341 stored.archived = true;
2342 f.repos.save(&stored).await.expect("save repo");
2343
2344 let refused = merge(
2345 &f,
2346 &f.owner,
2347 "steid",
2348 pull.number,
2349 MergeStrategy::Merge,
2350 false,
2351 &git,
2352 &merges,
2353 )
2354 .await;
2355
2356 assert!(
2357 matches!(refused, Err(Error::Domain(DomainError::Archived))),
2358 "the same refusal a push gets"
2359 );
2360 assert!(merges.commits().is_empty());
2361
2362 // The conversation stays open — archiving says the code is finished, not that
2363 // nobody may discuss it.
2364 comment_on_pull(
2365 &f.owner,
2366 &f.handle,
2367 &repo("steid"),
2368 pull.number,
2369 "still worth doing",
2370 at(6_000),
2371 &f.orgs,
2372 &f.memberships,
2373 &f.repos,
2374 &f.pulls,
2375 )
2376 .await
2377 .expect("commenting is not a write to the contents");
2378 }
2379
2380 #[tokio::test]
2381 async fn only_the_owner_may_merge() {
2382 let f = fixture().await;
2383 let git = three_way();
2384 let merges = InMemoryGitMerge::writing("f");
2385 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2386
2387 for actor in [&f.member, &f.stranger] {
2388 let refused = merge(
2389 &f,
2390 actor,
2391 "steid",
2392 pull.number,
2393 MergeStrategy::Merge,
2394 false,
2395 &git,
2396 &merges,
2397 )
2398 .await;
2399
2400 assert!(matches!(
2401 refused,
2402 Err(Error::Domain(DomainError::Forbidden))
2403 ));
2404 }
2405
2406 assert!(merges.updates().is_empty());
2407 }
2408
2409 // --- state, and the shared numbering -------------------------------------------------
2410
2411 #[tokio::test]
2412 async fn a_request_cannot_be_marked_merged_by_the_state_form() {
2413 let f = fixture().await;
2414 let git = three_way();
2415 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2416
2417 let refused = set_pull_state(
2418 &f.owner,
2419 &f.handle,
2420 &repo("steid"),
2421 pull.number,
2422 PullRequestState::Merged,
2423 at(6_000),
2424 &f.orgs,
2425 &f.memberships,
2426 &f.repos,
2427 &f.pulls,
2428 )
2429 .await;
2430
2431 assert!(matches!(
2432 refused,
2433 Err(Error::Domain(DomainError::Validation { .. }))
2434 ));
2435 }
2436
2437 #[tokio::test]
2438 async fn the_counts_move_between_the_three_states() {
2439 let f = fixture().await;
2440 let git = three_way();
2441 let merges = InMemoryGitMerge::writing("f");
2442
2443 let merged = open_with(&f, "steid", "spike", "main", &git).await;
2444 let closed = open_with(&f, "steid", "other", "main", &git).await;
2445 open_with(&f, "steid", "third", "main", &git).await;
2446
2447 merge(
2448 &f,
2449 &f.owner,
2450 "steid",
2451 merged.number,
2452 MergeStrategy::Merge,
2453 false,
2454 &git,
2455 &merges,
2456 )
2457 .await
2458 .expect("should merge");
2459
2460 set_pull_state(
2461 &f.owner,
2462 &f.handle,
2463 &repo("steid"),
2464 closed.number,
2465 PullRequestState::Closed,
2466 at(6_000),
2467 &f.orgs,
2468 &f.memberships,
2469 &f.repos,
2470 &f.pulls,
2471 )
2472 .await
2473 .expect("should close");
2474
2475 let listed = list_pulls(
2476 &f.owner,
2477 &f.handle,
2478 &repo("steid"),
2479 PullRequestState::Open,
2480 None,
2481 1,
2482 &f.orgs,
2483 &f.memberships,
2484 &f.repos,
2485 &f.pulls,
2486 &f.users,
2487 &f.labels,
2488 )
2489 .await
2490 .expect("should list")
2491 .expect("visible");
2492
2493 assert_eq!((listed.open, listed.merged, listed.closed), (1, 1, 1));
2494 assert_eq!(listed.pulls.items.len(), 1);
2495 }
2496
2497 #[tokio::test]
2498 async fn the_second_page_of_pull_requests_starts_where_the_first_ended() {
2499 let f = fixture().await;
2500 let git = three_way();
2501
2502 for n in 1..=(PULL_LIMIT + 3) {
2503 open_with(&f, "steid", &format!("spike-{n}"), "main", &git).await;
2504 }
2505
2506 // Built inline rather than through a closure: `repo("steid")` is a temporary,
2507 // and a closure returning the future would let the borrow outlive it.
2508 let name = repo("steid");
2509 let first = list_pulls(
2510 &f.owner,
2511 &f.handle,
2512 &name,
2513 PullRequestState::Open,
2514 None,
2515 1,
2516 &f.orgs,
2517 &f.memberships,
2518 &f.repos,
2519 &f.pulls,
2520 &f.users,
2521 &f.labels,
2522 )
2523 .await
2524 .expect("should list")
2525 .expect("visible");
2526 let second = list_pulls(
2527 &f.owner,
2528 &f.handle,
2529 &name,
2530 PullRequestState::Open,
2531 None,
2532 2,
2533 &f.orgs,
2534 &f.memberships,
2535 &f.repos,
2536 &f.pulls,
2537 &f.users,
2538 &f.labels,
2539 )
2540 .await
2541 .expect("should list")
2542 .expect("visible");
2543
2544 assert_eq!(first.pulls.items.len(), PULL_LIMIT);
2545 assert_eq!(second.pulls.items.len(), 3);
2546 assert_eq!(second.pulls.offset(), PULL_LIMIT);
2547 // Newest first, which for a monotonic sequence is descending number.
2548 assert_eq!(
2549 first.pulls.items[0].number,
2550 IssueNumber::from_trusted((PULL_LIMIT + 3) as u64)
2551 );
2552 }
2553
2554 #[tokio::test]
2555 async fn a_number_says_which_kind_of_thing_it_is() {
2556 // What lets `/issues/7` and `/pulls/7` send a visitor to the other rather than
2557 // 404ing at a `#7` somebody wrote in a body.
2558 let f = fixture().await;
2559 let git = three_way();
2560 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2561
2562 let issue = crate::application::create_issue(
2563 &f.owner,
2564 &f.handle,
2565 &repo("steid"),
2566 &crate::application::NewIssue {
2567 title: "an issue".to_owned(),
2568 body: String::new(),
2569 },
2570 at(2_000),
2571 &f.orgs,
2572 &f.memberships,
2573 &f.repos,
2574 &f.issues,
2575 )
2576 .await
2577 .expect("should open");
2578
2579 let name = repo("steid");
2580 let kind = async |number| {
2581 numbered_thing(
2582 &f.owner,
2583 &f.handle,
2584 &name,
2585 number,
2586 &f.orgs,
2587 &f.memberships,
2588 &f.repos,
2589 &f.issues,
2590 &f.pulls,
2591 )
2592 .await
2593 .expect("should read")
2594 };
2595
2596 assert_eq!(kind(pull.number).await, Numbered::PullRequest);
2597 assert_eq!(kind(issue.number).await, Numbered::Issue);
2598 assert_eq!(kind(IssueNumber::from_trusted(99)).await, Numbered::Neither);
2599 }
2600
2601 #[tokio::test]
2602 async fn a_stranger_is_told_a_private_repository_has_neither() {
2603 // Not "no such number" versus "there is one" — that would count the issues on a
2604 // repository they cannot see.
2605 let f = fixture().await;
2606 let git = three_way();
2607 let pull = open_with(&f, "secret", "spike", "main", &git).await;
2608
2609 assert_eq!(
2610 numbered_thing(
2611 &f.stranger,
2612 &f.handle,
2613 &repo("secret"),
2614 pull.number,
2615 &f.orgs,
2616 &f.memberships,
2617 &f.repos,
2618 &f.issues,
2619 &f.pulls,
2620 )
2621 .await
2622 .expect("should read"),
2623 Numbered::Neither
2624 );
2625 }
2626
2627 #[tokio::test]
2628 async fn a_comment_moves_the_request_without_changing_what_it_says() {
2629 let f = fixture().await;
2630 let git = three_way();
2631 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2632
2633 comment_on_pull(
2634 &f.owner,
2635 &f.handle,
2636 &repo("steid"),
2637 pull.number,
2638 " looks good ",
2639 at(6_000),
2640 &f.orgs,
2641 &f.memberships,
2642 &f.repos,
2643 &f.pulls,
2644 )
2645 .await
2646 .expect("should comment");
2647
2648 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
2649 .await
2650 .expect("visible");
2651
2652 assert_eq!(detail.comments.len(), 1);
2653 assert_eq!(detail.comments[0].body, "looks good");
2654 assert_eq!(detail.title, pull.title);
2655 }
2656
2657 #[tokio::test]
2658 async fn an_edit_cannot_move_the_branches() {
2659 let f = fixture().await;
2660 let git = three_way();
2661 let pull = open_with(&f, "steid", "spike", "main", &git).await;
2662
2663 edit_pull(
2664 &f.owner,
2665 &f.handle,
2666 &repo("steid"),
2667 pull.number,
2668 &PullEdit {
2669 title: "A better title".to_owned(),
2670 body: "and a better body".to_owned(),
2671 },
2672 at(6_000),
2673 &f.orgs,
2674 &f.memberships,
2675 &f.repos,
2676 &f.pulls,
2677 )
2678 .await
2679 .expect("should edit");
2680
2681 let detail = viewed(&f, &f.owner, "steid", pull.number, &git)
2682 .await
2683 .expect("visible");
2684
2685 assert_eq!(detail.title, "A better title");
2686 assert_eq!(detail.source_branch, rev("spike"));
2687 assert_eq!(detail.target_branch, rev("main"));
2688 }
2689
2690 // --- the suggested title -----------------------------------------------------------
2691
2692 #[tokio::test]
2693 async fn a_branch_with_one_commit_lends_the_form_its_subject() {
2694 // One commit is the case where a subject is already a title somebody wrote for
2695 // this change.
2696 let f = fixture().await;
2697 let git = three_way().with_log(vec![crate::domain::CommitSummary {
2698 id: oid("b"),
2699 summary: "perf: cache highlighting per blob object id".to_owned(),
2700 author_name: "Ada".to_owned(),
2701 committed_at: at(3_000),
2702 }]);
2703
2704 assert_eq!(
2705 suggested_title(
2706 &f.owner,
2707 &f.handle,
2708 &repo("steid"),
2709 &rev("spike"),
2710 &rev("main"),
2711 &f.orgs,
2712 &f.memberships,
2713 &f.repos,
2714 &git,
2715 )
2716 .await
2717 .expect("should read"),
2718 Some("perf: cache highlighting per blob object id".to_owned())
2719 );
2720 }
2721
2722 #[tokio::test]
2723 async fn a_branch_with_two_commits_suggests_nothing() {
2724 // Naming the change after whichever commit happened to be last is worse than an
2725 // empty field, because it looks deliberate.
2726 let f = fixture().await;
2727 let summary = |id: &str, text: &str| crate::domain::CommitSummary {
2728 id: oid(id),
2729 summary: text.to_owned(),
2730 author_name: "Ada".to_owned(),
2731 committed_at: at(3_000),
2732 };
2733 let git = three_way().with_log(vec![
2734 summary("b", "docs: note what the cache costs"),
2735 summary("c", "perf: cache highlighting per blob object id"),
2736 ]);
2737
2738 assert_eq!(
2739 suggested_title(
2740 &f.owner,
2741 &f.handle,
2742 &repo("steid"),
2743 &rev("spike"),
2744 &rev("main"),
2745 &f.orgs,
2746 &f.memberships,
2747 &f.repos,
2748 &git,
2749 )
2750 .await
2751 .expect("should read"),
2752 None
2753 );
2754 }
2755}