forge
Explore
Log in

Don't you dare go Hollow

The merge gate and merge logic move from the merge page to merge.rs, the media and snippet file handlers under raw, and after_change under ci, so no infrastructure module depends on pages any more

Browse files at this commit

575873e0d18758910802aa6854ab0def41dfe930Ahmet Kaan GümüşParent: 372b0ec
  • refactor
    • the merge gate and merge logic move from the merge page to merge.rs, the media and snippet file handlers under raw, and after_change under ci, so no infrastructure module depends on pages any more
Show full message
♻️ refactor: the merge gate and merge logic move from the merge page to merge.rs, the media and snippet file handlers under raw, and after_change under ci, so no infrastructure module depends on pages any more
crates/forge-web/src/automerge.rsmodified+1 -1
@@ -8,7 +8,7 @@
8 8
9 use forge_core::{Action, IssueState, PullRequest, Repo, authorize};9 use forge_core::{Action, IssueState, PullRequest, Repo, authorize};
10 10
11-use crate::pages::pulls_merge::{MergeOutcome, merge_gate, perform_merge};11+use crate::merge::{MergeOutcome, merge_gate, perform_merge};
12 use crate::state::AppState;12 use crate::state::AppState;
13 13
14 /// Re-evaluates every open pull request of `repo_id` that has auto-merge on and whose head is14 /// Re-evaluates every open pull request of `repo_id` that has auto-merge on and whose head is
crates/forge-web/src/ci/mod.rsmodified+29 -0
@@ -174,6 +174,35 @@ fn short(text: &str) -> String {
174 .collect()174 .collect()
175 }175 }
176 176
177+/// Wakes the job queue and syncs the commit status of every job whose state changed since `before`.
178+/// A job missing from `before` (a fresh run) counts as changed.
179+pub async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> topcoat::Result<()> {
180+ state.ci_waker.notify_waiters();
181+ let Some(run) = state.store.run_by_id(run_id).await? else {
182+ return Ok(());
183+ };
184+ state.ci_live.bump_run(run_id);
185+ state.ci_live.bump_repo(&run.repo_id);
186+ for job in state.store.jobs_for_run(run_id).await? {
187+ // A cancel request on a running job changes no state, but its row shows "stopping".
188+ let changed = before
189+ .iter()
190+ .find(|old| old.id == job.id)
191+ .is_none_or(|old| {
192+ old.state != job.state || old.cancel_requested != job.cancel_requested
193+ });
194+ if changed {
195+ if job.state.is_terminal() {
196+ state.ci_live.close_job(&job.id);
197+ } else {
198+ state.ci_live.bump_job(&job.id);
199+ }
200+ sync_status(state, &run, &job).await;
201+ }
202+ }
203+ Ok(())
204+}
205+
177 #[cfg(test)]206 #[cfg(test)]
178 mod org_tests {207 mod org_tests {
179 use super::*;208 use super::*;
crates/forge-web/src/ci/schedule.rsmodified+1 -1
@@ -407,7 +407,7 @@ async fn cancel_superseded_runs(state: &AppState, run: &CiRun) -> forge_core::Re
407 for old in older.into_iter().filter(|old| old.number < run.number) {407 for old in older.into_iter().filter(|old| old.number < run.number) {
408 let before = state.store.jobs_for_run(&old.id).await?;408 let before = state.store.jobs_for_run(&old.id).await?;
409 state.store.request_cancel(&old.id).await?;409 state.store.request_cancel(&old.id).await?;
410- if let Err(e) = crate::pages::ci_runs::after_change(state, &old.id, &before).await {410+ if let Err(e) = crate::ci::after_change(state, &old.id, &before).await {
411 tracing::error!(error = %e, run_id = %old.id, "ci: syncing a superseded run failed");411 tracing::error!(error = %e, run_id = %old.id, "ci: syncing a superseded run failed");
412 }412 }
413 }413 }
crates/forge-web/src/main.rsmodified+1 -0
@@ -37,6 +37,7 @@ mod lfs;
37 mod lfs_pointer;37 mod lfs_pointer;
38 mod live;38 mod live;
39 mod mail;39 mod mail;
40+mod merge;
40 mod merge_queue;41 mod merge_queue;
41 mod mirrors;42 mod mirrors;
42 mod notify;43 mod notify;
crates/forge-web/src/merge.rsadded+464 -0
@@ -0,0 +1,464 @@
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+
4+use forge_core::protection::{Protection, effective};
5+use forge_core::store::commit_status::StatusState;
6+use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User};
7+use forge_git::browse::{CommitInfo, default_branch_commit};
8+use forge_git::pulls::{
9+ MergeCheck, RebaseResult, Signature, check_merge, commit_tree, is_ancestor, range_log,
10+ rebase_commits, update_ref_cas,
11+};
12+use forge_git::repo::repo_path;
13+use topcoat::router::StatusCode;
14+
15+use crate::internal::trigger_maintenance;
16+use crate::notify::{self, Activity};
17+use crate::post_update::after_ref_update;
18+use crate::state::AppState;
19+use crate::views::now_unix;
20+use crate::webhooks::emit::{Sender, emit_item_action};
21+
22+/// Commits listed in a squash message.
23+pub 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.
27+pub const ERR_CONFLICT: &str = "conflict";
28+pub const ERR_UP_TO_DATE: &str = "up_to_date";
29+pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible";
30+pub const ERR_BASE_MOVED: &str = "base_moved";
31+pub const ERR_HEAD_MOVED: &str = "head_moved";
32+pub const ERR_ALREADY_MERGED: &str = "already_merged";
33+pub const ERR_NOT_OPEN: &str = "not_open";
34+pub const ERR_HEAD_MISSING: &str = "head_missing";
35+pub const ERR_BASE_MISSING: &str = "base_missing";
36+pub const ERR_MESSAGE_INVALID: &str = "message_invalid";
37+pub const ERR_NEEDS_APPROVALS: &str = "needs_approvals";
38+pub const ERR_CHANGES_REQUESTED: &str = "changes_requested";
39+pub const ERR_NOT_UP_TO_DATE: &str = "not_up_to_date";
40+pub const ERR_DRAFT: &str = "draft";
41+pub const ERR_NEEDS_CHECKS: &str = "needs_checks";
42+pub const ERR_REBASE_CONFLICT: &str = "rebase_conflict";
43+pub const ERR_AUTO_MERGE_BLOCKED: &str = "auto_merge_blocked";
44+pub const ERR_QUEUE_REQUIRED: &str = "queue_required";
45+pub const ERR_QUEUE_ALREADY: &str = "queue_already";
46+
47+pub 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.";
48+pub const CONFLICTS_MSG: &str = "This branch has conflicts that must be resolved";
49+pub const MOVED_MSG: &str = "The base branch moved; reload and try again.";
50+pub const UP_TO_DATE_MSG: &str =
51+ "Nothing to merge: the head is already contained in the base branch.";
52+pub const FF_MSG: &str =
53+ "fast-forward not possible: the base branch has commits the head does not contain";
54+pub const ALREADY_MERGED_MSG: &str = "This pull request is already merged.";
55+pub const CLOSED_MSG: &str = "This pull request is closed.";
56+pub const HEAD_MISSING_MSG: &str =
57+ "The head repository was deleted, so this pull request cannot be merged.";
58+pub 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)]
63+pub 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.
69+pub 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+
84+pub 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.
93+pub 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)]
101+pub 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)]
117+pub struct RequiredCheck {
118+ pub context: String,
119+ pub state: Option<StatusState>,
120+}
121+
122+impl 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.
167+pub 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.
239+pub 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.
279+pub 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.
376+pub 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.
408+pub 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+
424+pub 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.
433+pub 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.
456+pub 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+}
crates/forge-web/src/merge_queue.rsmodified+2 -2
@@ -21,11 +21,11 @@ use forge_git::pulls::{set_ref, update_ref_cas};
21 use forge_git::repo::repo_path;21 use forge_git::repo::repo_path;
22 22
23 use crate::ci::schedule::merge_queue_run;23 use crate::ci::schedule::merge_queue_run;
24-use crate::notify::{self, Activity};24+use crate::merge::{
25-use crate::pages::pulls_merge::{
26 ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE,25 ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE,
27 ERR_QUEUE_ALREADY, MergeOutcome, finish_merge, merge_commit, merge_gate,26 ERR_QUEUE_ALREADY, MergeOutcome, finish_merge, merge_commit, merge_gate,
28 };27 };
28+use crate::notify::{self, Activity};
29 use crate::state::AppState;29 use crate::state::AppState;
30 30
31 /// Whether the protection of `branch` routes merges through the queue. Direct merges are refused31 /// Whether the protection of `branch` routes merges through the queue. Direct merges are refused
crates/forge-web/src/oci/mod.rsmodified+1 -1
@@ -6,7 +6,7 @@
6 //! in the blob store, shared by digest ([`blobs`]). Manifests and tags live in the database6 //! in the blob store, shared by digest ([`blobs`]). Manifests and tags live in the database
7 //! ([`manifests`]). Unreferenced blobs are removed by a mark and sweep after deletes ([`gc`]).7 //! ([`manifests`]). Unreferenced blobs are removed by a mark and sweep after deletes ([`gc`]).
8 //! Credentials come through `GET /v2/token` ([`auth`]); the Packages tab and the package page show8 //! Credentials come through `GET /v2/token` ([`auth`]); the Packages tab and the package page show
9-//! the images ([`crate::pages::packages`]).9+//! the images (the `packages` page).
10 //!10 //!
11 //! The `/v2/` path must reach the forge unchanged, with a large body limit and no request11 //! The `/v2/` path must reach the forge unchanged, with a large body limit and no request
12 //! buffering, since layers are big. docs/packages.md says how a proxy is set up.12 //! buffering, since layers are big. docs/packages.md says how a proxy is set up.
crates/forge-web/src/pages/blob.rsmodified+1 -1
@@ -18,7 +18,6 @@ use crate::lfs::has_object;
18 use crate::lfs_pointer;18 use crate::lfs_pointer;
19 use crate::pages::code_live::{follows_branch, live_url};19 use crate::pages::code_live::{follows_branch, live_url};
20 use crate::pages::finder::file_finder;20 use crate::pages::finder::file_finder;
21-use crate::pages::media::media_url;
22 use crate::pages::refs::{load_refs, ref_links};21 use crate::pages::refs::{load_refs, ref_links};
23 use crate::pages::repo::repo_head;22 use crate::pages::repo::repo_head;
24 use crate::pages::repo_ctx::load_repo;23 use crate::pages::repo_ctx::load_repo;
@@ -26,6 +25,7 @@ use crate::pages::repo_side::{code_sub, commit_strip, run_pips, run_rows, tree_f
26 use crate::pages::tree::{25 use crate::pages::tree::{
27 entry_rows, last_commits, latest_bar, link_context, read_dir, read_file, resolve, tree_table,26 entry_rows, last_commits, latest_bar, link_context, read_dir, read_file, resolve, tree_table,
28 };27 };
28+use crate::raw::media::media_url;
29 use crate::raw::raw_url;29 use crate::raw::raw_url;
30 use crate::render::highlight::highlight_lines;30 use crate::render::highlight::highlight_lines;
31 use crate::render::markdown::render_markdown;31 use crate::render::markdown::render_markdown;
crates/forge-web/src/pages/ci_runs.rsmodified+1 -29
@@ -32,6 +32,7 @@ use topcoat::router::{HeaderValue, page, path_param, route};
32 use topcoat::view::{View, component, view};32 use topcoat::view::{View, component, view};
33 33
34 use crate::auth::{current_user, require_csrf};34 use crate::auth::{current_user, require_csrf};
35+use crate::ci::after_change;
35 use crate::ci::log_path;36 use crate::ci::log_path;
36 use crate::i18n::timeline::{self as tl, K as TK};37 use crate::i18n::timeline::{self as tl, K as TK};
37 use crate::i18n::{38 use crate::i18n::{
@@ -330,35 +331,6 @@ async fn run_of(state: &AppState, ctx: &RepoCtx, number: &str) -> Result<CiRun>
330 }331 }
331 }332 }
332 333
333-/// Wakes the job queue and syncs the commit status of every job whose state changed since `before`.
334-/// A job missing from `before` (a fresh run) counts as changed.
335-pub(crate) async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Result<()> {
336- state.ci_waker.notify_waiters();
337- let Some(run) = state.store.run_by_id(run_id).await? else {
338- return Ok(());
339- };
340- state.ci_live.bump_run(run_id);
341- state.ci_live.bump_repo(&run.repo_id);
342- for job in state.store.jobs_for_run(run_id).await? {
343- // A cancel request on a running job changes no state, but its row shows "stopping".
344- let changed = before
345- .iter()
346- .find(|old| old.id == job.id)
347- .is_none_or(|old| {
348- old.state != job.state || old.cancel_requested != job.cancel_requested
349- });
350- if changed {
351- if job.state.is_terminal() {
352- state.ci_live.close_job(&job.id);
353- } else {
354- state.ci_live.bump_job(&job.id);
355- }
356- crate::ci::sync_status(state, &run, &job).await;
357- }
358- }
359- Ok(())
360-}
361-
362 /// A job name as the timeline's label column can hold it: a matrix combination shows its values334 /// A job name as the timeline's label column can hold it: a matrix combination shows its values
363 /// without the base name (the job list below groups them), and a long name is cut with an ellipsis.335 /// without the base name (the job list below groups them), and a long name is cut with an ellipsis.
364 fn gantt_name(name: &str) -> String {336 fn gantt_name(name: &str) -> String {
crates/forge-web/src/pages/merge_queue.rsmodified+1 -1
@@ -29,9 +29,9 @@ use crate::auth::require_csrf;
29 use crate::i18n::merge_queue::{self as g, K};29 use crate::i18n::merge_queue::{self as g, K};
30 use crate::i18n::{self, Lang};30 use crate::i18n::{self, Lang};
31 use crate::live::{changed_event, events_response};31 use crate::live::{changed_event, events_response};
32+use crate::merge::ERR_NOT_OPEN;
32 use crate::merge_queue as queue;33 use crate::merge_queue as queue;
33 use crate::pages::issue_parts::parse_number;34 use crate::pages::issue_parts::parse_number;
34-use crate::pages::pulls_merge::ERR_NOT_OPEN;
35 use crate::pages::repo::repo_head;35 use crate::pages::repo::repo_head;
36 use crate::pages::repo_ctx::{RepoCtx, load_repo};36 use crate::pages::repo_ctx::{RepoCtx, load_repo};
37 use crate::state::AppState;37 use crate::state::AppState;
crates/forge-web/src/pages/mod.rsmodified+0 -2
@@ -68,7 +68,6 @@ pub mod issues_live;
68 pub mod labels_css;68 pub mod labels_css;
69 pub mod labels_page;69 pub mod labels_page;
70 pub mod login;70 pub mod login;
71-pub mod media;
72 pub mod merge_queue;71 pub mod merge_queue;
73 pub mod milestones_page;72 pub mod milestones_page;
74 pub mod needs_you;73 pub mod needs_you;
@@ -141,7 +140,6 @@ pub mod settings_sessions;
141 pub mod settings_tokens;140 pub mod settings_tokens;
142 pub mod setup;141 pub mod setup;
143 pub mod shell_events;142 pub mod shell_events;
144-pub mod snippet_raw;
145 pub mod snippets;143 pub mod snippets;
146 pub mod snippets_live;144 pub mod snippets_live;
147 pub mod star;145 pub mod star;
crates/forge-web/src/pages/pull_flow.rsmodified+1 -1
@@ -20,9 +20,9 @@ use topcoat::router::response::Response;
20 use topcoat::router::{path_param, route};20 use topcoat::router::{path_param, route};
21 21
22 use crate::auth::require_csrf;22 use crate::auth::require_csrf;
23+use crate::merge::{ERR_AUTO_MERGE_BLOCKED, merge_gate};
23 use crate::notify::{self, Activity};24 use crate::notify::{self, Activity};
24 use crate::pages::issue_parts::parse_number;25 use crate::pages::issue_parts::parse_number;
25-use crate::pages::pulls_merge::{ERR_AUTO_MERGE_BLOCKED, merge_gate};
26 use crate::pages::repo_ctx::{RepoCtx, load_repo};26 use crate::pages::repo_ctx::{RepoCtx, load_repo};
27 use crate::state::AppState;27 use crate::state::AppState;
28 use crate::views::repo_href;28 use crate::views::repo_href;
crates/forge-web/src/pages/pull_reviews.rsmodified+1 -1
@@ -31,9 +31,9 @@ use crate::auth::require_user;
31 use crate::i18n::pulls_review::{self as g, K};31 use crate::i18n::pulls_review::{self as g, K};
32 use crate::i18n::{self, Lang};32 use crate::i18n::{self, Lang};
33 use crate::internal::{may_push_directly, trigger_maintenance};33 use crate::internal::{may_push_directly, trigger_maintenance};
34+use crate::merge::contact_email;
34 use crate::notify::{self, Activity};35 use crate::notify::{self, Activity};
35 use crate::pages::issue_parts::{check_write, csrf_of, may_change, may_converse, parse_number};36 use crate::pages::issue_parts::{check_write, csrf_of, may_change, may_converse, parse_number};
36-use crate::pages::pulls_merge::contact_email;
37 use crate::pages::repo::repo_head;37 use crate::pages::repo::repo_head;
38 use crate::pages::repo_ctx::{RepoCtx, load_repo};38 use crate::pages::repo_ctx::{RepoCtx, load_repo};
39 use crate::post_update::after_ref_update;39 use crate::post_update::after_ref_update;
crates/forge-web/src/pages/pull_view.rsmodified+7 -7
@@ -22,6 +22,13 @@ use topcoat::view::{Child, View, component, view};
22 use crate::auth::require_user;22 use crate::auth::require_user;
23 use crate::i18n::pulls_review::{self as g, K};23 use crate::i18n::pulls_review::{self as g, K};
24 use crate::i18n::{self, Lang};24 use crate::i18n::{self, Lang};
25+use crate::merge::{
26+ ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED,
27+ ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING,
28+ ERR_HEAD_MOVED, ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN,
29+ ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE,
30+ merge_gate,
31+};
25 use crate::pages::commits::{CommitRow, now_secs};32 use crate::pages::commits::{CommitRow, now_secs};
26 use crate::pages::issue_meta::item_href;33 use crate::pages::issue_meta::item_href;
27 use crate::pages::issue_parts::{34 use crate::pages::issue_parts::{
@@ -32,13 +39,6 @@ use crate::pages::issue_parts::{
32 use crate::pages::notifications::notify_box_for;39 use crate::pages::notifications::notify_box_for;
33 use crate::pages::pull_branch::{self, branch_box, branch_error_from};40 use crate::pages::pull_branch::{self, branch_box, branch_error_from};
34 use crate::pages::pull_reviews::error_text_in;41 use crate::pages::pull_reviews::error_text_in;
35-use crate::pages::pulls_merge::{
36- ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED,
37- ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING,
38- ERR_HEAD_MOVED, ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN,
39- ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE,
40- merge_gate,
41-};
42 use crate::pages::repo_ctx::{RepoCtx, load_repo};42 use crate::pages::repo_ctx::{RepoCtx, load_repo};
43 use crate::pages::review_requests::{load_reviewers, reviewers_box};43 use crate::pages::review_requests::{load_reviewers, reviewers_box};
44 use crate::state::AppState;44 use crate::state::AppState;
crates/forge-web/src/pages/pulls_merge.rsmodified+3 -454
@@ -12,15 +12,7 @@
12 //! does not run for it. After the ref moves, the pull request is marked merged and the same12 //! does not run for it. After the ref moves, the pull request is marked merged and the same
13 //! post-update work a push gets runs (closing keywords, maintenance, mergeability of other pulls).13 //! post-update work a push gets runs (closing keywords, maintenance, mergeability of other pulls).
14 14
15-use forge_core::protection::{Protection, effective};15+use forge_core::{Action, IssueState, MergeStyle, authorize};
16-use forge_core::store::commit_status::StatusState;
17-use forge_core::{Action, IssueState, MergeStyle, PullRequest, ReviewState, Role, User, authorize};
18-use forge_git::browse::{CommitInfo, default_branch_commit};
19-use forge_git::pulls::{
20- MergeCheck, RebaseResult, Signature, check_merge, commit_tree, is_ancestor, range_log,
21- rebase_commits, update_ref_cas,
22-};
23-use forge_git::repo::repo_path;
24 use http::HeaderValue;16 use http::HeaderValue;
25 use http::header::CONTENT_TYPE;17 use http::header::CONTENT_TYPE;
26 use serde::Deserialize;18 use serde::Deserialize;
@@ -32,14 +24,11 @@ use topcoat::router::response::Response;
32 use topcoat::router::{Body, StatusCode, path_param, route};24 use topcoat::router::{Body, StatusCode, path_param, route};
33 25
34 use crate::auth::require_csrf;26 use crate::auth::require_csrf;
35-use crate::internal::trigger_maintenance;27+use crate::merge::*;
36-use crate::notify::{self, Activity};
37 use crate::pages::issue_parts::parse_number;28 use crate::pages::issue_parts::parse_number;
38 use crate::pages::repo_ctx::load_repo;29 use crate::pages::repo_ctx::load_repo;
39-use crate::post_update::after_ref_update;
40 use crate::state::AppState;30 use crate::state::AppState;
41-use crate::views::{now_unix, repo_href};31+use crate::views::repo_href;
42-use crate::webhooks::emit::{Sender, emit_item_action};
43 32
44 path_param!(owner);33 path_param!(owner);
45 path_param!(repo);34 path_param!(repo);
@@ -47,43 +36,6 @@ path_param!(number);
47 36
48 /// Largest accepted merge message, in bytes.37 /// Largest accepted merge message, in bytes.
49 const MAX_MESSAGE_BYTES: usize = 64 * 1024;38 const MAX_MESSAGE_BYTES: usize = 64 * 1024;
50-/// Commits listed in a squash message.
51-const MAX_SQUASH_COMMITS: usize = 250;
52-
53-/// Refusal codes, sent as `?merge_error=<code>` on the pull request page. The page owns the
54-/// wording for each code; a code outside this set is never echoed back.
55-pub const ERR_CONFLICT: &str = "conflict";
56-pub const ERR_UP_TO_DATE: &str = "up_to_date";
57-pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible";
58-pub const ERR_BASE_MOVED: &str = "base_moved";
59-pub const ERR_HEAD_MOVED: &str = "head_moved";
60-pub const ERR_ALREADY_MERGED: &str = "already_merged";
61-pub const ERR_NOT_OPEN: &str = "not_open";
62-pub const ERR_HEAD_MISSING: &str = "head_missing";
63-pub const ERR_BASE_MISSING: &str = "base_missing";
64-pub const ERR_MESSAGE_INVALID: &str = "message_invalid";
65-pub const ERR_NEEDS_APPROVALS: &str = "needs_approvals";
66-pub const ERR_CHANGES_REQUESTED: &str = "changes_requested";
67-pub const ERR_NOT_UP_TO_DATE: &str = "not_up_to_date";
68-pub const ERR_DRAFT: &str = "draft";
69-pub const ERR_NEEDS_CHECKS: &str = "needs_checks";
70-pub const ERR_REBASE_CONFLICT: &str = "rebase_conflict";
71-pub const ERR_AUTO_MERGE_BLOCKED: &str = "auto_merge_blocked";
72-pub const ERR_QUEUE_REQUIRED: &str = "queue_required";
73-pub const ERR_QUEUE_ALREADY: &str = "queue_already";
74-
75-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.";
76-const CONFLICTS_MSG: &str = "This branch has conflicts that must be resolved";
77-const MOVED_MSG: &str = "The base branch moved; reload and try again.";
78-const UP_TO_DATE_MSG: &str = "Nothing to merge: the head is already contained in the base branch.";
79-const FF_MSG: &str =
80- "fast-forward not possible: the base branch has commits the head does not contain";
81-const ALREADY_MERGED_MSG: &str = "This pull request is already merged.";
82-const CLOSED_MSG: &str = "This pull request is closed.";
83-const HEAD_MISSING_MSG: &str =
84- "The head repository was deleted, so this pull request cannot be merged.";
85-const BASE_MISSING_MSG: &str = "The base branch does not exist.";
86-
87 #[derive(Deserialize)]39 #[derive(Deserialize)]
88 struct MergeForm {40 struct MergeForm {
89 #[serde(default)]41 #[serde(default)]
@@ -100,14 +52,6 @@ struct MergeForm {
100 head: String,52 head: String,
101 }53 }
102 54
103-/// What a merge attempt did: the base branch now points at `commit`, or the attempt was refused
104-/// with an HTTP status and a message for the viewer.
105-#[derive(Debug, PartialEq, Eq)]
106-pub enum MergeOutcome {
107- Merged { commit: String },
108- Refused { status: StatusCode, message: String },
109-}
110-
111 #[route(POST "/{owner}/{repo}/pulls/{number}/merge")]55 #[route(POST "/{owner}/{repo}/pulls/{number}/merge")]
112 async fn merge_post(cx: &Cx, Form(form): Form<MergeForm>) -> Result<Response> {56 async fn merge_post(cx: &Cx, Form(form): Form<MergeForm>) -> Result<Response> {
113 let number = parse_number(number(cx))?;57 let number = parse_number(number(cx))?;
@@ -189,22 +133,6 @@ fn back_to_pull(pull_href: &str, code: &str) -> Result<Response> {
189 Err(see_other(format!("{pull_href}?merge_error={code}")).into())133 Err(see_other(format!("{pull_href}?merge_error={code}")).into())
190 }134 }
191 135
192-/// The refusal code for a message `perform_merge` returns, if it has one.
193-fn refusal_code(message: &str) -> Option<&'static str> {
194- Some(match message {
195- CONFLICTS_MSG => ERR_CONFLICT,
196- UP_TO_DATE_MSG => ERR_UP_TO_DATE,
197- FF_MSG => ERR_FF_IMPOSSIBLE,
198- REBASE_CONFLICT_MSG => ERR_REBASE_CONFLICT,
199- MOVED_MSG => ERR_BASE_MOVED,
200- ALREADY_MERGED_MSG => ERR_ALREADY_MERGED,
201- CLOSED_MSG => ERR_NOT_OPEN,
202- HEAD_MISSING_MSG => ERR_HEAD_MISSING,
203- BASE_MISSING_MSG => ERR_BASE_MISSING,
204- _ => return None,
205- })
206-}
207-
208 /// A blank message means "use the default". Otherwise CRLF becomes LF. A message over 64 KiB or136 /// A blank message means "use the default". Otherwise CRLF becomes LF. A message over 64 KiB or
209 /// with a NUL byte is rejected with the reason.137 /// with a NUL byte is rejected with the reason.
210 fn clean_message(raw: &str) -> std::result::Result<Option<String>, &'static str> {138 fn clean_message(raw: &str) -> std::result::Result<Option<String>, &'static str> {
@@ -231,385 +159,6 @@ fn refusal(status: StatusCode, message: &str) -> Response {
231 response159 response
232 }160 }
233 161
234-fn refused(status: StatusCode, message: &str) -> MergeOutcome {
235- MergeOutcome::Refused {
236- status,
237- message: message.to_owned(),
238- }
239-}
240-
241-/// Whether `user` is a reviewer whose approvals and change requests count under merge rules:
242-/// the repo owner, an instance admin, or a collaborator with Write, Maintain or Admin.
243-pub fn counts_for_merge_rules(repo: &forge_core::Repo, user: &User, role: Option<Role>) -> bool {
244- user.is_admin
245- || user.id == repo.owner_id
246- || matches!(role, Some(Role::Write | Role::Maintain | Role::Admin))
247-}
248-
249-/// The base branch's merge rule for a pull request, with the facts that rule checks.
250-#[derive(Debug, Clone, PartialEq, Eq)]
251-pub struct MergeGate {
252- pub rule: Protection,
253- /// Distinct counting reviewers whose latest submitted review is an approval.
254- pub approvals: u32,
255- /// Some counting reviewer's latest submitted review requests changes.
256- pub changes_requested: bool,
257- /// The head contains the current base tip. Always true when the rule does not require it.
258- pub up_to_date: bool,
259- /// The pull request is a draft.
260- pub draft: bool,
261- /// Each required check context with its state on the head commit (`None`: not reported).
262- pub required: Vec<RequiredCheck>,
263-}
264-
265-/// One required status check and where it stands on the pull request head.
266-#[derive(Debug, Clone, PartialEq, Eq)]
267-pub struct RequiredCheck {
268- pub context: String,
269- pub state: Option<StatusState>,
270-}
271-
272-impl MergeGate {
273- /// Every refusal code that currently blocks the merge, in the order they are reported.
274- pub fn blockers(&self) -> Vec<&'static str> {
275- let mut out = Vec::new();
276- if self.draft {
277- out.push(ERR_DRAFT);
278- }
279- if self.approvals < self.rule.required_approvals {
280- out.push(ERR_NEEDS_APPROVALS);
281- }
282- if self.rule.block_on_changes_requested && self.changes_requested {
283- out.push(ERR_CHANGES_REQUESTED);
284- }
285- if self
286- .required
287- .iter()
288- .any(|check| check.state != Some(StatusState::Success))
289- {
290- out.push(ERR_NEEDS_CHECKS);
291- }
292- if self.rule.require_up_to_date && !self.up_to_date {
293- out.push(ERR_NOT_UP_TO_DATE);
294- }
295- out
296- }
297-
298- /// The refusal code for the first rule that blocks the merge, if any.
299- pub fn blocked(&self) -> Option<&'static str> {
300- self.blockers().first().copied()
301- }
302-
303- /// Whether waiting could clear every blocker: only missing approvals or checks that are not
304- /// green yet. Auto-merge may be enabled only then (or when nothing blocks).
305- pub fn waiting_only(&self) -> bool {
306- self.blockers()
307- .iter()
308- .all(|code| matches!(*code, ERR_NEEDS_APPROVALS | ERR_NEEDS_CHECKS))
309- }
310-}
311-
312-/// Evaluates the effective rule for the pull request's base branch. Approvals and change requests
313-/// count only from `counts_for_merge_rules` reviewers, using each reviewer's latest review; an
314-/// approval counts only while the head is the commit it was given on.
315-/// Repo admins are not exempt. A base branch that does not exist counts as up to date; the merge
316-/// itself reports that.
317-pub async fn merge_gate(
318- state: &AppState,
319- repo: &forge_core::Repo,
320- pr: &PullRequest,
321-) -> forge_core::Result<MergeGate> {
322- let rules = state.store.list_branch_rules(&repo.id).await?;
323- let rule = effective(&rules, &repo.default_branch, &pr.base_branch);
324- let mut approvals = 0u32;
325- let mut changes_requested = false;
326- for (author_id, _, review, commit) in state.store.latest_review_states(&pr.issue.id).await? {
327- // An approval is of the commits the reviewer saw: a push after it leaves it uncounted
328- // until they approve again. A change request stands until it is dismissed or replaced.
329- if review == ReviewState::Approved && commit != pr.head_oid {
330- continue;
331- }
332- let Some(reviewer) = state.store.user_by_id(&author_id).await? else {
333- continue;
334- };
335- let collaborator = state.store.collaborator_role(&repo.id, &author_id).await?;
336- let org = state
337- .store
338- .org_repo_role(&repo.owner_id, &author_id, &repo.id)
339- .await?;
340- let role = forge_core::authz::max_role(collaborator, org);
341- if !counts_for_merge_rules(repo, &reviewer, role) {
342- continue;
343- }
344- match review {
345- ReviewState::Approved => approvals = approvals.saturating_add(1),
346- _ => changes_requested = true,
347- }
348- }
349- let up_to_date = if rule.require_up_to_date {
350- let base_path = repo_path(&state.git.data_dir, &repo.id)?;
351- match default_branch_commit(&base_path, &pr.base_branch)? {
352- Some(tip) => is_ancestor(&state.git, &base_path, &tip, &pr.head_oid).await?,
353- None => true,
354- }
355- } else {
356- true
357- };
358- let required = if rule.required_checks.is_empty() {
359- Vec::new()
360- } else {
361- let statuses = state.store.statuses_for(&repo.id, &pr.head_oid).await?;
362- rule.required_checks
363- .iter()
364- .map(|context| RequiredCheck {
365- context: context.clone(),
366- state: statuses
367- .iter()
368- .find(|s| &s.context == context)
369- .map(|s| s.state),
370- })
371- .collect()
372- };
373- Ok(MergeGate {
374- rule,
375- approvals,
376- changes_requested,
377- up_to_date,
378- draft: pr.draft,
379- required,
380- })
381-}
382-
383-/// Merges `pr` into its base branch in `repo` as `viewer`.
384-///
385-/// The base tip is `expected_base` when given, otherwise the current tip of the base branch. The
386-/// merge is checked and built against that tip, and the ref moves only if it still points there.
387-/// `message` replaces the default commit message (not used by fast-forward). Refusals that the
388-/// viewer can act on come back as `MergeOutcome::Refused`; git and database failures are errors.
389-pub async fn perform_merge(
390- state: &AppState,
391- repo: &forge_core::Repo,
392- pr: &PullRequest,
393- viewer: &User,
394- style: MergeStyle,
395- message: Option<&str>,
396- expected_base: Option<&str>,
397-) -> forge_core::Result<MergeOutcome> {
398- let base_path = repo_path(&state.git.data_dir, &repo.id)?;
399- let refname = format!("refs/heads/{}", pr.base_branch);
400- let base_tip = match expected_base {
401- Some(oid) => oid.to_owned(),
402- None => match default_branch_commit(&base_path, &pr.base_branch)? {
403- Some(oid) => oid,
404- None => {
405- return Ok(refused(StatusCode::CONFLICT, BASE_MISSING_MSG));
406- }
407- },
408- };
409- let new = match merge_commit(state, repo, pr, viewer, style, message, &base_tip).await? {
410- Ok(new) => new,
411- Err(refusal) => return Ok(refusal),
412- };
413-
414- match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await {
415- Ok(()) => {}
416- Err(forge_git::error::Error::RefMoved(_)) => {
417- return Ok(refused(StatusCode::CONFLICT, MOVED_MSG));
418- }
419- Err(e) => return Err(e.into()),
420- }
421-
422- finish_merge(state, repo, pr, viewer, &refname, &base_tip, &new).await;
423- Ok(MergeOutcome::Merged { commit: new })
424-}
425-
426-/// The commit that merging `pr` into `base_tip` makes in `style`, committed as `committer`. No ref
427-/// moves. A refusal the caller can act on comes back as the inner `Err`. Fast-forward returns the
428-/// head itself.
429-pub async fn merge_commit(
430- state: &AppState,
431- repo: &forge_core::Repo,
432- pr: &PullRequest,
433- committer: &User,
434- style: MergeStyle,
435- message: Option<&str>,
436- base_tip: &str,
437-) -> forge_core::Result<std::result::Result<String, MergeOutcome>> {
438- let base_path = repo_path(&state.git.data_dir, &repo.id)?;
439- let base_tip = base_tip.to_owned();
440- let viewer = committer;
441- let head = pr.head_oid.as_str();
442- let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? {
443- MergeCheck::Clean { tree } => tree,
444- MergeCheck::Conflict { .. } => {
445- return Ok(Err(refused(StatusCode::CONFLICT, CONFLICTS_MSG)));
446- }
447- MergeCheck::UpToDate => return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))),
448- };
449-
450- let now = now_unix();
451- let committer = Signature {
452- name: viewer.username.clone(),
453- email: contact_email(&state.config.base_url, viewer),
454- time_unix: now,
455- };
456- let new = match style {
457- MergeStyle::FastForward => {
458- if !is_ancestor(&state.git, &base_path, &base_tip, head).await? {
459- return Ok(Err(refused(StatusCode::CONFLICT, FF_MSG)));
460- }
461- head.to_owned()
462- }
463- MergeStyle::Rebase => {
464- match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? {
465- RebaseResult::Clean { tip, count } if count > 0 => tip,
466- RebaseResult::Clean { .. } => {
467- return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG)));
468- }
469- RebaseResult::Conflict { .. } => {
470- return Ok(Err(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG)));
471- }
472- }
473- }
474- MergeStyle::Merge => {
475- let text = match message {
476- Some(text) => text.to_owned(),
477- None => default_merge_message(state, pr).await?,
478- };
479- commit_tree(
480- &state.git,
481- &base_path,
482- &tree,
483- &[base_tip.as_str(), head],
484- &text,
485- &committer,
486- &committer,
487- )
488- .await?
489- }
490- MergeStyle::Squash => {
491- let author = match state.store.user_by_id(&pr.issue.author_id).await? {
492- Some(author) => Signature {
493- name: author.username.clone(),
494- email: contact_email(&state.config.base_url, &author),
495- time_unix: now,
496- },
497- None => committer.clone(),
498- };
499- let text = match message {
500- Some(text) => text.to_owned(),
501- None => {
502- let commits =
503- range_log(&state.git, &base_path, &base_tip, head, MAX_SQUASH_COMMITS)
504- .await?;
505- squash_message(pr, &commits)
506- }
507- };
508- commit_tree(
509- &state.git,
510- &base_path,
511- &tree,
512- &[base_tip.as_str()],
513- &text,
514- &author,
515- &committer,
516- )
517- .await?
518- }
519- };
520- Ok(Ok(new))
521-}
522-
523-/// The work after a merge moved `refname` from `base_tip` to `new`: the pull request is marked
524-/// merged, its events and notifications go out, and the ref update runs its post-update work.
525-/// Failures here are logged, not reported: the merge is already in place.
526-pub async fn finish_merge(
527- state: &AppState,
528- repo: &forge_core::Repo,
529- pr: &PullRequest,
530- viewer: &User,
531- refname: &str,
532- base_tip: &str,
533- new: &str,
534-) {
535- match state.store.mark_merged(&pr.issue.id, &viewer.id, new).await {
536- Ok(()) => {
537- let sender = Sender::of(viewer);
538- emit_item_action(state, repo, &sender, true, pr.issue.number, "merged").await;
539- notify::dispatch(state, repo, &pr.issue, &viewer.id, Activity::Merged, None).await;
540- }
541- Err(e) => {
542- tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "merge: mark_merged failed");
543- }
544- }
545- trigger_maintenance(&state.git, &repo.id);
546- // Boxed: the queue lands through this path, and the post-update work can reach the queue again.
547- if let Err(e) = Box::pin(after_ref_update(
548- state, repo, &viewer.id, refname, base_tip, new,
549- ))
550- .await
551- {
552- tracing::error!(error = %e, repo_id = %repo.id, ref_name = %refname, "merge: post-update failed");
553- }
554-}
555-
556-/// The address written into a commit for `user`: their email, or a noreply address on this
557-/// instance's host when they have none.
558-pub(crate) fn contact_email(base_url: &str, user: &User) -> String {
559- match user
560- .email
561- .as_deref()
562- .map(str::trim)
563- .filter(|e| !e.is_empty())
564- {
565- Some(email) => email.to_owned(),
566- None => format!(
567- "{}@users.noreply.{}",
568- user.username,
569- base_url_host(base_url)
570- ),
571- }
572-}
573-
574-fn base_url_host(base_url: &str) -> String {
575- base_url
576- .parse::<http::Uri>()
577- .ok()
578- .and_then(|uri| uri.host().map(str::to_owned))
579- .unwrap_or_else(|| "localhost".to_owned())
580-}
581-
582-/// `Merge pull request #N from owner/branch`, a blank line, then the pull request title.
583-async fn default_merge_message(state: &AppState, pr: &PullRequest) -> forge_core::Result<String> {
584- let head_owner = match pr.head_repo_id.as_deref() {
585- Some(id) => state
586- .store
587- .repo_by_id(id)
588- .await?
589- .map(|head| head.owner_name),
590- None => None,
591- };
592- let head = match head_owner {
593- Some(owner) => format!("{owner}/{}", pr.head_branch),
594- None => pr.head_branch.clone(),
595- };
596- Ok(format!(
597- "Merge pull request #{} from {head}\n\n{}",
598- pr.issue.number, pr.issue.title
599- ))
600-}
601-
602-/// `<title> (#N)`, a blank line, then one `- <summary>` line per commit, oldest first.
603-fn squash_message(pr: &PullRequest, commits: &[CommitInfo]) -> String {
604- let mut text = format!("{} (#{})\n\n", pr.issue.title, pr.issue.number);
605- for commit in commits {
606- text.push_str("- ");
607- text.push_str(&commit.summary);
608- text.push('\n');
609- }
610- text
611-}
612-
613 #[cfg(test)]162 #[cfg(test)]
614 mod tests {163 mod tests {
615 use std::path::{Path, PathBuf};164 use std::path::{Path, PathBuf};
crates/forge-web/src/pages/snippets.rsmodified+1 -1
@@ -22,8 +22,8 @@ use crate::audit::{self, Actor, Target};
22 use crate::auth::{current_user, require_csrf, require_user};22 use crate::auth::{current_user, require_csrf, require_user};
23 use crate::i18n::community::{self as g, K};23 use crate::i18n::community::{self as g, K};
24 use crate::i18n::{self, Lang};24 use crate::i18n::{self, Lang};
25-use crate::pages::snippet_raw::snippet_raw_url;
26 use crate::pages::snippets_live::{bump_snippet, item_live_url, list_live_url};25 use crate::pages::snippets_live::{bump_snippet, item_live_url, list_live_url};
26+use crate::raw::snippet_raw::snippet_raw_url;
27 use crate::render::highlight::highlight_lines;27 use crate::render::highlight::highlight_lines;
28 use crate::render::markdown::render_markdown;28 use crate::render::markdown::render_markdown;
29 use crate::state::AppState;29 use crate::state::AppState;
crates/forge-web/src/pages/media.rs → crates/forge-web/src/raw/media.rsrenamed+0 -0
crates/forge-web/src/raw.rs → crates/forge-web/src/raw/mod.rsrenamed+5 -2
@@ -1,6 +1,9 @@
1 //! Raw user-content origin (separate listener, explicit routes; never `.discover()`).1 //! Raw user-content origin (separate listener, explicit routes; never `.discover()`).
2 //! See docs/architecture.md, section 5.5.2 //! See docs/architecture.md, section 5.5.
3 3
4+pub mod media;
5+pub mod snippet_raw;
6+
4 use std::path::Path;7 use std::path::Path;
5 use std::process::Stdio;8 use std::process::Stdio;
6 use std::time::{SystemTime, UNIX_EPOCH};9 use std::time::{SystemTime, UNIX_EPOCH};
@@ -103,13 +106,13 @@ pub fn router(state: AppState) -> Router {
103 .route(RouteFn::new(106 .route(RouteFn::new(
104 vec![Method::GET, Method::HEAD],107 vec![Method::GET, Method::HEAD],
105 "/{owner}/{repo}/-/media/{*rest}",108 "/{owner}/{repo}/-/media/{*rest}",
106- crate::pages::media::media_file,109+ crate::raw::media::media_file,
107 ))110 ))
108 // Snippet files sit under the same reserved `-` segment: `/-/snippets/{id}/{file}`.111 // Snippet files sit under the same reserved `-` segment: `/-/snippets/{id}/{file}`.
109 .route(RouteFn::new(112 .route(RouteFn::new(
110 vec![Method::GET, Method::HEAD],113 vec![Method::GET, Method::HEAD],
111 "/-/snippets/{id}/{*rest}",114 "/-/snippets/{id}/{*rest}",
112- crate::pages::snippet_raw::snippet_file,115+ crate::raw::snippet_raw::snippet_file,
113 ))116 ))
114 .route(RouteFn::new(Method::GET, "/healthz", healthz))117 .route(RouteFn::new(Method::GET, "/healthz", healthz))
115 // Responses must match the bytes behind the ETag and Content-Length.118 // Responses must match the bytes behind the ETag and Content-Length.
crates/forge-web/src/pages/snippet_raw.rs → crates/forge-web/src/raw/snippet_raw.rsrenamed+0 -0