forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiBb00f3f4Tahinli1 month ago147 commits

pull_flow.rs165 lines, 6.0 KiBHistoryRawDownload
1//! Pull request flow controls: draft state and auto-merge.
2//!
3//! - `POST /{owner}/{repo}/pulls/{number}/ready` marks a draft ready for review.
4//! - `POST /{owner}/{repo}/pulls/{number}/draft` converts an open pull request back to a draft.
5//! - `POST /{owner}/{repo}/pulls/{number}/auto-merge` enables auto-merge with a style.
6//! - `POST /{owner}/{repo}/pulls/{number}/auto-merge/disable` switches it off.
7//!
8//! Draft changes are for the pull request author and for Write holders. Auto-merge needs Write,
9//! a signed-in viewer with a valid CSRF token, and a pull request that is blocked only by checks
10//! or approvals that can still arrive. All of them answer with a redirect back to the pull
11//! request (the soft-nav script follows it without a reload).
12
13use forge_core::{Action, IssueState, MergeStyle, PullRequest, authorize};
14use serde::Deserialize;
15use topcoat::Result;
16use topcoat::context::{Cx, app_context};
17use topcoat::router::content::Form;
18use topcoat::router::error::{bad_request, forbidden, not_found, see_other};
19use topcoat::router::response::Response;
20use topcoat::router::{path_param, route};
21
22use crate::auth::require_csrf;
23use crate::notify::{self, Activity};
24use crate::pages::issue_parts::parse_number;
25use crate::pages::pulls_merge::{ERR_AUTO_MERGE_BLOCKED, merge_gate};
26use crate::pages::repo_ctx::{RepoCtx, load_repo};
27use crate::state::AppState;
28use crate::views::repo_href;
29use crate::webhooks::emit::{Sender, emit_item_action};
30
31path_param!(owner);
32path_param!(repo);
33path_param!(number);
34
35#[derive(Deserialize)]
36struct FlowForm {
37 #[serde(default)]
38 csrf: String,
39 #[serde(default)]
40 style: String,
41}
42
43fn pull_href(ctx: &RepoCtx, number: i64) -> String {
44 repo_href(
45 &ctx.repo.owner_name,
46 &ctx.repo.name,
47 "pulls",
48 &number.to_string(),
49 )
50}
51
52fn can_write(ctx: &RepoCtx, user: &forge_core::User) -> bool {
53 authorize(Some(user), &ctx.repo, ctx.role, ctx.org_role, Action::Write).is_ok()
54}
55
56async fn load(cx: &Cx, ctx: &RepoCtx, number: i64) -> Result<PullRequest> {
57 let state = app_context::<AppState>(cx);
58 match state.store.pull_by_number(&ctx.repo.id, number).await? {
59 Some(pr) => Ok(pr),
60 None => Err(not_found().into()),
61 }
62}
63
64#[route(POST "/{owner}/{repo}/pulls/{number}/ready")]
65async fn ready_post(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Response> {
66 set_draft(cx, &form.csrf, false).await
67}
68
69#[route(POST "/{owner}/{repo}/pulls/{number}/draft")]
70async fn draft_post(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Response> {
71 set_draft(cx, &form.csrf, true).await
72}
73
74async fn set_draft(cx: &Cx, csrf: &str, draft: bool) -> Result<Response> {
75 let number = parse_number(path_param::<Number>(cx))?;
76 let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
77 let (user, _) = require_csrf(cx, csrf).await?;
78 let state = app_context::<AppState>(cx);
79 let pr = load(cx, &ctx, number).await?;
80 if ctx.repo.archived || !(can_write(&ctx, &user) || user.id == pr.issue.author_id) {
81 return Err(forbidden().into());
82 }
83 let href = pull_href(&ctx, number);
84 if pr.merged_at.is_some() || pr.issue.state != IssueState::Open {
85 return Err(see_other(href).into());
86 }
87 let changed = match state
88 .store
89 .set_pull_draft(&pr.issue.id, Some(&user.id), draft)
90 .await
91 {
92 Ok(changed) => changed,
93 Err(forge_core::Error::Conflict(_)) => false,
94 Err(e) => return Err(e.into()),
95 };
96 if changed {
97 let action = if draft {
98 "converted_to_draft"
99 } else {
100 "ready_for_review"
101 };
102 emit_item_action(state, &ctx.repo, &Sender::of(&user), true, number, action).await;
103 if !draft {
104 // Reviewers hear about the pull request now, not when it was opened as a draft.
105 notify::dispatch(
106 state,
107 &ctx.repo,
108 &pr.issue,
109 &user.id,
110 Activity::Opened,
111 Some(&pr.issue.body),
112 )
113 .await;
114 }
115 }
116 Err(see_other(href).into())
117}
118
119#[route(POST "/{owner}/{repo}/pulls/{number}/auto-merge")]
120async fn auto_merge_enable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Response> {
121 let number = parse_number(path_param::<Number>(cx))?;
122 let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
123 let (user, _) = require_csrf(cx, &form.csrf).await?;
124 if ctx.repo.archived || !can_write(&ctx, &user) {
125 return Err(forbidden().into());
126 }
127 let state = app_context::<AppState>(cx);
128 let pr = load(cx, &ctx, number).await?;
129 let style = form
130 .style
131 .parse::<MergeStyle>()
132 .map_err(|e| bad_request(e.to_string()))?;
133 let href = pull_href(&ctx, number);
134 if pr.merged_at.is_some() || pr.issue.state != IssueState::Open || pr.head_repo_id.is_none() {
135 return Err(see_other(href).into());
136 }
137 let gate = merge_gate(state, &ctx.repo, &pr).await?;
138 if !gate.waiting_only() {
139 return Err(see_other(format!("{href}?merge_error={ERR_AUTO_MERGE_BLOCKED}")).into());
140 }
141 state
142 .store
143 .enable_auto_merge(&pr.issue.id, &user.id, style)
144 .await?;
145 // Nothing may be missing by now: merge right away instead of waiting for an event.
146 crate::automerge::on_pull(state, &ctx.repo, number).await;
147 Err(see_other(href).into())
148}
149
150#[route(POST "/{owner}/{repo}/pulls/{number}/auto-merge/disable")]
151async fn auto_merge_disable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Response> {
152 let number = parse_number(path_param::<Number>(cx))?;
153 let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
154 let (user, _) = require_csrf(cx, &form.csrf).await?;
155 if ctx.repo.archived || !can_write(&ctx, &user) {
156 return Err(forbidden().into());
157 }
158 let state = app_context::<AppState>(cx);
159 let pr = load(cx, &ctx, number).await?;
160 state
161 .store
162 .disable_auto_merge(&pr.issue.id, Some(&user.id), "manual")
163 .await?;
164 Err(see_other(pull_href(&ctx, number)).into())
165}