forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

merge.rs464 lines, 17.3 KiBHistoryRawDownload
1//! Merging a pull request: the merge gate, the merge itself and what follows it, shared by the
2//! merge page, auto-merge and the merge queue.
3
4use forge_core::protection::{Protection, effective};
5use forge_core::store::commit_status::StatusState;
6use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User};
7use forge_git::browse::{CommitInfo, default_branch_commit};
8use forge_git::pulls::{
9 MergeCheck, RebaseResult, Signature, check_merge, commit_tree, is_ancestor, range_log,
10 rebase_commits, update_ref_cas,
11};
12use forge_git::repo::repo_path;
13use topcoat::router::StatusCode;
14
15use crate::internal::trigger_maintenance;
16use crate::notify::{self, Activity};
17use crate::post_update::after_ref_update;
18use crate::state::AppState;
19use crate::views::now_unix;
20use crate::webhooks::emit::{Sender, emit_item_action};
21
22/// Commits listed in a squash message.
23pub const MAX_SQUASH_COMMITS: usize = 250;
24
25/// Refusal codes, sent as `?merge_error=<code>` on the pull request page. The page owns the
26/// wording for each code; a code outside this set is never echoed back.
27pub const ERR_CONFLICT: &str = "conflict";
28pub const ERR_UP_TO_DATE: &str = "up_to_date";
29pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible";
30pub const ERR_BASE_MOVED: &str = "base_moved";
31pub const ERR_HEAD_MOVED: &str = "head_moved";
32pub const ERR_ALREADY_MERGED: &str = "already_merged";
33pub const ERR_NOT_OPEN: &str = "not_open";
34pub const ERR_HEAD_MISSING: &str = "head_missing";
35pub const ERR_BASE_MISSING: &str = "base_missing";
36pub const ERR_MESSAGE_INVALID: &str = "message_invalid";
37pub const ERR_NEEDS_APPROVALS: &str = "needs_approvals";
38pub const ERR_CHANGES_REQUESTED: &str = "changes_requested";
39pub const ERR_NOT_UP_TO_DATE: &str = "not_up_to_date";
40pub const ERR_DRAFT: &str = "draft";
41pub const ERR_NEEDS_CHECKS: &str = "needs_checks";
42pub const ERR_REBASE_CONFLICT: &str = "rebase_conflict";
43pub const ERR_AUTO_MERGE_BLOCKED: &str = "auto_merge_blocked";
44pub const ERR_QUEUE_REQUIRED: &str = "queue_required";
45pub const ERR_QUEUE_ALREADY: &str = "queue_already";
46
47pub const REBASE_CONFLICT_MSG: &str = "Rebase failed: a commit does not apply cleanly on the base branch. Resolve the conflicts or use another merge style.";
48pub const CONFLICTS_MSG: &str = "This branch has conflicts that must be resolved";
49pub const MOVED_MSG: &str = "The base branch moved; reload and try again.";
50pub const UP_TO_DATE_MSG: &str =
51 "Nothing to merge: the head is already contained in the base branch.";
52pub const FF_MSG: &str =
53 "fast-forward not possible: the base branch has commits the head does not contain";
54pub const ALREADY_MERGED_MSG: &str = "This pull request is already merged.";
55pub const CLOSED_MSG: &str = "This pull request is closed.";
56pub const HEAD_MISSING_MSG: &str =
57 "The head repository was deleted, so this pull request cannot be merged.";
58pub const BASE_MISSING_MSG: &str = "The base branch does not exist.";
59
60/// What a merge attempt did: the base branch now points at `commit`, or the attempt was refused
61/// with an HTTP status and a message for the viewer.
62#[derive(Debug, PartialEq, Eq)]
63pub enum MergeOutcome {
64 Merged { commit: String },
65 Refused { status: StatusCode, message: String },
66}
67
68/// The refusal code for a message `perform_merge` returns, if it has one.
69pub fn refusal_code(message: &str) -> Option<&'static str> {
70 Some(match message {
71 CONFLICTS_MSG => ERR_CONFLICT,
72 UP_TO_DATE_MSG => ERR_UP_TO_DATE,
73 FF_MSG => ERR_FF_IMPOSSIBLE,
74 REBASE_CONFLICT_MSG => ERR_REBASE_CONFLICT,
75 MOVED_MSG => ERR_BASE_MOVED,
76 ALREADY_MERGED_MSG => ERR_ALREADY_MERGED,
77 CLOSED_MSG => ERR_NOT_OPEN,
78 HEAD_MISSING_MSG => ERR_HEAD_MISSING,
79 BASE_MISSING_MSG => ERR_BASE_MISSING,
80 _ => return None,
81 })
82}
83
84pub fn refused(status: StatusCode, message: &str) -> MergeOutcome {
85 MergeOutcome::Refused {
86 status,
87 message: message.to_owned(),
88 }
89}
90
91/// Whether `user` is a reviewer whose approvals and change requests count under merge rules:
92/// the repo owner, an instance admin, or a collaborator with Write, Maintain or Admin.
93pub fn counts_for_merge_rules(repo: &forge_core::Repo, user: &User, role: Option<Role>) -> bool {
94 user.is_admin
95 || user.id == repo.owner_id
96 || matches!(role, Some(Role::Write | Role::Maintain | Role::Admin))
97}
98
99/// The base branch's merge rule for a pull request, with the facts that rule checks.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct MergeGate {
102 pub rule: Protection,
103 /// Distinct counting reviewers whose latest submitted review is an approval.
104 pub approvals: u32,
105 /// Some counting reviewer's latest submitted review requests changes.
106 pub changes_requested: bool,
107 /// The head contains the current base tip. Always true when the rule does not require it.
108 pub up_to_date: bool,
109 /// The pull request is a draft.
110 pub draft: bool,
111 /// Each required check context with its state on the head commit (`None`: not reported).
112 pub required: Vec<RequiredCheck>,
113}
114
115/// One required status check and where it stands on the pull request head.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct RequiredCheck {
118 pub context: String,
119 pub state: Option<StatusState>,
120}
121
122impl MergeGate {
123 /// Every refusal code that currently blocks the merge, in the order they are reported.
124 pub fn blockers(&self) -> Vec<&'static str> {
125 let mut out = Vec::new();
126 if self.draft {
127 out.push(ERR_DRAFT);
128 }
129 if self.approvals < self.rule.required_approvals {
130 out.push(ERR_NEEDS_APPROVALS);
131 }
132 if self.rule.block_on_changes_requested && self.changes_requested {
133 out.push(ERR_CHANGES_REQUESTED);
134 }
135 if self
136 .required
137 .iter()
138 .any(|check| check.state != Some(StatusState::Success))
139 {
140 out.push(ERR_NEEDS_CHECKS);
141 }
142 if self.rule.require_up_to_date && !self.up_to_date {
143 out.push(ERR_NOT_UP_TO_DATE);
144 }
145 out
146 }
147
148 /// The refusal code for the first rule that blocks the merge, if any.
149 pub fn blocked(&self) -> Option<&'static str> {
150 self.blockers().first().copied()
151 }
152
153 /// Whether waiting could clear every blocker: only missing approvals or checks that are not
154 /// green yet. Auto-merge may be enabled only then (or when nothing blocks).
155 pub fn waiting_only(&self) -> bool {
156 self.blockers()
157 .iter()
158 .all(|code| matches!(*code, ERR_NEEDS_APPROVALS | ERR_NEEDS_CHECKS))
159 }
160}
161
162/// Evaluates the effective rule for the pull request's base branch. Approvals and change requests
163/// count only from `counts_for_merge_rules` reviewers, using each reviewer's latest review; an
164/// approval counts only while the head is the commit it was given on.
165/// Repo admins are not exempt. A base branch that does not exist counts as up to date; the merge
166/// itself reports that.
167pub async fn merge_gate(
168 state: &AppState,
169 repo: &forge_core::Repo,
170 pr: &PullRequest,
171) -> forge_core::Result<MergeGate> {
172 let rules = state.store.list_branch_rules(&repo.id).await?;
173 let rule = effective(&rules, &repo.default_branch, &pr.base_branch);
174 let mut approvals = 0u32;
175 let mut changes_requested = false;
176 for (author_id, _, review, commit) in state.store.latest_review_states(&pr.issue.id).await? {
177 // An approval is of the commits the reviewer saw: a push after it leaves it uncounted
178 // until they approve again. A change request stands until it is dismissed or replaced.
179 if review == ReviewState::Approved && commit != pr.head_oid {
180 continue;
181 }
182 let Some(reviewer) = state.store.user_by_id(&author_id).await? else {
183 continue;
184 };
185 let collaborator = state.store.collaborator_role(&repo.id, &author_id).await?;
186 let org = state
187 .store
188 .org_repo_role(&repo.owner_id, &author_id, &repo.id)
189 .await?;
190 let role = forge_core::authz::max_role(collaborator, org);
191 if !counts_for_merge_rules(repo, &reviewer, role) {
192 continue;
193 }
194 match review {
195 ReviewState::Approved => approvals = approvals.saturating_add(1),
196 _ => changes_requested = true,
197 }
198 }
199 let up_to_date = if rule.require_up_to_date {
200 let base_path = repo_path(&state.git.data_dir, &repo.id)?;
201 match default_branch_commit(&base_path, &pr.base_branch)? {
202 Some(tip) => is_ancestor(&state.git, &base_path, &tip, &pr.head_oid).await?,
203 None => true,
204 }
205 } else {
206 true
207 };
208 let required = if rule.required_checks.is_empty() {
209 Vec::new()
210 } else {
211 let statuses = state.store.statuses_for(&repo.id, &pr.head_oid).await?;
212 rule.required_checks
213 .iter()
214 .map(|context| RequiredCheck {
215 context: context.clone(),
216 state: statuses
217 .iter()
218 .find(|s| &s.context == context)
219 .map(|s| s.state),
220 })
221 .collect()
222 };
223 Ok(MergeGate {
224 rule,
225 approvals,
226 changes_requested,
227 up_to_date,
228 draft: pr.draft,
229 required,
230 })
231}
232
233/// Merges `pr` into its base branch in `repo` as `viewer`.
234///
235/// The base tip is `expected_base` when given, otherwise the current tip of the base branch. The
236/// merge is checked and built against that tip, and the ref moves only if it still points there.
237/// `message` replaces the default commit message (not used by fast-forward). Refusals that the
238/// viewer can act on come back as `MergeOutcome::Refused`; git and database failures are errors.
239pub async fn perform_merge(
240 state: &AppState,
241 repo: &forge_core::Repo,
242 pr: &PullRequest,
243 viewer: &User,
244 style: MergeStyle,
245 message: Option<&str>,
246 expected_base: Option<&str>,
247) -> forge_core::Result<MergeOutcome> {
248 let base_path = repo_path(&state.git.data_dir, &repo.id)?;
249 let refname = format!("refs/heads/{}", pr.base_branch);
250 let base_tip = match expected_base {
251 Some(oid) => oid.to_owned(),
252 None => match default_branch_commit(&base_path, &pr.base_branch)? {
253 Some(oid) => oid,
254 None => {
255 return Ok(refused(StatusCode::CONFLICT, BASE_MISSING_MSG));
256 }
257 },
258 };
259 let new = match merge_commit(state, repo, pr, viewer, style, message, &base_tip).await? {
260 Ok(new) => new,
261 Err(refusal) => return Ok(refusal),
262 };
263
264 match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await {
265 Ok(()) => {}
266 Err(forge_git::error::Error::RefMoved(_)) => {
267 return Ok(refused(StatusCode::CONFLICT, MOVED_MSG));
268 }
269 Err(e) => return Err(e.into()),
270 }
271
272 finish_merge(state, repo, pr, viewer, &refname, &base_tip, &new).await;
273 Ok(MergeOutcome::Merged { commit: new })
274}
275
276/// The commit that merging `pr` into `base_tip` makes in `style`, committed as `committer`. No ref
277/// moves. A refusal the caller can act on comes back as the inner `Err`. Fast-forward returns the
278/// head itself.
279pub async fn merge_commit(
280 state: &AppState,
281 repo: &forge_core::Repo,
282 pr: &PullRequest,
283 committer: &User,
284 style: MergeStyle,
285 message: Option<&str>,
286 base_tip: &str,
287) -> forge_core::Result<std::result::Result<String, MergeOutcome>> {
288 let base_path = repo_path(&state.git.data_dir, &repo.id)?;
289 let base_tip = base_tip.to_owned();
290 let viewer = committer;
291 let head = pr.head_oid.as_str();
292 let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? {
293 MergeCheck::Clean { tree } => tree,
294 MergeCheck::Conflict { .. } => {
295 return Ok(Err(refused(StatusCode::CONFLICT, CONFLICTS_MSG)));
296 }
297 MergeCheck::UpToDate => return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))),
298 };
299
300 let now = now_unix();
301 let committer = Signature {
302 name: viewer.username.clone(),
303 email: contact_email(&state.config.base_url, viewer),
304 time_unix: now,
305 };
306 let new = match style {
307 MergeStyle::FastForward => {
308 if !is_ancestor(&state.git, &base_path, &base_tip, head).await? {
309 return Ok(Err(refused(StatusCode::CONFLICT, FF_MSG)));
310 }
311 head.to_owned()
312 }
313 MergeStyle::Rebase => {
314 match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? {
315 RebaseResult::Clean { tip, count } if count > 0 => tip,
316 RebaseResult::Clean { .. } => {
317 return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG)));
318 }
319 RebaseResult::Conflict { .. } => {
320 return Ok(Err(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG)));
321 }
322 }
323 }
324 MergeStyle::Merge => {
325 let text = match message {
326 Some(text) => text.to_owned(),
327 None => default_merge_message(state, pr).await?,
328 };
329 commit_tree(
330 &state.git,
331 &base_path,
332 &tree,
333 &[base_tip.as_str(), head],
334 &text,
335 &committer,
336 &committer,
337 )
338 .await?
339 }
340 MergeStyle::Squash => {
341 let author = match state.store.user_by_id(&pr.issue.author_id).await? {
342 Some(author) => Signature {
343 name: author.username.clone(),
344 email: contact_email(&state.config.base_url, &author),
345 time_unix: now,
346 },
347 None => committer.clone(),
348 };
349 let text = match message {
350 Some(text) => text.to_owned(),
351 None => {
352 let commits =
353 range_log(&state.git, &base_path, &base_tip, head, MAX_SQUASH_COMMITS)
354 .await?;
355 squash_message(pr, &commits)
356 }
357 };
358 commit_tree(
359 &state.git,
360 &base_path,
361 &tree,
362 &[base_tip.as_str()],
363 &text,
364 &author,
365 &committer,
366 )
367 .await?
368 }
369 };
370 Ok(Ok(new))
371}
372
373/// The work after a merge moved `refname` from `base_tip` to `new`: the pull request is marked
374/// merged, its events and notifications go out, and the ref update runs its post-update work.
375/// Failures here are logged, not reported: the merge is already in place.
376pub async fn finish_merge(
377 state: &AppState,
378 repo: &forge_core::Repo,
379 pr: &PullRequest,
380 viewer: &User,
381 refname: &str,
382 base_tip: &str,
383 new: &str,
384) {
385 match state.store.mark_merged(&pr.issue.id, &viewer.id, new).await {
386 Ok(()) => {
387 let sender = Sender::of(viewer);
388 emit_item_action(state, repo, &sender, true, pr.issue.number, "merged").await;
389 notify::dispatch(state, repo, &pr.issue, &viewer.id, Activity::Merged, None).await;
390 }
391 Err(e) => {
392 tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "merge: mark_merged failed");
393 }
394 }
395 trigger_maintenance(&state.git, &repo.id);
396 // Boxed: the queue lands through this path, and the post-update work can reach the queue again.
397 if let Err(e) = Box::pin(after_ref_update(
398 state, repo, &viewer.id, refname, base_tip, new,
399 ))
400 .await
401 {
402 tracing::error!(error = %e, repo_id = %repo.id, ref_name = %refname, "merge: post-update failed");
403 }
404}
405
406/// The address written into a commit for `user`: their email, or a noreply address on this
407/// instance's host when they have none.
408pub fn contact_email(base_url: &str, user: &User) -> String {
409 match user
410 .email
411 .as_deref()
412 .map(str::trim)
413 .filter(|e| !e.is_empty())
414 {
415 Some(email) => email.to_owned(),
416 None => format!(
417 "{}@users.noreply.{}",
418 user.username,
419 base_url_host(base_url)
420 ),
421 }
422}
423
424pub fn base_url_host(base_url: &str) -> String {
425 base_url
426 .parse::<http::Uri>()
427 .ok()
428 .and_then(|uri| uri.host().map(str::to_owned))
429 .unwrap_or_else(|| "localhost".to_owned())
430}
431
432/// `Merge pull request #N from owner/branch`, a blank line, then the pull request title.
433pub async fn default_merge_message(
434 state: &AppState,
435 pr: &PullRequest,
436) -> forge_core::Result<String> {
437 let head_owner = match pr.head_repo_id.as_deref() {
438 Some(id) => state
439 .store
440 .repo_by_id(id)
441 .await?
442 .map(|head| head.owner_name),
443 None => None,
444 };
445 let head = match head_owner {
446 Some(owner) => format!("{owner}/{}", pr.head_branch),
447 None => pr.head_branch.clone(),
448 };
449 Ok(format!(
450 "Merge pull request #{} from {head}\n\n{}",
451 pr.issue.number, pr.issue.title
452 ))
453}
454
455/// `<title> (#N)`, a blank line, then one `- <summary>` line per commit, oldest first.
456pub fn squash_message(pr: &PullRequest, commits: &[CommitInfo]) -> String {
457 let mut text = format!("{} (#{})\n\n", pr.issue.title, pr.issue.number);
458 for commit in commits {
459 text.push_str("- ");
460 text.push_str(&commit.summary);
461 text.push('\n');
462 }
463 text
464}