steid

@jamesgill /

1//! Pull requests — `/{handle}/repos/{name}/pulls`.
2//!
3//! The list, the new-request form, and one request under three sub-tabs: **Conversation**
4//! (the body, the comments and the merge box), **Commits** and **Files changed**.
5//!
6//! The two tabs after the first are a comparison of `target...source`, rendered by
7//! [`commit`](super::commit)'s own components — the same three-dot comparison the compare
8//! page shows, which is exactly what a pull request means by "what this branch adds".
9//! Nothing about the diff is reimplemented here; `compare_revisions` is the use case and
10//! `commit_log`, `diff_view` and `diff_stats` are the renderers, so a pull request's files
11//! and a comparison's files cannot drift apart.
12//!
13//! **Bodies are markdown, rendered through [`markdown`](super::markdown)**, which never
14//! passes source HTML through — the property that makes rendering user content on the
15//! session cookie's origin safe at all. See that module before changing anything here.
16//!
17//! `/issues/{n}` and `/pulls/{n}` **redirect to each other** for a number that is the
18//! other kind. The two share one sequence precisely so `#7` names one thing, and a
19//! cross-reference written as `#7` cannot know which kind it found.
20
21use std::time::SystemTime;
22
23use serde::Deserialize;
24use topcoat::{
25 Result,
26 context::Cx,
27 icon::{icon, iconify::iconify_icon},
28 router::{
29 StatusCode,
30 content::Form,
31 error::{bad_request, forbidden, not_found},
32 page, path_param, query_params,
33 },
34 view::{attributes, component, view},
35};
36
37use crate::{
38 application::{
39 CommentView, Compared, Error, MergeAuthor, Mergeability, NewPull, Numbered, PullDetail,
40 PullEdit, PullList, PullSummary, RefList, RepoView, comment_on_pull, compare_revisions,
41 create_pull, edit_pull, list_pulls, list_refs, merge_pull, numbered_thing, set_pull_state,
42 suggested_title, view_pull,
43 },
44 components::{
45 badge::{BadgeVariant, badge},
46 button::{ButtonSize, ButtonVariant, button, button_variants},
47 flash::{FlashKind, flash},
48 input::input,
49 label::label,
50 textarea::textarea,
51 },
52 domain::{DomainError, IssueNumber, MergeStrategy, OrgName, PullRequestState, RefName},
53};
54
55use super::{
56 browse::{ago, commit_log, encode, timestamp},
57 commit::{commit_url, diff_view, took_too_long, unwrap_page},
58 context::{
59 current_actor, git_features, identity, issues, labels, location, memberships, merges, orgs,
60 public_origin, pulls, push_events, queries, repos, server_error, users, webhook_sender,
61 webhooks,
62 },
63 issues::issue_url,
64 labels::{Filtering, label_pill, labels_url},
65 layout::wide,
66 markdown,
67 paging::{Pages, list_pages, requested_page, showing},
68 repo::{Tab, repo_for, repo_header},
69};
70
71/// `{number}` from the path, raw — validation is [`IssueNumber`]'s job.
72#[path_param]
73struct Number(str);
74
75/// `?state=merged|closed`, `?label=bug` and `?page=N`. Anything else in `state` means
76/// open.
77#[query_params(error = bad_request)]
78struct StateQuery {
79 state: Option<String>,
80 label: Option<String>,
81 page: Option<String>,
82}
83
84/// `?source=&target=`, prefilling the new-request form from the compare page.
85#[query_params(error = bad_request)]
86struct PrefillQuery {
87 source: Option<String>,
88 target: Option<String>,
89}
90
91/// `?page=N` on the Commits sub-tab. The diff on Files changed does not page — it is
92/// what the whole range changes either way, exactly as a comparison's does.
93#[query_params(error = bad_request)]
94struct PageQuery {
95 page: Option<String>,
96}
97
98#[derive(Debug, Deserialize)]
99struct PullForm {
100 title: String,
101 body: String,
102 source: String,
103 target: String,
104}
105
106#[derive(Debug, Deserialize)]
107struct EditForm {
108 title: String,
109 body: String,
110}
111
112#[derive(Debug, Deserialize)]
113struct CommentForm {
114 body: String,
115}
116
117#[derive(Debug, Deserialize)]
118struct StateForm {
119 state: String,
120}
121
122#[derive(Debug, Deserialize)]
123struct MergeForm {
124 strategy: String,
125 /// An unticked checkbox is not submitted at all, which is why this is an `Option`
126 /// and not a `bool`: `serde` would refuse the missing field.
127 delete_source: Option<String>,
128}
129
130/// Which sub-tab of one pull request is being looked at.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132enum Sub {
133 Conversation,
134 Commits,
135 Files,
136}
137
138// --- URLs ---------------------------------------------------------------------------
139
140pub(super) fn pulls_url(handle: &str, name: &str) -> String {
141 format!("/{handle}/repos/{name}/pulls")
142}
143
144/// The list's URL with whichever of state, label and page it needs.
145///
146/// One builder for all three, the reason the issue list has one: paging out of a filter
147/// would silently widen the list, switching state must not lose the label, and neither
148/// must strand the reader on page 4 of a list that now has one page.
149fn listed_url(
150 handle: &str,
151 name: &str,
152 state: PullRequestState,
153 filter: &str,
154 page: usize,
155) -> String {
156 let mut url = pulls_url(handle, name);
157 let mut parts = Vec::new();
158
159 if !state.is_open() {
160 parts.push(format!("state={state}"));
161 }
162
163 if !filter.is_empty() {
164 parts.push(format!("label={}", encode(filter, false)));
165 }
166
167 // Page 1 is the bare URL: a `?page=1` in a shared link says nothing and makes two
168 // URLs for one page.
169 if page > 1 {
170 parts.push(format!("page={page}"));
171 }
172
173 if !parts.is_empty() {
174 url.push('?');
175 url.push_str(&parts.join("&"));
176 }
177
178 url
179}
180
181pub(super) fn pull_url(handle: &str, name: &str, number: IssueNumber) -> String {
182 format!("/{handle}/repos/{name}/pulls/{number}")
183}
184
185/// The new-request form, prefilled with two branches.
186///
187/// Each half is percent-encoded on its own, so a slash inside a branch name survives as
188/// part of the value rather than becoming anything else.
189pub(super) fn new_pull_url(handle: &str, name: &str, source: &str, target: &str) -> String {
190 format!(
191 "/{handle}/repos/{name}/pulls/new?source={}&target={}",
192 encode(source, false),
193 encode(target, false)
194 )
195}
196
197// --- Resolution ---------------------------------------------------------------------
198
199/// The number in the path, or 404.
200///
201/// A number that does not parse names nothing, exactly like one that is out of range,
202/// and answering differently would tell a prober which of the two they had found.
203fn number_for(cx: &Cx) -> Result<IssueNumber> {
204 path_param::<Number>(cx)
205 .parse::<IssueNumber>()
206 .map_err(|_| not_found().into())
207}
208
209/// What looking a `#n` up found.
210///
211/// Three answers rather than two, because a number that is the *other* kind of thing is
212/// neither what was asked for nor a 404: it is a number this repository has handed out,
213/// and the visitor belongs at the other page. That is what makes a `#7` written in a
214/// body a link that lands whatever kind of thing it names.
215///
216/// Generic over what was being looked for, so the issues page and this one share it —
217/// and, with it, share [`elsewhere_or_missing`] and cannot disagree about when a number
218/// is worth redirecting.
219pub(super) enum Found<T> {
220 /// Boxed because the detail is much the larger variant and clippy is right about
221 /// what carrying it by value would cost on every return.
222 Here(Box<T>),
223 /// The URL to send them to, with a 303.
224 Elsewhere(String),
225}
226
227/// One pull request, or where the visitor should be instead.
228async fn detail(cx: &Cx, repo: &RepoView, number: IssueNumber) -> Result<Found<PullDetail>> {
229 let found = view_pull(
230 &current_actor(cx).await?,
231 &repo.handle,
232 &repo.name,
233 number,
234 git_features(cx).merge_tree,
235 &orgs(cx),
236 &memberships(cx),
237 &repos(cx),
238 &pulls(cx),
239 &users(cx),
240 &queries(cx),
241 &labels(cx),
242 )
243 .await
244 .map_err(server_error)?;
245
246 match found {
247 Some(detail) => Ok(Found::Here(Box::new(detail))),
248 None => elsewhere_or_missing(cx, repo, number, Numbered::Issue).await,
249 }
250}
251
252/// Where a missing number should send the visitor: the *other* kind of thing if that is
253/// what it turns out to be, and a 404 if it is neither.
254///
255/// Shared by both directions — this module's pages and the issues page's — so the two
256/// cannot end up disagreeing about when a number is worth redirecting.
257///
258/// The redirect is spelled as a URL rather than as a response because `#[page]` must
259/// return a view, so the caller emits `SEE_OTHER` plus a `Location` inside its own
260/// `view!` — see [`location`].
261pub(super) async fn elsewhere_or_missing<T>(
262 cx: &Cx,
263 repo: &RepoView,
264 number: IssueNumber,
265 wanted: Numbered,
266) -> Result<Found<T>> {
267 let found = numbered_thing(
268 &current_actor(cx).await?,
269 &repo.handle,
270 &repo.name,
271 number,
272 &orgs(cx),
273 &memberships(cx),
274 &repos(cx),
275 &issues(cx),
276 &pulls(cx),
277 )
278 .await
279 .map_err(server_error)?;
280
281 let handle = repo.handle.as_str();
282 let name = repo.name.as_str();
283
284 // Only the kind the caller is *not* showing is worth a redirect. Anything else — the
285 // number belongs to nothing, or to a repository this actor cannot read — is a 404,
286 // one answer for both so a prober cannot count what is on a private repository.
287 match (found == wanted, wanted) {
288 (true, Numbered::Issue) => Ok(Found::Elsewhere(issue_url(handle, name, number))),
289 (true, Numbered::PullRequest) => Ok(Found::Elsewhere(pull_url(handle, name, number))),
290 _ => Err(not_found().into()),
291 }
292}
293
294/// The request a failed write re-renders from.
295///
296/// A write only reaches here having already resolved the pull request, so a number that
297/// has become an *issue* in the meantime is not a redirect worth following — it is a
298/// state nothing can produce, and a 404 is the honest answer.
299async fn reread(cx: &Cx, repo: &RepoView, number: IssueNumber) -> Result<Box<PullDetail>> {
300 match detail(cx, repo, number).await? {
301 Found::Here(pull) => Ok(pull),
302 Found::Elsewhere(_) => Err(not_found().into()),
303 }
304}
305
306/// The repository, refused for anyone who does not own it.
307///
308/// A non-owner gets a 404 rather than a 403, the rule the settings and issues pages
309/// already set: a 403 on a repository they cannot see would confirm it exists.
310async fn owned_repo(cx: &Cx) -> Result<RepoView> {
311 let repo = repo_for(cx).await?;
312
313 if !repo.viewer_is_owner {
314 return Err(not_found().into());
315 }
316
317 Ok(repo)
318}
319
320/// Turns a use case failure into either a message to re-render with, or a response.
321fn write_failure(error: Error) -> std::result::Result<String, topcoat::Error> {
322 match error {
323 Error::Domain(DomainError::Validation { field, reason }) => {
324 Ok(format!("That {field} is no good: {reason}."))
325 }
326 // The repository is archived or still importing. The reason is the useful part
327 // and it is the same sentence a `git push` gets, so it is shown rather than
328 // turned into a status code.
329 Error::Domain(DomainError::Archived) => {
330 Ok("This repository is archived, so nothing can be merged into it.".to_owned())
331 }
332 Error::Domain(DomainError::Unavailable { reason, .. }) => {
333 Ok(format!("This repository is unavailable: {reason}"))
334 }
335 // Somebody pushed between the page rendering and the button being pressed. A
336 // message, not a failure: reloading shows the new state and the merge can be
337 // tried again.
338 Error::GitMerge(merge) if merge.is_stale() => Ok(merge.to_string()),
339 Error::Domain(DomainError::Forbidden) => Err(forbidden().into()),
340 Error::Domain(DomainError::NotFound { .. }) => Err(not_found().into()),
341 other => Err(server_error(std::io::Error::other(other.to_string()))),
342 }
343}
344
345// --- The list -------------------------------------------------------------------------
346
347#[page("/{handle}/repos/{name}/pulls")]
348async fn pulls_page(cx: &Cx) -> Result {
349 let repo = repo_for(cx).await?;
350 let query = query_params::<StateQuery>(cx)?;
351
352 // An unrecognised `?state=` shows the open list rather than erroring: this is a link
353 // someone may have mangled, not a form, and the only thing it can reveal is which
354 // requests are open anyway.
355 let state = query
356 .state
357 .as_deref()
358 .and_then(|value| value.parse::<PullRequestState>().ok())
359 .unwrap_or(PullRequestState::Open);
360
361 // Kept as the raw string as well as resolved, so a filter naming a label that has
362 // been deleted still says what it was filtering on rather than silently widening.
363 let filter = query.label.as_deref().filter(|name| !name.is_empty());
364
365 let listed = list_pulls(
366 &current_actor(cx).await?,
367 &repo.handle,
368 &repo.name,
369 state,
370 filter,
371 requested_page(query.page.as_deref()),
372 &orgs(cx),
373 &memberships(cx),
374 &repos(cx),
375 &pulls(cx),
376 &users(cx),
377 &labels(cx),
378 )
379 .await
380 .map_err(server_error)?
381 // `repo_for` already resolved the repository as visible, so `None` here means it
382 // vanished between the two reads. A 404 is the honest answer to that.
383 .ok_or_else(not_found)?;
384
385 view! {
386 wide(
387 repo_header(repo: &repo, rev: "", active: Tab::Pulls)
388 pull_list(
389 handle: repo.handle.as_str(),
390 name: repo.name.as_str(),
391 listed: &listed,
392 filter: filter.unwrap_or(""),
393 )
394 )
395 }
396}
397
398/// The three state filters, the label filter, and the way in, on one row.
399#[component]
400async fn pulls_toolbar(handle: &str, name: &str, listed: &PullList, filter: &str) -> Result {
401 // The primary colour is not used here: which list you are looking at is marked the
402 // same way the issues toolbar marks it, by contrast rather than by hue, so the merge
403 // box below stays the one coloured thing on the page.
404 let current = |active: bool| {
405 if active {
406 "text-foreground"
407 } else {
408 "text-muted-foreground hover:text-foreground"
409 }
410 };
411
412 view! {
413 <div class="mb-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
414 for (state, count) in [
415 (PullRequestState::Open, listed.open),
416 (PullRequestState::Merged, listed.merged),
417 (PullRequestState::Closed, listed.closed),
418 ] {
419 // The state links keep the label filter and drop the page, exactly as
420 // the issues toolbar's do.
421 <a
422 href=(listed_url(handle, name, state, filter, 1))
423 class=(format!(
424 "flex items-center gap-1.5 {}",
425 current(listed.state == state)
426 ))
427 >
428 state_icon(state: state, muted: listed.state != state)
429 (label_for(state))
430 <span class="font-mono text-xs text-muted-foreground">(count)</span>
431 </a>
432 }
433
434 // The active filter, with the way out of it. Drawn from the raw query value
435 // rather than only when it resolved, so a filter on a label that has since
436 // been deleted still says what it is filtering on.
437 if !filter.is_empty() {
438 <span class="flex items-center gap-1.5">
439 if let Some(pill) = listed.filter.as_ref() {
440 label_pill(handle: handle, name: name, pill: pill, to: Filtering::Pulls)
441 } else {
442 <span class="label-pill label-gray">(filter)</span>
443 }
444 <a
445 href=(listed_url(handle, name, listed.state, "", 1))
446 class="text-muted-foreground hover:text-foreground"
447 title=("Clear this filter")
448 >"×"</a>
449 </span>
450 }
451
452 <span class="ml-auto flex items-center gap-4">
453 <a
454 href=(labels_url(handle, name))
455 class="text-muted-foreground hover:text-foreground"
456 >"Labels"</a>
457 if listed.viewer_is_owner {
458 <a
459 href=(format!("{}/new", pulls_url(handle, name)))
460 class=(button_variants(ButtonVariant::Primary, ButtonSize::Sm))
461 >"New pull request"</a>
462 }
463 </span>
464 </div>
465 }
466}
467
468/// What a state is called on a tab and in a sentence.
469fn label_for(state: PullRequestState) -> &'static str {
470 match state {
471 PullRequestState::Open => "Open",
472 PullRequestState::Merged => "Merged",
473 PullRequestState::Closed => "Closed",
474 }
475}
476
477/// The state marker.
478///
479/// The one live fact about a pull request is whether it is still open, so that is what
480/// carries colour: open in `success`, **merged in the purple** that says it landed, and
481/// closed muted. Merged is the one place a third colour earns its place — "finished" and
482/// "abandoned" are opposite outcomes and a single muted grey for both would say a branch
483/// was rejected when it shipped.
484#[component]
485async fn state_icon(state: PullRequestState, #[default] muted: bool) -> Result {
486 let tone = match (muted, state) {
487 (true, _) | (_, PullRequestState::Closed) => "text-muted-foreground",
488 (_, PullRequestState::Open) => "text-success",
489 (_, PullRequestState::Merged) => "text-merged",
490 };
491
492 view! {
493 icon(
494 data: match state {
495 PullRequestState::Open => iconify_icon!("feather:git-pull-request"),
496 PullRequestState::Merged => iconify_icon!("feather:git-merge"),
497 PullRequestState::Closed => iconify_icon!("feather:x-circle"),
498 },
499 attrs: attributes! { class=(format!("size-3.5 shrink-0 {tone}")) }
500 )
501 }
502}
503
504#[component]
505async fn pull_list(handle: &str, name: &str, listed: &PullList, filter: &str) -> Result {
506 let items = &listed.pulls;
507 let noun = match filter.is_empty() {
508 true => format!("{} pull requests", label_for(listed.state).to_lowercase()),
509 false => format!(
510 "{} pull requests labelled {filter}",
511 label_for(listed.state).to_lowercase()
512 ),
513 };
514 let sentence = showing(items.offset(), items.items.len(), items.total, &noun);
515 let pages = Pages::numbered(items.page, items.pages, |page| {
516 listed_url(handle, name, listed.state, filter, page)
517 });
518
519 view! {
520 pulls_toolbar(handle: handle, name: name, listed: listed, filter: filter)
521
522 if items.items.is_empty() {
523 <div class="rounded-lg border border-border px-4 py-10 text-center">
524 <p class="text-sm text-muted-foreground">
525 "No " (label_for(listed.state).to_lowercase()) " pull requests"
526 if filter.is_empty() { "." } else { " labelled " (filter) "." }
527 </p>
528 // No button here: the toolbar carries one for the owner forty pixels
529 // above, and offering it twice reads as two different things.
530 if !listed.viewer_is_owner && listed.state.is_open() {
531 <p class="mt-1 text-xs text-muted-foreground">
532 "Only the owner can open one here."
533 </p>
534 }
535 </div>
536 } else {
537 <ul class="divide-y divide-border rounded-lg border border-border">
538 for pull in &items.items {
539 pull_row(handle: handle, name: name, pull: pull)
540 }
541 </ul>
542 list_pages(summary: sentence.as_str(), pages: &pages)
543 }
544 }
545}
546
547/// One request on one line: what it is, then who and when and between which branches.
548#[component]
549async fn pull_row(handle: &str, name: &str, pull: &PullSummary) -> Result {
550 let author = pull
551 .author
552 .as_ref()
553 .map(OrgName::as_str)
554 .unwrap_or("someone");
555
556 view! {
557 <li class="flex items-center gap-3 px-4 py-2.5 text-sm">
558 state_icon(state: pull.state)
559
560 <div class="min-w-0 flex-1">
561 <div class="flex flex-wrap items-center gap-x-2 gap-y-1">
562 <a
563 href=(pull_url(handle, name, pull.number))
564 class="truncate font-medium hover:text-primary"
565 >(pull.title.as_str())</a>
566 // After the title, before the meta line: a pill is part of what the
567 // request is, not part of when it happened.
568 for pill in &pull.labels {
569 label_pill(handle: handle, name: name, pill: pill, to: Filtering::Pulls)
570 }
571 </div>
572 <p class="mt-0.5 truncate text-xs text-muted-foreground">
573 <span class="font-mono">"#" (pull.number.get())</span>
574 " opened "
575 <span title=(timestamp(pull.created_at))>(ago(pull.created_at))</span>
576 " by "
577 <span class="font-mono">"@" (author)</span>
578 " · "
579 branch_pair(
580 source: pull.source_branch.as_str(),
581 target: pull.target_branch.as_str(),
582 )
583 </p>
584 </div>
585
586 if pull.comments > 0 {
587 <span
588 class="flex shrink-0 items-center gap-1 text-xs text-muted-foreground"
589 title=(format!("{} comments", pull.comments))
590 >
591 icon(
592 data: iconify_icon!("feather:message-square"),
593 attrs: attributes! { class="size-3.5" }
594 )
595 <span class="font-mono">(pull.comments)</span>
596 </span>
597 }
598 </li>
599 }
600}
601
602/// `source → target`, in mono, which is what distinguishes two requests with similar
603/// titles.
604#[component]
605async fn branch_pair(source: &str, target: &str) -> Result {
606 view! {
607 <span class="font-mono">(source)</span>
608 " → "
609 <span class="font-mono">(target)</span>
610 }
611}
612
613// --- Opening one ----------------------------------------------------------------------
614
615#[page("/{handle}/repos/{name}/pulls/new")]
616async fn new_pull_page(cx: &Cx) -> Result {
617 let repo = owned_repo(cx).await?;
618 let prefill = query_params::<PrefillQuery>(cx)?;
619 let refs = branch_names(cx, &repo).await?;
620
621 // Prefilled from the compare page, which is the way in this form is designed for.
622 // Typed directly it opens empty except for the target, which defaults to whatever
623 // the repository's default branch is — the answer nine times in ten.
624 let source = prefill.source.as_deref().unwrap_or_default().to_owned();
625 let target = match prefill.target.as_deref() {
626 Some(target) => target.to_owned(),
627 None => default_branch(cx, &repo).await?,
628 };
629
630 // Only worth asking when both fields actually name something. A form opened with no
631 // source has nothing to suggest a title from, and would pay three git questions to
632 // find that out.
633 let title = match (RefName::new(&source), RefName::new(&target)) {
634 (Ok(source), Ok(target)) => suggested_title(
635 &current_actor(cx).await?,
636 &repo.handle,
637 &repo.name,
638 &source,
639 &target,
640 &orgs(cx),
641 &memberships(cx),
642 &repos(cx),
643 &queries(cx),
644 )
645 .await
646 .map_err(server_error)?
647 .unwrap_or_default(),
648 _ => String::new(),
649 };
650
651 let draft = Draft {
652 source,
653 target,
654 title,
655 ..Draft::default()
656 };
657
658 view! {
659 wide(
660 repo_header(repo: &repo, rev: "", active: Tab::Pulls)
661 new_pull_form(
662 handle: repo.handle.as_str(),
663 name: repo.name.as_str(),
664 draft: &draft,
665 refs: &refs,
666 error: "",
667 )
668 )
669 }
670}
671
672/// Opens the request, then redirects to it.
673#[page(POST "/{handle}/repos/{name}/pulls")]
674async fn create(cx: &Cx, Form(submitted): Form<PullForm>) -> Result {
675 let repo = owned_repo(cx).await?;
676
677 // A branch name that is not a well-formed revision is a message on the form rather
678 // than a 400: it is something somebody typed, and the field it belongs to is known.
679 let parsed = (
680 RefName::new(&submitted.source),
681 RefName::new(&submitted.target),
682 );
683
684 let message = match parsed {
685 (Ok(source), Ok(target)) => {
686 let outcome = create_pull(
687 &current_actor(cx).await?,
688 &repo.handle,
689 &repo.name,
690 &NewPull {
691 title: submitted.title.clone(),
692 body: submitted.body.clone(),
693 source,
694 target,
695 },
696 SystemTime::now(),
697 &orgs(cx),
698 &memberships(cx),
699 &repos(cx),
700 &issues(cx),
701 &pulls(cx),
702 &queries(cx),
703 )
704 .await;
705
706 match outcome {
707 Ok(pull) => {
708 return view! {
709 (StatusCode::SEE_OTHER)
710 (location(&pull_url(
711 repo.handle.as_str(),
712 repo.name.as_str(),
713 pull.number,
714 ))?)
715 };
716 }
717 Err(error) => write_failure(error)?,
718 }
719 }
720 _ => "That is not a branch name.".to_owned(),
721 };
722
723 let refs = branch_names(cx, &repo).await?;
724 // Re-rendered with what was typed. Bouncing back to an empty form would throw away a
725 // description somebody spent ten minutes on to tell them a branch name was wrong.
726 let draft = Draft {
727 title: submitted.title,
728 body: submitted.body,
729 source: submitted.source,
730 target: submitted.target,
731 };
732
733 view! {
734 wide(
735 repo_header(repo: &repo, rev: "", active: Tab::Pulls)
736 new_pull_form(
737 handle: repo.handle.as_str(),
738 name: repo.name.as_str(),
739 draft: &draft,
740 refs: &refs,
741 error: message.as_str(),
742 )
743 )
744 }
745}
746
747/// What the new-request form currently holds.
748///
749/// One struct rather than four more parameters, and for a better reason than the
750/// argument count: these four are what a *rejected* submission has to put back, so they
751/// travel together everywhere and a caller cannot restore three of them.
752#[derive(Debug, Default)]
753pub(super) struct Draft {
754 pub title: String,
755 pub body: String,
756 pub source: String,
757 pub target: String,
758}
759
760#[component]
761async fn new_pull_form(
762 handle: &str,
763 name: &str,
764 draft: &Draft,
765 /// Branch names for the `<datalist>`, so the common case autocompletes.
766 refs: &[String],
767 error: &str,
768) -> Result {
769 view! {
770 <div class="max-w-3xl">
771 <h1 class="text-lg font-semibold tracking-tight">"New pull request"</h1>
772
773 if !error.is_empty() {
774 <div class="mt-4">
775 flash(kind: FlashKind::Error, (error))
776 </div>
777 }
778
779 <form method="post" action=(pulls_url(handle, name)) class="mt-5 space-y-4">
780 // The two branches first: which change this is about comes before what
781 // it is called, and a title typed against the wrong pair is wasted.
782 // Text inputs with a datalist rather than two selects, exactly as the
783 // compare form settled — the branch may have been pushed a second ago.
784 <div class="flex flex-wrap items-end gap-3">
785 <div class="flex min-w-44 flex-1 flex-col gap-1.5">
786 label(attrs: attributes! { for="source" class="text-xs" }, "Merge")
787 input(attrs: attributes! {
788 id="source" name="source" list="pull-branches" required=(true)
789 autocomplete="off" spellcheck="false" class="font-mono"
790 value=(draft.source.as_str()) placeholder="a branch"
791 })
792 </div>
793
794 <span class="pb-2.5 text-sm text-muted-foreground">"into"</span>
795
796 <div class="flex min-w-44 flex-1 flex-col gap-1.5">
797 label(attrs: attributes! { for="target" class="text-xs" }, "Base")
798 input(attrs: attributes! {
799 id="target" name="target" list="pull-branches" required=(true)
800 autocomplete="off" spellcheck="false" class="font-mono"
801 value=(draft.target.as_str()) placeholder="main"
802 })
803 </div>
804 </div>
805
806 <datalist id="pull-branches">
807 for branch in refs {
808 <option value=(branch.as_str())></option>
809 }
810 </datalist>
811
812 <div class="space-y-2">
813 label(attrs: attributes! { for="title" }, "Title")
814 input(attrs: attributes! {
815 id="title"
816 name="title"
817 type="text"
818 value=(draft.title.as_str())
819 placeholder="Speed blame up on large files"
820 required=(true)
821 })
822 </div>
823
824 <div class="space-y-2">
825 label(attrs: attributes! { for="body" }, "Description")
826 textarea(
827 attrs: attributes! {
828 id="body"
829 name="body"
830 rows="10"
831 placeholder="Markdown is supported."
832 },
833 (draft.body.as_str())
834 )
835 <p class="text-xs text-muted-foreground">
836 "Markdown. HTML in the source is shown as text, never rendered."
837 </p>
838 </div>
839
840 <div class="flex items-center gap-3">
841 button(attrs: attributes! { type="submit" }, "Open pull request")
842 <a
843 href=(pulls_url(handle, name))
844 class="text-sm text-muted-foreground hover:text-foreground"
845 >"Cancel"</a>
846 </div>
847 </form>
848 </div>
849 }
850}
851
852// --- One pull request -------------------------------------------------------------------
853
854#[page("/{handle}/repos/{name}/pulls/{number}")]
855async fn pull_page(cx: &Cx) -> Result {
856 let repo = repo_for(cx).await?;
857
858 let pull = match detail(cx, &repo, number_for(cx)?).await? {
859 Found::Here(pull) => pull,
860 Found::Elsewhere(url) => {
861 return view! { (StatusCode::SEE_OTHER) (location(&url)?) };
862 }
863 };
864
865 view! {
866 wide(
867 repo_header(repo: &repo, rev: "", active: Tab::Pulls)
868 pull_frame(repo: &repo, pull: &pull, active: Sub::Conversation,
869 conversation(
870 handle: repo.handle.as_str(),
871 name: repo.name.as_str(),
872 pull: &pull,
873 error: "",
874 comment: "",
875 editing: false,
876 )
877 )
878 )
879 }
880}
881
882/// The Commits sub-tab: the comparison's commit list, paged.
883#[page("/{handle}/repos/{name}/pulls/{number}/commits")]
884async fn pull_commits_page(cx: &Cx) -> Result {
885 let repo = repo_for(cx).await?;
886
887 let pull = match detail(cx, &repo, number_for(cx)?).await? {
888 Found::Here(pull) => pull,
889 Found::Elsewhere(url) => {
890 return view! { (StatusCode::SEE_OTHER) (location(&url)?) };
891 }
892 };
893
894 let page = requested_page(query_params::<PageQuery>(cx)?.page.as_deref());
895 let compared = compared_for(cx, &repo, &pull, page).await?;
896
897 let handle = repo.handle.as_str();
898 let name = repo.name.as_str();
899
900 // The whole range's commits are paged; the diff below is not shown on this tab at
901 // all, which is what makes the page cheap enough to number.
902 let listed = match &compared {
903 Some(Compared::Ready(comparison)) => Some(comparison.as_ref()),
904 _ => None,
905 };
906
907 // Built before the `view!`, not inside it: a `format!` or a `showing(..)` in an
908 // argument position is a temporary the borrow it produces outlives — the same trap
909 // the compare page's own `unknown` sentence sidesteps.
910 let sentence = listed
911 .map(|comparison| {
912 showing(
913 comparison.commits.offset(),
914 comparison.commits.items.len(),
915 comparison.commits.total,
916 "commits",
917 )
918 })
919 .unwrap_or_default();
920 let base = pull_url(handle, name, pull.number);
921 // `Pages::numbered` with a total of zero renders nothing at all, which is exactly
922 // what the states with no comparison want.
923 let pages = match listed {
924 Some(comparison) => {
925 Pages::numbered(comparison.commits.page, comparison.commits.pages, |page| {
926 format!("{base}/commits?page={page}")
927 })
928 }
929 None => Pages::numbered(1, 0, |_| String::new()),
930 };
931
932 view! {
933 wide(
934 repo_header(repo: &repo, rev: "", active: Tab::Pulls)
935 pull_frame(repo: &repo, pull: &pull, active: Sub::Commits,
936 match (compared.is_some(), listed) {
937 (false, _) => took_too_long(),
938 (true, Some(comparison)) => {
939 <div class="mb-2 text-xs text-muted-foreground">
940 "From merge base "
941 <a
942 href=(commit_url(handle, name, comparison.merge_base.as_str()))
943 class="font-mono hover:text-foreground"
944 >(comparison.merge_base.short())</a>
945 </div>
946 commit_log(
947 handle: handle,
948 name: name,
949 commits: &comparison.commits.items,
950 )
951 list_pages(summary: sentence.as_str(), pages: &pages)
952 }
953 (true, None) => nothing_to_compare(pull: &pull),
954 }
955 )
956 )
957 }
958}
959
960/// The Files changed sub-tab: the comparison's diff, rendered by the commit page's own
961/// renderer so a pull request's files and a comparison's files cannot drift apart.
962#[page("/{handle}/repos/{name}/pulls/{number}/files")]
963async fn pull_files_page(cx: &Cx) -> Result {
964 let repo = repo_for(cx).await?;
965
966 let pull = match detail(cx, &repo, number_for(cx)?).await? {
967 Found::Here(pull) => pull,
968 Found::Elsewhere(url) => {
969 return view! { (StatusCode::SEE_OTHER) (location(&url)?) };
970 }
971 };
972
973 let compared = compared_for(cx, &repo, &pull, 1).await?;
974
975 let handle = repo.handle.as_str();
976 let name = repo.name.as_str();
977
978 let listed = match &compared {
979 Some(Compared::Ready(comparison)) => Some(comparison.as_ref()),
980 _ => None,
981 };
982
983 view! {
984 wide(
985 repo_header(repo: &repo, rev: "", active: Tab::Pulls)
986 pull_frame(repo: &repo, pull: &pull, active: Sub::Files,
987 match (compared.is_some(), listed) {
988 (false, _) => took_too_long(),
989 (true, Some(comparison)) => diff_view(
990 handle: handle,
991 name: name,
992 rev: comparison.head_id.as_str(),
993 diff: &comparison.diff,
994 ),
995 (true, None) => nothing_to_compare(pull: &pull),
996 }
997 )
998 )
999 }
1000}
1001
1002/// What the Commits and Files tabs compare: the target against the source, three-dot,
1003/// which is exactly what a pull request proposes.
1004///
1005/// `Ok(None)` means git ran out of time, which the caller renders as a state rather than
1006/// a 500 — the rule the commit and compare pages already set.
1007async fn compared_for(
1008 cx: &Cx,
1009 repo: &RepoView,
1010 pull: &PullDetail,
1011 page: usize,
1012) -> Result<Option<Compared>> {
1013 unwrap_page(
1014 compare_revisions(
1015 &repo.handle,
1016 &repo.name,
1017 &pull.target_branch,
1018 &pull.source_branch,
1019 page,
1020 &current_actor(cx).await?,
1021 &orgs(cx),
1022 &memberships(cx),
1023 &repos(cx),
1024 &queries(cx),
1025 )
1026 .await,
1027 )
1028}
1029
1030/// What the two comparison tabs say when there is nothing to show.
1031///
1032/// One panel for four causes — a branch that is gone, two revisions that are the same
1033/// commit, histories that share nothing, a source already contained in the target —
1034/// because the reader's next move is the same in all four and the Conversation tab's
1035/// merge box already says which it is in words.
1036#[component]
1037async fn nothing_to_compare(pull: &PullDetail) -> Result {
1038 view! {
1039 <p class="rounded-lg border border-border px-4 py-10 text-center text-sm text-muted-foreground">
1040 "There is nothing to show here. "
1041 <span class="font-mono">(pull.source_branch.as_str())</span>
1042 " adds no commits to "
1043 <span class="font-mono">(pull.target_branch.as_str())</span>
1044 ", or one of the two branches is no longer in this repository."
1045 </p>
1046 }
1047}
1048
1049/// The header and sub-tab strip every one of the three tabs carries.
1050///
1051/// A hairline strip like the settings section list rather than a second bordered tab
1052/// row: the repository's own tab strip is directly above it, and two identical strips
1053/// stacked would make the page look like it had lost its place.
1054#[component]
1055async fn pull_frame(
1056 repo: &RepoView,
1057 pull: &PullDetail,
1058 active: Sub,
1059 child: topcoat::view::View,
1060) -> Result {
1061 let handle = repo.handle.as_str();
1062 let name = repo.name.as_str();
1063 let url = pull_url(handle, name, pull.number);
1064 let author = pull
1065 .author
1066 .as_ref()
1067 .map(OrgName::as_str)
1068 .unwrap_or("someone");
1069
1070 let tab = |current| {
1071 if current {
1072 "border-primary text-foreground"
1073 } else {
1074 "border-transparent text-muted-foreground hover:text-foreground"
1075 }
1076 };
1077
1078 view! {
1079 <h1 class="text-xl font-semibold tracking-tight">
1080 (pull.title.as_str())
1081 <span class="ml-2 font-mono text-lg font-normal text-muted-foreground">
1082 "#" (pull.number.get())
1083 </span>
1084 </h1>
1085
1086 <div class="mt-2 flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-muted-foreground">
1087 state_badge(state: pull.state)
1088 <span>
1089 <span class="font-mono">"@" (author)</span>
1090 " wants to merge "
1091 branch_pair(
1092 source: pull.source_branch.as_str(),
1093 target: pull.target_branch.as_str(),
1094 )
1095 </span>
1096 <span title=(timestamp(pull.created_at))>"opened " (ago(pull.created_at))</span>
1097 </div>
1098
1099 // On the frame rather than on the Conversation tab: what a request is labelled
1100 // is as true on Files changed as it is here.
1101 if !pull.labels.is_empty() {
1102 <div class="mt-2 flex flex-wrap items-center gap-1.5">
1103 for pill in &pull.labels {
1104 label_pill(handle: handle, name: name, pill: pill, to: Filtering::Pulls)
1105 }
1106 </div>
1107 }
1108
1109 <nav class="mt-3 mb-4 flex items-center gap-5 border-b border-border text-sm">
1110 for (sub, name, href) in [
1111 (Sub::Conversation, "Conversation", url.clone()),
1112 (Sub::Commits, "Commits", format!("{url}/commits")),
1113 (Sub::Files, "Files changed", format!("{url}/files")),
1114 ] {
1115 <a
1116 href=(href.as_str())
1117 class=(format!("-mb-px border-b-2 pb-2 {}", tab(active == sub)))
1118 >(name)</a>
1119 }
1120 </nav>
1121
1122 (child)
1123 }
1124}
1125
1126/// The state badge: the same three-way distinction the row icon makes, in words.
1127#[component]
1128async fn state_badge(state: PullRequestState) -> Result {
1129 view! {
1130 match state {
1131 PullRequestState::Merged => badge(variant: BadgeVariant::Merged, "Merged"),
1132 PullRequestState::Open => badge(variant: BadgeVariant::Primary, "Open"),
1133 PullRequestState::Closed => badge(variant: BadgeVariant::Secondary, "Closed"),
1134 }
1135 }
1136}
1137
1138// --- The conversation tab -----------------------------------------------------------------
1139
1140#[component]
1141async fn conversation(
1142 handle: &str,
1143 name: &str,
1144 pull: &PullDetail,
1145 error: &str,
1146 /// A comment that was rejected, put back in the box.
1147 comment: &str,
1148 /// Whether the edit panel starts open — true only when an edit was refused.
1149 editing: bool,
1150) -> Result {
1151 let author = pull
1152 .author
1153 .as_ref()
1154 .map(OrgName::as_str)
1155 .unwrap_or("someone");
1156 let url = pull_url(handle, name, pull.number);
1157
1158 view! {
1159 <div class="max-w-3xl">
1160 if !error.is_empty() {
1161 <div class="mb-4">
1162 flash(kind: FlashKind::Error, (error))
1163 </div>
1164 }
1165
1166 <div class="space-y-3">
1167 <article class="rounded-lg border border-border">
1168 <header class="flex items-center gap-2 border-b border-border px-4 py-2 text-xs text-muted-foreground">
1169 <span class="font-mono">"@" (author)</span>
1170 <span title=(timestamp(pull.created_at))>(ago(pull.created_at))</span>
1171 </header>
1172 body_panel(
1173 handle: handle,
1174 name: name,
1175 source: pull.body.as_str(),
1176 empty: "No description given.",
1177 )
1178 </article>
1179
1180 for comment in &pull.comments {
1181 pull_comment(handle: handle, name: name, comment: comment)
1182 }
1183 </div>
1184
1185 // What happened, once it has. Replaces the merge box entirely rather than
1186 // sitting beside it: a merged request has one fact left to state.
1187 if let Some(landed) = pull.merge_commit.as_ref() {
1188 <div class="mt-5 rounded-lg border border-border px-4 py-3 text-sm">
1189 <span class="flex flex-wrap items-center gap-x-2 gap-y-1">
1190 icon(
1191 data: iconify_icon!("feather:git-merge"),
1192 attrs: attributes! { class="size-4 shrink-0 text-merged" }
1193 )
1194 "Merged "
1195 <a
1196 href=(commit_url(handle, name, landed.as_str()))
1197 class="font-mono hover:text-primary"
1198 >(landed.short())</a>
1199 " into "
1200 <span class="font-mono">(pull.target_branch.as_str())</span>
1201 if let Some(at) = pull.merged_at {
1202 <span class="text-muted-foreground" title=(timestamp(at))>(ago(at))</span>
1203 }
1204 </span>
1205 </div>
1206 } else if pull.viewer_is_owner {
1207 merge_box(handle: handle, name: name, pull: pull)
1208 }
1209
1210 if pull.viewer_is_owner {
1211 // Two forms, one row, as the issue page settled: a form cannot nest, and
1212 // the Comment button reaches its own by `form=` id rather than by
1213 // containment — which is what keeps the textarea out of the row.
1214 <form
1215 id="pull-comment-form"
1216 method="post"
1217 action=(format!("{url}/comments"))
1218 class="mt-5 space-y-2"
1219 >
1220 label(attrs: attributes! { for="pull-comment-body" }, "Comment")
1221 textarea(
1222 attrs: attributes! {
1223 id="pull-comment-body"
1224 name="body"
1225 rows="5"
1226 placeholder="Markdown is supported."
1227 },
1228 (comment)
1229 )
1230 </form>
1231
1232 <div class="mt-3 flex flex-wrap items-center gap-2">
1233 button(
1234 size: ButtonSize::Sm,
1235 attrs: attributes! { type="submit" form="pull-comment-form" },
1236 "Comment"
1237 )
1238
1239 // Absent once merged: there is no state left to move it to, and a
1240 // "Close" button on a landed request would offer to undo history.
1241 if !pull.state.is_merged() {
1242 <form method="post" action=(format!("{url}/state"))>
1243 <input
1244 type="hidden"
1245 name="state"
1246 value=(if pull.state.is_open() { "closed" } else { "open" })
1247 />
1248 button(
1249 variant: ButtonVariant::Outline,
1250 size: ButtonSize::Sm,
1251 attrs: attributes! { type="submit" },
1252 if pull.state.is_open() {
1253 "Close pull request"
1254 } else {
1255 "Reopen pull request"
1256 }
1257 )
1258 </form>
1259 }
1260 </div>
1261
1262 // The issue page's control, in the same words and posting the same
1263 // shape — the route is `labels.rs`'s, beside the issue one.
1264 <details class="mt-3">
1265 <summary class="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
1266 "Labels"
1267 </summary>
1268
1269 if pull.repo_labels.is_empty() {
1270 <p class="mt-2 text-xs text-muted-foreground">
1271 "This repository has no labels yet. "
1272 <a href=(labels_url(handle, name)) class="underline hover:text-foreground">
1273 "Make one"
1274 </a>
1275 "."
1276 </p>
1277 } else {
1278 // Every box, ticked or not, submitted as the whole set — which is
1279 // what makes pressing Save twice mean the same as once.
1280 <form method="post" action=(format!("{url}/labels")) class="mt-2 space-y-2">
1281 <div class="flex flex-wrap gap-x-4 gap-y-2">
1282 for choice in &pull.repo_labels {
1283 <label class="flex items-center gap-2 text-xs">
1284 <input
1285 type="checkbox"
1286 name="label"
1287 value=(choice.id.as_str())
1288 checked=(pull.labels.iter().any(|on| on.id == choice.id))
1289 />
1290 <span class=(format!("label-pill label-{}", choice.colour))>
1291 (choice.name.as_str())
1292 </span>
1293 </label>
1294 }
1295 </div>
1296 <div class="flex items-center gap-3 pt-1">
1297 button(
1298 size: ButtonSize::Sm,
1299 variant: ButtonVariant::Outline,
1300 attrs: attributes! { type="submit" },
1301 "Save labels"
1302 )
1303 <a
1304 href=(labels_url(handle, name))
1305 class="text-xs text-muted-foreground hover:text-foreground"
1306 >"Manage labels"</a>
1307 </div>
1308 </form>
1309 }
1310 </details>
1311
1312 <details class="mt-3" open=(editing)>
1313 <summary class="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
1314 "Edit title and description"
1315 </summary>
1316
1317 <form method="post" action=(format!("{url}/edit")) class="mt-3 space-y-4">
1318 <div class="space-y-2">
1319 label(attrs: attributes! { for="edit-title" }, "Title")
1320 input(attrs: attributes! {
1321 id="edit-title"
1322 name="title"
1323 type="text"
1324 value=(pull.title.as_str())
1325 required=(true)
1326 })
1327 </div>
1328 <div class="space-y-2">
1329 label(attrs: attributes! { for="edit-body" }, "Description")
1330 textarea(
1331 attrs: attributes! { id="edit-body" name="body" rows="10" },
1332 (pull.body.as_str())
1333 )
1334 </div>
1335 // The branches are not here: changing either would make every
1336 // comment above an opinion about a different change.
1337 button(
1338 size: ButtonSize::Sm,
1339 attrs: attributes! { type="submit" },
1340 "Save changes"
1341 )
1342 </form>
1343 </details>
1344 } else {
1345 <p class="mt-5 rounded-lg border border-border px-4 py-3 text-xs text-muted-foreground">
1346 "Only the owner can comment on, change or merge this pull request."
1347 </p>
1348 }
1349
1350 <p class="mt-8">
1351 <a
1352 href=(pulls_url(handle, name))
1353 class="text-sm text-muted-foreground hover:text-foreground"
1354 >"Back to pull requests"</a>
1355 </p>
1356 </div>
1357 }
1358}
1359
1360/// The merge box: one line of status, then — only when there is something to press — a
1361/// strategy, a checkbox and one primary button.
1362///
1363/// The button is the one primary-coloured control on the page, which is the ui.md rule
1364/// doing its job: it is the single live thing here, and everything else is either
1365/// position or history.
1366#[component]
1367async fn merge_box(handle: &str, name: &str, pull: &PullDetail) -> Result {
1368 let url = pull_url(handle, name, pull.number);
1369 let strategies = pull.merge.strategies();
1370 // Deleting the source is the tidy default, and it is safe: the branch is in the
1371 // merge commit's history. Merging a branch into itself is not a proposal, so the
1372 // control is not drawn at all there.
1373 let deletable = pull.source_branch != pull.target_branch;
1374 // …but the default branch is the one people clone and push to, so proposing to
1375 // delete it is a different kind of thing. The box is still there — somebody may
1376 // genuinely mean it — and it opens unticked.
1377 let delete_by_default = !pull.source_is_default;
1378
1379 view! {
1380 <div class="mt-5 rounded-lg border border-border px-4 py-3">
1381 <p class="flex flex-wrap items-center gap-2 text-sm">
1382 merge_status_icon(merge: &pull.merge, state: pull.state)
1383 (merge_sentence(&pull.merge, pull.state))
1384 </p>
1385
1386 if let Mergeability::Conflicted { paths } = &pull.merge {
1387 // Named, because which files disagree is the whole of what the reader
1388 // can act on — and a conflict list is a `git` command they run locally.
1389 <ul class="mt-2 flex flex-wrap gap-x-3 gap-y-1 font-mono text-xs text-muted-foreground">
1390 for path in paths.iter().take(10) {
1391 <li class="truncate">(path.as_str())</li>
1392 }
1393 if paths.len() > 10 {
1394 <li>"…and " (paths.len() - 10) " more"</li>
1395 }
1396 </ul>
1397 <p class="mt-2 text-xs text-muted-foreground">
1398 "Merge "
1399 <span class="font-mono text-foreground">(pull.target_branch.as_str())</span>
1400 " into "
1401 <span class="font-mono text-foreground">(pull.source_branch.as_str())</span>
1402 " locally, resolve the conflicts and push."
1403 </p>
1404 }
1405
1406 if !strategies.is_empty() {
1407 <form method="post" action=(format!("{url}/merge")) class="mt-3 flex flex-wrap items-end gap-3">
1408 <div class="flex min-w-56 flex-col gap-1.5">
1409 label(attrs: attributes! { for="strategy" class="text-xs" }, "How")
1410 // A native select rather than the styled component: this sits
1411 // inside a bordered box beside a button, and the component's own
1412 // chevron wrapper wants a column of its own.
1413 <select
1414 id="strategy"
1415 name="strategy"
1416 class="h-9 rounded-lg border border-border bg-background px-3 text-sm"
1417 >
1418 for strategy in &strategies {
1419 <option value=(strategy.as_str())>(strategy.label())</option>
1420 }
1421 </select>
1422 </div>
1423
1424 if deletable {
1425 <label class="flex items-center gap-2 pb-2.5 text-xs text-muted-foreground">
1426 // On by default: the branch's commits are in the target's
1427 // history once this lands, so the branch itself is the copy
1428 // nobody needs. Off when that branch is the default one.
1429 <input
1430 type="checkbox"
1431 name="delete_source"
1432 value="yes"
1433 checked=(delete_by_default)
1434 />
1435 "Delete "
1436 <span class="font-mono">(pull.source_branch.as_str())</span>
1437 " afterwards"
1438 </label>
1439 }
1440
1441 <button
1442 type="submit"
1443 class=(format!(
1444 "ml-auto {}",
1445 button_variants(ButtonVariant::Primary, ButtonSize::Md)
1446 ))
1447 >"Merge pull request"</button>
1448 </form>
1449 }
1450 </div>
1451 }
1452}
1453
1454/// The dot beside the merge status: the only colour in the box that is not the button.
1455#[component]
1456async fn merge_status_icon(merge: &Mergeability, state: PullRequestState) -> Result {
1457 let (data, tone) = match (state.is_open(), merge) {
1458 (false, _) => (iconify_icon!("feather:x-circle"), "text-muted-foreground"),
1459 (_, Mergeability::Ready { .. }) => (iconify_icon!("feather:check-circle"), "text-success"),
1460 (_, Mergeability::Conflicted { .. }) => {
1461 (iconify_icon!("feather:alert-triangle"), "text-destructive")
1462 }
1463 _ => (iconify_icon!("feather:info"), "text-muted-foreground"),
1464 };
1465
1466 view! {
1467 icon(data: data, attrs: attributes! { class=(format!("size-4 shrink-0 {tone}")) })
1468 }
1469}
1470
1471/// The one line the merge box leads with.
1472///
1473/// Plain sentences rather than a status word: "Conflicts in 3 files" is a thing to act
1474/// on, "Conflicted" is a label to decode.
1475fn merge_sentence(merge: &Mergeability, state: PullRequestState) -> String {
1476 if !state.is_open() {
1477 return "This pull request is closed. Reopen it to merge.".to_owned();
1478 }
1479
1480 match merge {
1481 Mergeability::Ready { fast_forward: true } => {
1482 "Can be merged, and the base can simply catch up.".to_owned()
1483 }
1484 Mergeability::Ready { .. } => "Can be merged.".to_owned(),
1485 Mergeability::Conflicted { paths } => match paths.len() {
1486 1 => "Conflicts in 1 file:".to_owned(),
1487 other => format!("Conflicts in {other} files:"),
1488 },
1489 Mergeability::NothingToMerge => {
1490 "Nothing to merge — every commit is already on the base branch.".to_owned()
1491 }
1492 Mergeability::Unrelated => {
1493 "These two branches share no history, so there is nothing to merge.".to_owned()
1494 }
1495 Mergeability::MissingBranch { branch } => {
1496 format!("There is no branch called {branch} in this repository any more.")
1497 }
1498 Mergeability::Unsupported => "Merging needs git 2.38 or newer on the server.".to_owned(),
1499 Mergeability::NotOpen => "This pull request is not open.".to_owned(),
1500 }
1501}
1502
1503#[component]
1504async fn pull_comment(handle: &str, name: &str, comment: &CommentView) -> Result {
1505 let author = comment
1506 .author
1507 .as_ref()
1508 .map(OrgName::as_str)
1509 .unwrap_or("someone");
1510
1511 view! {
1512 <article class="rounded-lg border border-border">
1513 <header class="flex items-center gap-2 border-b border-border px-4 py-2 text-xs text-muted-foreground">
1514 <span class="font-mono">"@" (author)</span>
1515 <span title=(timestamp(comment.created_at))>(ago(comment.created_at))</span>
1516 </header>
1517 body_panel(handle: handle, name: name, source: comment.body.as_str(), empty: "")
1518 </article>
1519 }
1520}
1521
1522/// A markdown body inside a panel.
1523///
1524/// Split out so the one `view!` holding rendered markdown is a single line, and safe
1525/// because [`markdown`](super::markdown) writes every tag itself.
1526#[component]
1527async fn body_panel(handle: &str, name: &str, source: &str, empty: &str) -> Result {
1528 view! {
1529 if source.is_empty() {
1530 <p class="px-4 py-3 text-sm text-muted-foreground italic">(empty)</p>
1531 } else {
1532 <div class="overflow-x-auto px-4 py-2 text-sm [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
1533 (markdown::render(
1534 source,
1535 Some(markdown::Crossref {
1536 handle,
1537 name,
1538 origin: None,
1539 }),
1540 ))
1541 </div>
1542 }
1543 }
1544}
1545
1546// --- Writes -----------------------------------------------------------------------------
1547
1548/// Adds a comment, then redirects so a reload cannot repeat it.
1549#[page(POST "/{handle}/repos/{name}/pulls/{number}/comments")]
1550async fn add_comment(cx: &Cx, Form(submitted): Form<CommentForm>) -> Result {
1551 let repo = owned_repo(cx).await?;
1552 let number = number_for(cx)?;
1553
1554 let outcome = comment_on_pull(
1555 &current_actor(cx).await?,
1556 &repo.handle,
1557 &repo.name,
1558 number,
1559 &submitted.body,
1560 SystemTime::now(),
1561 &orgs(cx),
1562 &memberships(cx),
1563 &repos(cx),
1564 &pulls(cx),
1565 )
1566 .await;
1567
1568 let message = match outcome {
1569 Ok(()) => return view! { see_pull(repo: &repo, number: number) },
1570 Err(error) => write_failure(error)?,
1571 };
1572
1573 let pull = reread(cx, &repo, number).await?;
1574
1575 view! {
1576 wide(
1577 repo_header(repo: &repo, rev: "", active: Tab::Pulls)
1578 pull_frame(repo: &repo, pull: &pull, active: Sub::Conversation,
1579 conversation(
1580 handle: repo.handle.as_str(),
1581 name: repo.name.as_str(),
1582 pull: &pull,
1583 error: message.as_str(),
1584 // Kept, so a rejected comment is not silently thrown away.
1585 comment: submitted.body.as_str(),
1586 editing: false,
1587 )
1588 )
1589 )
1590 }
1591}
1592
1593/// Closes or reopens, then redirects.
1594#[page(POST "/{handle}/repos/{name}/pulls/{number}/state")]
1595async fn set_state(cx: &Cx, Form(submitted): Form<StateForm>) -> Result {
1596 let repo = owned_repo(cx).await?;
1597 let number = number_for(cx)?;
1598
1599 // A value neither state can name is a tampered form, not something to default:
1600 // defaulting would close a request somebody asked to reopen. `merged` parses but the
1601 // use case refuses it — landing a branch is the merge form's job.
1602 let state = submitted
1603 .state
1604 .parse::<PullRequestState>()
1605 .map_err(|_| bad_request("unknown pull request state"))?;
1606
1607 match set_pull_state(
1608 &current_actor(cx).await?,
1609 &repo.handle,
1610 &repo.name,
1611 number,
1612 state,
1613 SystemTime::now(),
1614 &orgs(cx),
1615 &memberships(cx),
1616 &repos(cx),
1617 &pulls(cx),
1618 )
1619 .await
1620 {
1621 Ok(()) => {}
1622 // Nothing typed to preserve, so a failure here is a response rather than a
1623 // re-render.
1624 Err(error) => {
1625 write_failure(error)?;
1626 }
1627 }
1628
1629 view! { see_pull(repo: &repo, number: number) }
1630}
1631
1632/// Changes the title and body, then redirects.
1633#[page(POST "/{handle}/repos/{name}/pulls/{number}/edit")]
1634async fn edit(cx: &Cx, Form(submitted): Form<EditForm>) -> Result {
1635 let repo = owned_repo(cx).await?;
1636 let number = number_for(cx)?;
1637
1638 let outcome = edit_pull(
1639 &current_actor(cx).await?,
1640 &repo.handle,
1641 &repo.name,
1642 number,
1643 &PullEdit {
1644 title: submitted.title.clone(),
1645 body: submitted.body.clone(),
1646 },
1647 SystemTime::now(),
1648 &orgs(cx),
1649 &memberships(cx),
1650 &repos(cx),
1651 &pulls(cx),
1652 )
1653 .await;
1654
1655 let message = match outcome {
1656 Ok(()) => return view! { see_pull(repo: &repo, number: number) },
1657 Err(error) => write_failure(error)?,
1658 };
1659
1660 // The stored request, with the rejected edit put back into the form and the panel
1661 // opened on it — otherwise the reason is visible and what caused it is hidden behind
1662 // a closed disclosure.
1663 let stored = reread(cx, &repo, number).await?;
1664 let attempted = PullDetail {
1665 title: submitted.title.clone(),
1666 body: submitted.body.clone(),
1667 ..*stored
1668 };
1669
1670 view! {
1671 wide(
1672 repo_header(repo: &repo, rev: "", active: Tab::Pulls)
1673 pull_frame(repo: &repo, pull: &attempted, active: Sub::Conversation,
1674 conversation(
1675 handle: repo.handle.as_str(),
1676 name: repo.name.as_str(),
1677 pull: &attempted,
1678 error: message.as_str(),
1679 comment: "",
1680 editing: true,
1681 )
1682 )
1683 )
1684 }
1685}
1686
1687/// Merges, then redirects to the request.
1688///
1689/// The webhooks are delivered in a spawned task, exactly as a push's are: a delivery
1690/// runs for up to two and a half minutes with its retries, and nothing about whether the
1691/// merge succeeded depends on whether a receiver answered.
1692#[page(POST "/{handle}/repos/{name}/pulls/{number}/merge")]
1693async fn submit_merge(cx: &Cx, Form(submitted): Form<MergeForm>) -> Result {
1694 let repo = owned_repo(cx).await?;
1695 let number = number_for(cx)?;
1696
1697 // A strategy the domain cannot name is a tampered form. Defaulting would land a
1698 // squash where somebody asked for a merge commit, and history cannot be un-landed.
1699 let strategy = submitted
1700 .strategy
1701 .parse::<MergeStrategy>()
1702 .map_err(|_| bad_request("unknown merge strategy"))?;
1703
1704 // The identity the top bar already read this request. `None` would mean the session
1705 // outlived its user, which the use case refuses a moment later anyway — the fallback
1706 // exists so a merge commit always has a name on it rather than one git invented from
1707 // the host.
1708 let author = match identity(cx).await? {
1709 Some(who) => MergeAuthor {
1710 name: who.handle.to_string(),
1711 email: who.email.to_string(),
1712 },
1713 None => return Err(forbidden().into()),
1714 };
1715
1716 let outcome = merge_pull(
1717 &current_actor(cx).await?,
1718 &repo.handle,
1719 &repo.name,
1720 number,
1721 strategy,
1722 submitted.delete_source.is_some(),
1723 git_features(cx).merge_tree,
1724 SystemTime::now(),
1725 &orgs(cx),
1726 &memberships(cx),
1727 &repos(cx),
1728 &pulls(cx),
1729 &push_events(cx),
1730 &issues(cx),
1731 &queries(cx),
1732 &merges(cx),
1733 &author,
1734 )
1735 .await;
1736
1737 let message = match outcome {
1738 Ok(merged) => {
1739 deliver(cx, &repo, merged.events);
1740 return view! { see_pull(repo: &repo, number: number) };
1741 }
1742 Err(error) => write_failure(error)?,
1743 };
1744
1745 // Re-rendered rather than redirected: the reason a merge was refused — a conflict
1746 // that arrived a minute ago, a branch that moved — is the whole of what the page has
1747 // to say, and a redirect would drop it.
1748 let pull = reread(cx, &repo, number).await?;
1749
1750 view! {
1751 wide(
1752 repo_header(repo: &repo, rev: "", active: Tab::Pulls)
1753 pull_frame(repo: &repo, pull: &pull, active: Sub::Conversation,
1754 conversation(
1755 handle: repo.handle.as_str(),
1756 name: repo.name.as_str(),
1757 pull: &pull,
1758 error: message.as_str(),
1759 comment: "",
1760 editing: false,
1761 )
1762 )
1763 )
1764 }
1765}
1766
1767/// Sends the merge's push events to the repository's webhooks, in a task of its own.
1768///
1769/// Detached for the reason the git transport detaches its own: the retries alone run for
1770/// two and a half minutes, and a person waiting on a redirect must not wait on somebody
1771/// else's server. A failure is logged and nothing else — the merge has landed either way.
1772fn deliver(cx: &Cx, repo: &RepoView, events: Vec<crate::domain::PushEvent>) {
1773 use crate::{
1774 application::{DeliveryContext, RETRY_BACKOFF, deliver_push},
1775 infrastructure::clock::SystemClock,
1776 };
1777
1778 if events.is_empty() {
1779 return;
1780 }
1781
1782 let context = DeliveryContext {
1783 handle: repo.handle.clone(),
1784 name: repo.name.clone(),
1785 repo_url: format!("{}/{}/repos/{}", public_origin(cx), repo.handle, repo.name),
1786 pusher: Some(repo.handle.to_string()),
1787 };
1788
1789 // Cloned out of `cx` before the task starts: the request context does not outlive the
1790 // response, and every one of these is a cheap handle onto the pool or the config.
1791 let (queries, webhooks, deliveries, sender) = (
1792 queries(cx),
1793 webhooks(cx),
1794 super::context::deliveries(cx),
1795 webhook_sender(cx),
1796 );
1797
1798 tokio::spawn(async move {
1799 if let Err(error) = deliver_push(
1800 &events,
1801 &context,
1802 &queries,
1803 &webhooks,
1804 &deliveries,
1805 &sender,
1806 &SystemClock,
1807 &RETRY_BACKOFF,
1808 )
1809 .await
1810 {
1811 eprintln!(
1812 "steid: the webhooks for {}/{} could not be reached after a merge: {error}",
1813 context.handle, context.name
1814 );
1815 }
1816 });
1817}
1818
1819/// The post-redirect-get reply every write here ends with.
1820///
1821/// A `#[component]` rather than a plain function because `view!` needs `__cx` in scope,
1822/// which only a page or a component has — the same reason the browse helpers are
1823/// components. The status is a **303**: `redirect()` is a 307 and would make the browser
1824/// re-POST the form to the pull request's own URL.
1825#[component]
1826async fn see_pull(repo: &RepoView, number: IssueNumber) -> Result {
1827 view! {
1828 (StatusCode::SEE_OTHER)
1829 (location(&pull_url(repo.handle.as_str(), repo.name.as_str(), number))?)
1830 }
1831}
1832
1833// --- Shared reads -------------------------------------------------------------------------
1834
1835/// The repository's branch names, for the form's `<datalist>`. One `git` process.
1836async fn branch_names(cx: &Cx, repo: &RepoView) -> Result<Vec<String>> {
1837 let refs: RefList = list_refs(
1838 &repo.handle,
1839 &repo.name,
1840 &current_actor(cx).await?,
1841 &orgs(cx),
1842 &memberships(cx),
1843 &repos(cx),
1844 &queries(cx),
1845 )
1846 .await
1847 .map_err(server_error)?
1848 .unwrap_or_default();
1849
1850 Ok(refs
1851 .branches
1852 .iter()
1853 .map(|branch| branch.as_str().to_owned())
1854 .collect())
1855}
1856
1857/// What the form's base field opens with. One `git` process; empty for a repository with
1858/// no commits, where there is nothing to prefill with.
1859async fn default_branch(cx: &Cx, repo: &RepoView) -> Result<String> {
1860 use crate::application::port::GitQuery;
1861
1862 Ok(queries(cx)
1863 .default_branch(&repo.handle, &repo.name)
1864 .await
1865 .map_err(server_error)?
1866 .map(|branch| branch.as_str().to_owned())
1867 .unwrap_or_default())
1868}
1869
1870#[cfg(test)]
1871mod tests {
1872 use super::*;
1873
1874 #[test]
1875 fn the_first_page_of_the_open_list_is_the_bare_url() {
1876 assert_eq!(
1877 listed_url("ada", "steid", PullRequestState::Open, "", 1),
1878 "/ada/repos/steid/pulls"
1879 );
1880 }
1881
1882 #[test]
1883 fn a_page_link_carries_the_state_with_it() {
1884 // Paging out of a state filter would silently show a different list.
1885 assert_eq!(
1886 listed_url("ada", "steid", PullRequestState::Merged, "", 3),
1887 "/ada/repos/steid/pulls?state=merged&page=3"
1888 );
1889 }
1890
1891 #[test]
1892 fn a_state_link_drops_the_page() {
1893 // Page 4 of the open requests is not page 4 of the merged ones.
1894 assert_eq!(
1895 listed_url("ada", "steid", PullRequestState::Closed, "", 1),
1896 "/ada/repos/steid/pulls?state=closed"
1897 );
1898 }
1899
1900 #[test]
1901 fn a_page_link_carries_the_state_and_the_label_with_it() {
1902 // Paging out of a label filter would silently widen the list.
1903 assert_eq!(
1904 listed_url("ada", "steid", PullRequestState::Merged, "needs review", 3),
1905 "/ada/repos/steid/pulls?state=merged&label=needs%20review&page=3"
1906 );
1907 }
1908
1909 #[test]
1910 fn a_state_link_keeps_the_label() {
1911 assert_eq!(
1912 listed_url("ada", "steid", PullRequestState::Closed, "bug", 1),
1913 "/ada/repos/steid/pulls?state=closed&label=bug"
1914 );
1915 }
1916
1917 #[test]
1918 fn a_prefilled_form_encodes_each_branch_on_its_own() {
1919 // A slash inside a branch name must survive as part of the value.
1920 assert_eq!(
1921 new_pull_url("ada", "steid", "feature/login", "main"),
1922 "/ada/repos/steid/pulls/new?source=feature%2Flogin&target=main"
1923 );
1924 }
1925
1926 #[test]
1927 fn the_merge_sentence_names_what_can_be_acted_on() {
1928 let sentence = |merge| merge_sentence(&merge, PullRequestState::Open);
1929
1930 assert_eq!(
1931 sentence(Mergeability::Conflicted {
1932 paths: vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
1933 }),
1934 "Conflicts in 3 files:"
1935 );
1936 assert_eq!(
1937 sentence(Mergeability::Conflicted {
1938 paths: vec!["a".to_owned()],
1939 }),
1940 "Conflicts in 1 file:"
1941 );
1942 assert_eq!(
1943 sentence(Mergeability::Unsupported),
1944 "Merging needs git 2.38 or newer on the server."
1945 );
1946 // A closed request says so whatever git thinks of its branches.
1947 assert_eq!(
1948 merge_sentence(
1949 &Mergeability::Ready {
1950 fast_forward: false
1951 },
1952 PullRequestState::Closed
1953 ),
1954 "This pull request is closed. Reopen it to merge."
1955 );
1956 }
1957}