From 575873e0d18758910802aa6854ab0def41dfe930 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Dec 2026 05:05:08 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20the=20merge=20?= =?UTF-8?q?gate=20and=20merge=20logic=20move=20from=20the=20merge=20page?= =?UTF-8?q?=20to=20merge.rs,=20the=20media=20and=20snippet=20file=20handle?= =?UTF-8?q?rs=20under=20raw,=20and=20after=5Fchange=20under=20ci,=20so=20n?= =?UTF-8?q?o=20infrastructure=20module=20depends=20on=20pages=20any=20more?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web/src/automerge.rs | 2 +- crates/forge-web/src/ci/mod.rs | 29 ++ crates/forge-web/src/ci/schedule.rs | 2 +- crates/forge-web/src/main.rs | 1 + crates/forge-web/src/merge.rs | 464 ++++++++++++++++++ crates/forge-web/src/merge_queue.rs | 4 +- crates/forge-web/src/oci/mod.rs | 2 +- crates/forge-web/src/pages/blob.rs | 2 +- crates/forge-web/src/pages/ci_runs.rs | 30 +- crates/forge-web/src/pages/merge_queue.rs | 2 +- crates/forge-web/src/pages/mod.rs | 2 - crates/forge-web/src/pages/pull_flow.rs | 2 +- crates/forge-web/src/pages/pull_reviews.rs | 2 +- crates/forge-web/src/pages/pull_view.rs | 14 +- crates/forge-web/src/pages/pulls_merge.rs | 457 +---------------- crates/forge-web/src/pages/snippets.rs | 2 +- crates/forge-web/src/{pages => raw}/media.rs | 0 crates/forge-web/src/{raw.rs => raw/mod.rs} | 7 +- .../src/{pages => raw}/snippet_raw.rs | 0 19 files changed, 520 insertions(+), 504 deletions(-) create mode 100644 crates/forge-web/src/merge.rs rename crates/forge-web/src/{pages => raw}/media.rs (100%) rename crates/forge-web/src/{raw.rs => raw/mod.rs} (99%) rename crates/forge-web/src/{pages => raw}/snippet_raw.rs (100%) diff --git a/crates/forge-web/src/automerge.rs b/crates/forge-web/src/automerge.rs index 9bac7d3..d3ac679 100644 --- a/crates/forge-web/src/automerge.rs +++ b/crates/forge-web/src/automerge.rs @@ -8,7 +8,7 @@ use forge_core::{Action, IssueState, PullRequest, Repo, authorize}; -use crate::pages::pulls_merge::{MergeOutcome, merge_gate, perform_merge}; +use crate::merge::{MergeOutcome, merge_gate, perform_merge}; use crate::state::AppState; /// Re-evaluates every open pull request of `repo_id` that has auto-merge on and whose head is diff --git a/crates/forge-web/src/ci/mod.rs b/crates/forge-web/src/ci/mod.rs index f1bfae4..56246bc 100644 --- a/crates/forge-web/src/ci/mod.rs +++ b/crates/forge-web/src/ci/mod.rs @@ -174,6 +174,35 @@ fn short(text: &str) -> String { .collect() } +/// Wakes the job queue and syncs the commit status of every job whose state changed since `before`. +/// A job missing from `before` (a fresh run) counts as changed. +pub async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> topcoat::Result<()> { + state.ci_waker.notify_waiters(); + let Some(run) = state.store.run_by_id(run_id).await? else { + return Ok(()); + }; + state.ci_live.bump_run(run_id); + state.ci_live.bump_repo(&run.repo_id); + for job in state.store.jobs_for_run(run_id).await? { + // A cancel request on a running job changes no state, but its row shows "stopping". + let changed = before + .iter() + .find(|old| old.id == job.id) + .is_none_or(|old| { + old.state != job.state || old.cancel_requested != job.cancel_requested + }); + if changed { + if job.state.is_terminal() { + state.ci_live.close_job(&job.id); + } else { + state.ci_live.bump_job(&job.id); + } + sync_status(state, &run, &job).await; + } + } + Ok(()) +} + #[cfg(test)] mod org_tests { use super::*; diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index c8929de..e9af497 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -407,7 +407,7 @@ async fn cancel_superseded_runs(state: &AppState, run: &CiRun) -> forge_core::Re for old in older.into_iter().filter(|old| old.number < run.number) { let before = state.store.jobs_for_run(&old.id).await?; state.store.request_cancel(&old.id).await?; - if let Err(e) = crate::pages::ci_runs::after_change(state, &old.id, &before).await { + if let Err(e) = crate::ci::after_change(state, &old.id, &before).await { tracing::error!(error = %e, run_id = %old.id, "ci: syncing a superseded run failed"); } } diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 676fc07..324f0f4 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -37,6 +37,7 @@ mod lfs; mod lfs_pointer; mod live; mod mail; +mod merge; mod merge_queue; mod mirrors; mod notify; diff --git a/crates/forge-web/src/merge.rs b/crates/forge-web/src/merge.rs new file mode 100644 index 0000000..a0796d8 --- /dev/null +++ b/crates/forge-web/src/merge.rs @@ -0,0 +1,464 @@ +//! Merging a pull request: the merge gate, the merge itself and what follows it, shared by the +//! merge page, auto-merge and the merge queue. + +use forge_core::protection::{Protection, effective}; +use forge_core::store::commit_status::StatusState; +use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User}; +use forge_git::browse::{CommitInfo, default_branch_commit}; +use forge_git::pulls::{ + MergeCheck, RebaseResult, Signature, check_merge, commit_tree, is_ancestor, range_log, + rebase_commits, update_ref_cas, +}; +use forge_git::repo::repo_path; +use topcoat::router::StatusCode; + +use crate::internal::trigger_maintenance; +use crate::notify::{self, Activity}; +use crate::post_update::after_ref_update; +use crate::state::AppState; +use crate::views::now_unix; +use crate::webhooks::emit::{Sender, emit_item_action}; + +/// Commits listed in a squash message. +pub const MAX_SQUASH_COMMITS: usize = 250; + +/// Refusal codes, sent as `?merge_error=` on the pull request page. The page owns the +/// wording for each code; a code outside this set is never echoed back. +pub const ERR_CONFLICT: &str = "conflict"; +pub const ERR_UP_TO_DATE: &str = "up_to_date"; +pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible"; +pub const ERR_BASE_MOVED: &str = "base_moved"; +pub const ERR_HEAD_MOVED: &str = "head_moved"; +pub const ERR_ALREADY_MERGED: &str = "already_merged"; +pub const ERR_NOT_OPEN: &str = "not_open"; +pub const ERR_HEAD_MISSING: &str = "head_missing"; +pub const ERR_BASE_MISSING: &str = "base_missing"; +pub const ERR_MESSAGE_INVALID: &str = "message_invalid"; +pub const ERR_NEEDS_APPROVALS: &str = "needs_approvals"; +pub const ERR_CHANGES_REQUESTED: &str = "changes_requested"; +pub const ERR_NOT_UP_TO_DATE: &str = "not_up_to_date"; +pub const ERR_DRAFT: &str = "draft"; +pub const ERR_NEEDS_CHECKS: &str = "needs_checks"; +pub const ERR_REBASE_CONFLICT: &str = "rebase_conflict"; +pub const ERR_AUTO_MERGE_BLOCKED: &str = "auto_merge_blocked"; +pub const ERR_QUEUE_REQUIRED: &str = "queue_required"; +pub const ERR_QUEUE_ALREADY: &str = "queue_already"; + +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."; +pub const CONFLICTS_MSG: &str = "This branch has conflicts that must be resolved"; +pub const MOVED_MSG: &str = "The base branch moved; reload and try again."; +pub const UP_TO_DATE_MSG: &str = + "Nothing to merge: the head is already contained in the base branch."; +pub const FF_MSG: &str = + "fast-forward not possible: the base branch has commits the head does not contain"; +pub const ALREADY_MERGED_MSG: &str = "This pull request is already merged."; +pub const CLOSED_MSG: &str = "This pull request is closed."; +pub const HEAD_MISSING_MSG: &str = + "The head repository was deleted, so this pull request cannot be merged."; +pub const BASE_MISSING_MSG: &str = "The base branch does not exist."; + +/// What a merge attempt did: the base branch now points at `commit`, or the attempt was refused +/// with an HTTP status and a message for the viewer. +#[derive(Debug, PartialEq, Eq)] +pub enum MergeOutcome { + Merged { commit: String }, + Refused { status: StatusCode, message: String }, +} + +/// The refusal code for a message `perform_merge` returns, if it has one. +pub fn refusal_code(message: &str) -> Option<&'static str> { + Some(match message { + CONFLICTS_MSG => ERR_CONFLICT, + UP_TO_DATE_MSG => ERR_UP_TO_DATE, + FF_MSG => ERR_FF_IMPOSSIBLE, + REBASE_CONFLICT_MSG => ERR_REBASE_CONFLICT, + MOVED_MSG => ERR_BASE_MOVED, + ALREADY_MERGED_MSG => ERR_ALREADY_MERGED, + CLOSED_MSG => ERR_NOT_OPEN, + HEAD_MISSING_MSG => ERR_HEAD_MISSING, + BASE_MISSING_MSG => ERR_BASE_MISSING, + _ => return None, + }) +} + +pub fn refused(status: StatusCode, message: &str) -> MergeOutcome { + MergeOutcome::Refused { + status, + message: message.to_owned(), + } +} + +/// Whether `user` is a reviewer whose approvals and change requests count under merge rules: +/// the repo owner, an instance admin, or a collaborator with Write, Maintain or Admin. +pub fn counts_for_merge_rules(repo: &forge_core::Repo, user: &User, role: Option) -> bool { + user.is_admin + || user.id == repo.owner_id + || matches!(role, Some(Role::Write | Role::Maintain | Role::Admin)) +} + +/// The base branch's merge rule for a pull request, with the facts that rule checks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MergeGate { + pub rule: Protection, + /// Distinct counting reviewers whose latest submitted review is an approval. + pub approvals: u32, + /// Some counting reviewer's latest submitted review requests changes. + pub changes_requested: bool, + /// The head contains the current base tip. Always true when the rule does not require it. + pub up_to_date: bool, + /// The pull request is a draft. + pub draft: bool, + /// Each required check context with its state on the head commit (`None`: not reported). + pub required: Vec, +} + +/// One required status check and where it stands on the pull request head. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RequiredCheck { + pub context: String, + pub state: Option, +} + +impl MergeGate { + /// Every refusal code that currently blocks the merge, in the order they are reported. + pub fn blockers(&self) -> Vec<&'static str> { + let mut out = Vec::new(); + if self.draft { + out.push(ERR_DRAFT); + } + if self.approvals < self.rule.required_approvals { + out.push(ERR_NEEDS_APPROVALS); + } + if self.rule.block_on_changes_requested && self.changes_requested { + out.push(ERR_CHANGES_REQUESTED); + } + if self + .required + .iter() + .any(|check| check.state != Some(StatusState::Success)) + { + out.push(ERR_NEEDS_CHECKS); + } + if self.rule.require_up_to_date && !self.up_to_date { + out.push(ERR_NOT_UP_TO_DATE); + } + out + } + + /// The refusal code for the first rule that blocks the merge, if any. + pub fn blocked(&self) -> Option<&'static str> { + self.blockers().first().copied() + } + + /// Whether waiting could clear every blocker: only missing approvals or checks that are not + /// green yet. Auto-merge may be enabled only then (or when nothing blocks). + pub fn waiting_only(&self) -> bool { + self.blockers() + .iter() + .all(|code| matches!(*code, ERR_NEEDS_APPROVALS | ERR_NEEDS_CHECKS)) + } +} + +/// Evaluates the effective rule for the pull request's base branch. Approvals and change requests +/// count only from `counts_for_merge_rules` reviewers, using each reviewer's latest review; an +/// approval counts only while the head is the commit it was given on. +/// Repo admins are not exempt. A base branch that does not exist counts as up to date; the merge +/// itself reports that. +pub async fn merge_gate( + state: &AppState, + repo: &forge_core::Repo, + pr: &PullRequest, +) -> forge_core::Result { + let rules = state.store.list_branch_rules(&repo.id).await?; + let rule = effective(&rules, &repo.default_branch, &pr.base_branch); + let mut approvals = 0u32; + let mut changes_requested = false; + for (author_id, _, review, commit) in state.store.latest_review_states(&pr.issue.id).await? { + // An approval is of the commits the reviewer saw: a push after it leaves it uncounted + // until they approve again. A change request stands until it is dismissed or replaced. + if review == ReviewState::Approved && commit != pr.head_oid { + continue; + } + let Some(reviewer) = state.store.user_by_id(&author_id).await? else { + continue; + }; + let collaborator = state.store.collaborator_role(&repo.id, &author_id).await?; + let org = state + .store + .org_repo_role(&repo.owner_id, &author_id, &repo.id) + .await?; + let role = forge_core::authz::max_role(collaborator, org); + if !counts_for_merge_rules(repo, &reviewer, role) { + continue; + } + match review { + ReviewState::Approved => approvals = approvals.saturating_add(1), + _ => changes_requested = true, + } + } + let up_to_date = if rule.require_up_to_date { + let base_path = repo_path(&state.git.data_dir, &repo.id)?; + match default_branch_commit(&base_path, &pr.base_branch)? { + Some(tip) => is_ancestor(&state.git, &base_path, &tip, &pr.head_oid).await?, + None => true, + } + } else { + true + }; + let required = if rule.required_checks.is_empty() { + Vec::new() + } else { + let statuses = state.store.statuses_for(&repo.id, &pr.head_oid).await?; + rule.required_checks + .iter() + .map(|context| RequiredCheck { + context: context.clone(), + state: statuses + .iter() + .find(|s| &s.context == context) + .map(|s| s.state), + }) + .collect() + }; + Ok(MergeGate { + rule, + approvals, + changes_requested, + up_to_date, + draft: pr.draft, + required, + }) +} + +/// Merges `pr` into its base branch in `repo` as `viewer`. +/// +/// The base tip is `expected_base` when given, otherwise the current tip of the base branch. The +/// merge is checked and built against that tip, and the ref moves only if it still points there. +/// `message` replaces the default commit message (not used by fast-forward). Refusals that the +/// viewer can act on come back as `MergeOutcome::Refused`; git and database failures are errors. +pub async fn perform_merge( + state: &AppState, + repo: &forge_core::Repo, + pr: &PullRequest, + viewer: &User, + style: MergeStyle, + message: Option<&str>, + expected_base: Option<&str>, +) -> forge_core::Result { + let base_path = repo_path(&state.git.data_dir, &repo.id)?; + let refname = format!("refs/heads/{}", pr.base_branch); + let base_tip = match expected_base { + Some(oid) => oid.to_owned(), + None => match default_branch_commit(&base_path, &pr.base_branch)? { + Some(oid) => oid, + None => { + return Ok(refused(StatusCode::CONFLICT, BASE_MISSING_MSG)); + } + }, + }; + let new = match merge_commit(state, repo, pr, viewer, style, message, &base_tip).await? { + Ok(new) => new, + Err(refusal) => return Ok(refusal), + }; + + match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await { + Ok(()) => {} + Err(forge_git::error::Error::RefMoved(_)) => { + return Ok(refused(StatusCode::CONFLICT, MOVED_MSG)); + } + Err(e) => return Err(e.into()), + } + + finish_merge(state, repo, pr, viewer, &refname, &base_tip, &new).await; + Ok(MergeOutcome::Merged { commit: new }) +} + +/// The commit that merging `pr` into `base_tip` makes in `style`, committed as `committer`. No ref +/// moves. A refusal the caller can act on comes back as the inner `Err`. Fast-forward returns the +/// head itself. +pub async fn merge_commit( + state: &AppState, + repo: &forge_core::Repo, + pr: &PullRequest, + committer: &User, + style: MergeStyle, + message: Option<&str>, + base_tip: &str, +) -> forge_core::Result> { + let base_path = repo_path(&state.git.data_dir, &repo.id)?; + let base_tip = base_tip.to_owned(); + let viewer = committer; + let head = pr.head_oid.as_str(); + let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? { + MergeCheck::Clean { tree } => tree, + MergeCheck::Conflict { .. } => { + return Ok(Err(refused(StatusCode::CONFLICT, CONFLICTS_MSG))); + } + MergeCheck::UpToDate => return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))), + }; + + let now = now_unix(); + let committer = Signature { + name: viewer.username.clone(), + email: contact_email(&state.config.base_url, viewer), + time_unix: now, + }; + let new = match style { + MergeStyle::FastForward => { + if !is_ancestor(&state.git, &base_path, &base_tip, head).await? { + return Ok(Err(refused(StatusCode::CONFLICT, FF_MSG))); + } + head.to_owned() + } + MergeStyle::Rebase => { + match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? { + RebaseResult::Clean { tip, count } if count > 0 => tip, + RebaseResult::Clean { .. } => { + return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))); + } + RebaseResult::Conflict { .. } => { + return Ok(Err(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG))); + } + } + } + MergeStyle::Merge => { + let text = match message { + Some(text) => text.to_owned(), + None => default_merge_message(state, pr).await?, + }; + commit_tree( + &state.git, + &base_path, + &tree, + &[base_tip.as_str(), head], + &text, + &committer, + &committer, + ) + .await? + } + MergeStyle::Squash => { + let author = match state.store.user_by_id(&pr.issue.author_id).await? { + Some(author) => Signature { + name: author.username.clone(), + email: contact_email(&state.config.base_url, &author), + time_unix: now, + }, + None => committer.clone(), + }; + let text = match message { + Some(text) => text.to_owned(), + None => { + let commits = + range_log(&state.git, &base_path, &base_tip, head, MAX_SQUASH_COMMITS) + .await?; + squash_message(pr, &commits) + } + }; + commit_tree( + &state.git, + &base_path, + &tree, + &[base_tip.as_str()], + &text, + &author, + &committer, + ) + .await? + } + }; + Ok(Ok(new)) +} + +/// The work after a merge moved `refname` from `base_tip` to `new`: the pull request is marked +/// merged, its events and notifications go out, and the ref update runs its post-update work. +/// Failures here are logged, not reported: the merge is already in place. +pub async fn finish_merge( + state: &AppState, + repo: &forge_core::Repo, + pr: &PullRequest, + viewer: &User, + refname: &str, + base_tip: &str, + new: &str, +) { + match state.store.mark_merged(&pr.issue.id, &viewer.id, new).await { + Ok(()) => { + let sender = Sender::of(viewer); + emit_item_action(state, repo, &sender, true, pr.issue.number, "merged").await; + notify::dispatch(state, repo, &pr.issue, &viewer.id, Activity::Merged, None).await; + } + Err(e) => { + tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "merge: mark_merged failed"); + } + } + trigger_maintenance(&state.git, &repo.id); + // Boxed: the queue lands through this path, and the post-update work can reach the queue again. + if let Err(e) = Box::pin(after_ref_update( + state, repo, &viewer.id, refname, base_tip, new, + )) + .await + { + tracing::error!(error = %e, repo_id = %repo.id, ref_name = %refname, "merge: post-update failed"); + } +} + +/// The address written into a commit for `user`: their email, or a noreply address on this +/// instance's host when they have none. +pub fn contact_email(base_url: &str, user: &User) -> String { + match user + .email + .as_deref() + .map(str::trim) + .filter(|e| !e.is_empty()) + { + Some(email) => email.to_owned(), + None => format!( + "{}@users.noreply.{}", + user.username, + base_url_host(base_url) + ), + } +} + +pub fn base_url_host(base_url: &str) -> String { + base_url + .parse::() + .ok() + .and_then(|uri| uri.host().map(str::to_owned)) + .unwrap_or_else(|| "localhost".to_owned()) +} + +/// `Merge pull request #N from owner/branch`, a blank line, then the pull request title. +pub async fn default_merge_message( + state: &AppState, + pr: &PullRequest, +) -> forge_core::Result { + let head_owner = match pr.head_repo_id.as_deref() { + Some(id) => state + .store + .repo_by_id(id) + .await? + .map(|head| head.owner_name), + None => None, + }; + let head = match head_owner { + Some(owner) => format!("{owner}/{}", pr.head_branch), + None => pr.head_branch.clone(), + }; + Ok(format!( + "Merge pull request #{} from {head}\n\n{}", + pr.issue.number, pr.issue.title + )) +} + +/// ` (#N)`, a blank line, then one `- <summary>` line per commit, oldest first. +pub fn squash_message(pr: &PullRequest, commits: &[CommitInfo]) -> String { + let mut text = format!("{} (#{})\n\n", pr.issue.title, pr.issue.number); + for commit in commits { + text.push_str("- "); + text.push_str(&commit.summary); + text.push('\n'); + } + text +} diff --git a/crates/forge-web/src/merge_queue.rs b/crates/forge-web/src/merge_queue.rs index 2a40d96..520b8d9 100644 --- a/crates/forge-web/src/merge_queue.rs +++ b/crates/forge-web/src/merge_queue.rs @@ -21,11 +21,11 @@ use forge_git::pulls::{set_ref, update_ref_cas}; use forge_git::repo::repo_path; use crate::ci::schedule::merge_queue_run; -use crate::notify::{self, Activity}; -use crate::pages::pulls_merge::{ +use crate::merge::{ ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, MergeOutcome, finish_merge, merge_commit, merge_gate, }; +use crate::notify::{self, Activity}; use crate::state::AppState; /// Whether the protection of `branch` routes merges through the queue. Direct merges are refused diff --git a/crates/forge-web/src/oci/mod.rs b/crates/forge-web/src/oci/mod.rs index 49ba38b..36a6d93 100644 --- a/crates/forge-web/src/oci/mod.rs +++ b/crates/forge-web/src/oci/mod.rs @@ -6,7 +6,7 @@ //! in the blob store, shared by digest ([`blobs`]). Manifests and tags live in the database //! ([`manifests`]). Unreferenced blobs are removed by a mark and sweep after deletes ([`gc`]). //! Credentials come through `GET /v2/token` ([`auth`]); the Packages tab and the package page show -//! the images ([`crate::pages::packages`]). +//! the images (the `packages` page). //! //! The `/v2/` path must reach the forge unchanged, with a large body limit and no request //! buffering, since layers are big. docs/packages.md says how a proxy is set up. diff --git a/crates/forge-web/src/pages/blob.rs b/crates/forge-web/src/pages/blob.rs index 0c6b6c1..41075db 100644 --- a/crates/forge-web/src/pages/blob.rs +++ b/crates/forge-web/src/pages/blob.rs @@ -18,7 +18,6 @@ use crate::lfs::has_object; use crate::lfs_pointer; use crate::pages::code_live::{follows_branch, live_url}; use crate::pages::finder::file_finder; -use crate::pages::media::media_url; use crate::pages::refs::{load_refs, ref_links}; use crate::pages::repo::repo_head; 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 use crate::pages::tree::{ entry_rows, last_commits, latest_bar, link_context, read_dir, read_file, resolve, tree_table, }; +use crate::raw::media::media_url; use crate::raw::raw_url; use crate::render::highlight::highlight_lines; use crate::render::markdown::render_markdown; diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index a40b912..a350f9d 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -32,6 +32,7 @@ use topcoat::router::{HeaderValue, page, path_param, route}; use topcoat::view::{View, component, view}; use crate::auth::{current_user, require_csrf}; +use crate::ci::after_change; use crate::ci::log_path; use crate::i18n::timeline::{self as tl, K as TK}; use crate::i18n::{ @@ -330,35 +331,6 @@ async fn run_of(state: &AppState, ctx: &RepoCtx, number: &str) -> Result<CiRun> } } -/// Wakes the job queue and syncs the commit status of every job whose state changed since `before`. -/// A job missing from `before` (a fresh run) counts as changed. -pub(crate) async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Result<()> { - state.ci_waker.notify_waiters(); - let Some(run) = state.store.run_by_id(run_id).await? else { - return Ok(()); - }; - state.ci_live.bump_run(run_id); - state.ci_live.bump_repo(&run.repo_id); - for job in state.store.jobs_for_run(run_id).await? { - // A cancel request on a running job changes no state, but its row shows "stopping". - let changed = before - .iter() - .find(|old| old.id == job.id) - .is_none_or(|old| { - old.state != job.state || old.cancel_requested != job.cancel_requested - }); - if changed { - if job.state.is_terminal() { - state.ci_live.close_job(&job.id); - } else { - state.ci_live.bump_job(&job.id); - } - crate::ci::sync_status(state, &run, &job).await; - } - } - Ok(()) -} - /// A job name as the timeline's label column can hold it: a matrix combination shows its values /// without the base name (the job list below groups them), and a long name is cut with an ellipsis. fn gantt_name(name: &str) -> String { diff --git a/crates/forge-web/src/pages/merge_queue.rs b/crates/forge-web/src/pages/merge_queue.rs index 8c3c686..db3e1f0 100644 --- a/crates/forge-web/src/pages/merge_queue.rs +++ b/crates/forge-web/src/pages/merge_queue.rs @@ -29,9 +29,9 @@ use crate::auth::require_csrf; use crate::i18n::merge_queue::{self as g, K}; use crate::i18n::{self, Lang}; use crate::live::{changed_event, events_response}; +use crate::merge::ERR_NOT_OPEN; use crate::merge_queue as queue; use crate::pages::issue_parts::parse_number; -use crate::pages::pulls_merge::ERR_NOT_OPEN; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::state::AppState; diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 573f123..eac7981 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -68,7 +68,6 @@ pub mod issues_live; pub mod labels_css; pub mod labels_page; pub mod login; -pub mod media; pub mod merge_queue; pub mod milestones_page; pub mod needs_you; @@ -141,7 +140,6 @@ pub mod settings_sessions; pub mod settings_tokens; pub mod setup; pub mod shell_events; -pub mod snippet_raw; pub mod snippets; pub mod snippets_live; pub mod star; diff --git a/crates/forge-web/src/pages/pull_flow.rs b/crates/forge-web/src/pages/pull_flow.rs index 027b067..0f306a6 100644 --- a/crates/forge-web/src/pages/pull_flow.rs +++ b/crates/forge-web/src/pages/pull_flow.rs @@ -20,9 +20,9 @@ use topcoat::router::response::Response; use topcoat::router::{path_param, route}; use crate::auth::require_csrf; +use crate::merge::{ERR_AUTO_MERGE_BLOCKED, merge_gate}; use crate::notify::{self, Activity}; use crate::pages::issue_parts::parse_number; -use crate::pages::pulls_merge::{ERR_AUTO_MERGE_BLOCKED, merge_gate}; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::state::AppState; use crate::views::repo_href; diff --git a/crates/forge-web/src/pages/pull_reviews.rs b/crates/forge-web/src/pages/pull_reviews.rs index 1ebf3de..267dc7e 100644 --- a/crates/forge-web/src/pages/pull_reviews.rs +++ b/crates/forge-web/src/pages/pull_reviews.rs @@ -31,9 +31,9 @@ use crate::auth::require_user; use crate::i18n::pulls_review::{self as g, K}; use crate::i18n::{self, Lang}; use crate::internal::{may_push_directly, trigger_maintenance}; +use crate::merge::contact_email; use crate::notify::{self, Activity}; use crate::pages::issue_parts::{check_write, csrf_of, may_change, may_converse, parse_number}; -use crate::pages::pulls_merge::contact_email; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::post_update::after_ref_update; diff --git a/crates/forge-web/src/pages/pull_view.rs b/crates/forge-web/src/pages/pull_view.rs index 9377259..f88257b 100644 --- a/crates/forge-web/src/pages/pull_view.rs +++ b/crates/forge-web/src/pages/pull_view.rs @@ -22,6 +22,13 @@ use topcoat::view::{Child, View, component, view}; use crate::auth::require_user; use crate::i18n::pulls_review::{self as g, K}; use crate::i18n::{self, Lang}; +use crate::merge::{ + ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED, + ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING, + ERR_HEAD_MOVED, ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, + ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, + merge_gate, +}; use crate::pages::commits::{CommitRow, now_secs}; use crate::pages::issue_meta::item_href; use crate::pages::issue_parts::{ @@ -32,13 +39,6 @@ use crate::pages::issue_parts::{ use crate::pages::notifications::notify_box_for; use crate::pages::pull_branch::{self, branch_box, branch_error_from}; use crate::pages::pull_reviews::error_text_in; -use crate::pages::pulls_merge::{ - ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED, - ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING, - ERR_HEAD_MOVED, ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, - ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, - merge_gate, -}; use crate::pages::repo_ctx::{RepoCtx, load_repo}; use crate::pages::review_requests::{load_reviewers, reviewers_box}; use crate::state::AppState; diff --git a/crates/forge-web/src/pages/pulls_merge.rs b/crates/forge-web/src/pages/pulls_merge.rs index c7e5c42..0091980 100644 --- a/crates/forge-web/src/pages/pulls_merge.rs +++ b/crates/forge-web/src/pages/pulls_merge.rs @@ -12,15 +12,7 @@ //! does not run for it. After the ref moves, the pull request is marked merged and the same //! post-update work a push gets runs (closing keywords, maintenance, mergeability of other pulls). -use forge_core::protection::{Protection, effective}; -use forge_core::store::commit_status::StatusState; -use forge_core::{Action, IssueState, MergeStyle, PullRequest, ReviewState, Role, User, authorize}; -use forge_git::browse::{CommitInfo, default_branch_commit}; -use forge_git::pulls::{ - MergeCheck, RebaseResult, Signature, check_merge, commit_tree, is_ancestor, range_log, - rebase_commits, update_ref_cas, -}; -use forge_git::repo::repo_path; +use forge_core::{Action, IssueState, MergeStyle, authorize}; use http::HeaderValue; use http::header::CONTENT_TYPE; use serde::Deserialize; @@ -32,14 +24,11 @@ use topcoat::router::response::Response; use topcoat::router::{Body, StatusCode, path_param, route}; use crate::auth::require_csrf; -use crate::internal::trigger_maintenance; -use crate::notify::{self, Activity}; +use crate::merge::*; use crate::pages::issue_parts::parse_number; use crate::pages::repo_ctx::load_repo; -use crate::post_update::after_ref_update; use crate::state::AppState; -use crate::views::{now_unix, repo_href}; -use crate::webhooks::emit::{Sender, emit_item_action}; +use crate::views::repo_href; path_param!(owner); path_param!(repo); @@ -47,43 +36,6 @@ path_param!(number); /// Largest accepted merge message, in bytes. const MAX_MESSAGE_BYTES: usize = 64 * 1024; -/// Commits listed in a squash message. -const MAX_SQUASH_COMMITS: usize = 250; - -/// Refusal codes, sent as `?merge_error=<code>` on the pull request page. The page owns the -/// wording for each code; a code outside this set is never echoed back. -pub const ERR_CONFLICT: &str = "conflict"; -pub const ERR_UP_TO_DATE: &str = "up_to_date"; -pub const ERR_FF_IMPOSSIBLE: &str = "ff_impossible"; -pub const ERR_BASE_MOVED: &str = "base_moved"; -pub const ERR_HEAD_MOVED: &str = "head_moved"; -pub const ERR_ALREADY_MERGED: &str = "already_merged"; -pub const ERR_NOT_OPEN: &str = "not_open"; -pub const ERR_HEAD_MISSING: &str = "head_missing"; -pub const ERR_BASE_MISSING: &str = "base_missing"; -pub const ERR_MESSAGE_INVALID: &str = "message_invalid"; -pub const ERR_NEEDS_APPROVALS: &str = "needs_approvals"; -pub const ERR_CHANGES_REQUESTED: &str = "changes_requested"; -pub const ERR_NOT_UP_TO_DATE: &str = "not_up_to_date"; -pub const ERR_DRAFT: &str = "draft"; -pub const ERR_NEEDS_CHECKS: &str = "needs_checks"; -pub const ERR_REBASE_CONFLICT: &str = "rebase_conflict"; -pub const ERR_AUTO_MERGE_BLOCKED: &str = "auto_merge_blocked"; -pub const ERR_QUEUE_REQUIRED: &str = "queue_required"; -pub const ERR_QUEUE_ALREADY: &str = "queue_already"; - -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."; -const CONFLICTS_MSG: &str = "This branch has conflicts that must be resolved"; -const MOVED_MSG: &str = "The base branch moved; reload and try again."; -const UP_TO_DATE_MSG: &str = "Nothing to merge: the head is already contained in the base branch."; -const FF_MSG: &str = - "fast-forward not possible: the base branch has commits the head does not contain"; -const ALREADY_MERGED_MSG: &str = "This pull request is already merged."; -const CLOSED_MSG: &str = "This pull request is closed."; -const HEAD_MISSING_MSG: &str = - "The head repository was deleted, so this pull request cannot be merged."; -const BASE_MISSING_MSG: &str = "The base branch does not exist."; - #[derive(Deserialize)] struct MergeForm { #[serde(default)] @@ -100,14 +52,6 @@ struct MergeForm { head: String, } -/// What a merge attempt did: the base branch now points at `commit`, or the attempt was refused -/// with an HTTP status and a message for the viewer. -#[derive(Debug, PartialEq, Eq)] -pub enum MergeOutcome { - Merged { commit: String }, - Refused { status: StatusCode, message: String }, -} - #[route(POST "/{owner}/{repo}/pulls/{number}/merge")] async fn merge_post(cx: &Cx, Form(form): Form<MergeForm>) -> Result<Response> { let number = parse_number(number(cx))?; @@ -189,22 +133,6 @@ fn back_to_pull(pull_href: &str, code: &str) -> Result<Response> { Err(see_other(format!("{pull_href}?merge_error={code}")).into()) } -/// The refusal code for a message `perform_merge` returns, if it has one. -fn refusal_code(message: &str) -> Option<&'static str> { - Some(match message { - CONFLICTS_MSG => ERR_CONFLICT, - UP_TO_DATE_MSG => ERR_UP_TO_DATE, - FF_MSG => ERR_FF_IMPOSSIBLE, - REBASE_CONFLICT_MSG => ERR_REBASE_CONFLICT, - MOVED_MSG => ERR_BASE_MOVED, - ALREADY_MERGED_MSG => ERR_ALREADY_MERGED, - CLOSED_MSG => ERR_NOT_OPEN, - HEAD_MISSING_MSG => ERR_HEAD_MISSING, - BASE_MISSING_MSG => ERR_BASE_MISSING, - _ => return None, - }) -} - /// A blank message means "use the default". Otherwise CRLF becomes LF. A message over 64 KiB or /// with a NUL byte is rejected with the reason. fn clean_message(raw: &str) -> std::result::Result<Option<String>, &'static str> { @@ -231,385 +159,6 @@ fn refusal(status: StatusCode, message: &str) -> Response { response } -fn refused(status: StatusCode, message: &str) -> MergeOutcome { - MergeOutcome::Refused { - status, - message: message.to_owned(), - } -} - -/// Whether `user` is a reviewer whose approvals and change requests count under merge rules: -/// the repo owner, an instance admin, or a collaborator with Write, Maintain or Admin. -pub fn counts_for_merge_rules(repo: &forge_core::Repo, user: &User, role: Option<Role>) -> bool { - user.is_admin - || user.id == repo.owner_id - || matches!(role, Some(Role::Write | Role::Maintain | Role::Admin)) -} - -/// The base branch's merge rule for a pull request, with the facts that rule checks. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MergeGate { - pub rule: Protection, - /// Distinct counting reviewers whose latest submitted review is an approval. - pub approvals: u32, - /// Some counting reviewer's latest submitted review requests changes. - pub changes_requested: bool, - /// The head contains the current base tip. Always true when the rule does not require it. - pub up_to_date: bool, - /// The pull request is a draft. - pub draft: bool, - /// Each required check context with its state on the head commit (`None`: not reported). - pub required: Vec<RequiredCheck>, -} - -/// One required status check and where it stands on the pull request head. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RequiredCheck { - pub context: String, - pub state: Option<StatusState>, -} - -impl MergeGate { - /// Every refusal code that currently blocks the merge, in the order they are reported. - pub fn blockers(&self) -> Vec<&'static str> { - let mut out = Vec::new(); - if self.draft { - out.push(ERR_DRAFT); - } - if self.approvals < self.rule.required_approvals { - out.push(ERR_NEEDS_APPROVALS); - } - if self.rule.block_on_changes_requested && self.changes_requested { - out.push(ERR_CHANGES_REQUESTED); - } - if self - .required - .iter() - .any(|check| check.state != Some(StatusState::Success)) - { - out.push(ERR_NEEDS_CHECKS); - } - if self.rule.require_up_to_date && !self.up_to_date { - out.push(ERR_NOT_UP_TO_DATE); - } - out - } - - /// The refusal code for the first rule that blocks the merge, if any. - pub fn blocked(&self) -> Option<&'static str> { - self.blockers().first().copied() - } - - /// Whether waiting could clear every blocker: only missing approvals or checks that are not - /// green yet. Auto-merge may be enabled only then (or when nothing blocks). - pub fn waiting_only(&self) -> bool { - self.blockers() - .iter() - .all(|code| matches!(*code, ERR_NEEDS_APPROVALS | ERR_NEEDS_CHECKS)) - } -} - -/// Evaluates the effective rule for the pull request's base branch. Approvals and change requests -/// count only from `counts_for_merge_rules` reviewers, using each reviewer's latest review; an -/// approval counts only while the head is the commit it was given on. -/// Repo admins are not exempt. A base branch that does not exist counts as up to date; the merge -/// itself reports that. -pub async fn merge_gate( - state: &AppState, - repo: &forge_core::Repo, - pr: &PullRequest, -) -> forge_core::Result<MergeGate> { - let rules = state.store.list_branch_rules(&repo.id).await?; - let rule = effective(&rules, &repo.default_branch, &pr.base_branch); - let mut approvals = 0u32; - let mut changes_requested = false; - for (author_id, _, review, commit) in state.store.latest_review_states(&pr.issue.id).await? { - // An approval is of the commits the reviewer saw: a push after it leaves it uncounted - // until they approve again. A change request stands until it is dismissed or replaced. - if review == ReviewState::Approved && commit != pr.head_oid { - continue; - } - let Some(reviewer) = state.store.user_by_id(&author_id).await? else { - continue; - }; - let collaborator = state.store.collaborator_role(&repo.id, &author_id).await?; - let org = state - .store - .org_repo_role(&repo.owner_id, &author_id, &repo.id) - .await?; - let role = forge_core::authz::max_role(collaborator, org); - if !counts_for_merge_rules(repo, &reviewer, role) { - continue; - } - match review { - ReviewState::Approved => approvals = approvals.saturating_add(1), - _ => changes_requested = true, - } - } - let up_to_date = if rule.require_up_to_date { - let base_path = repo_path(&state.git.data_dir, &repo.id)?; - match default_branch_commit(&base_path, &pr.base_branch)? { - Some(tip) => is_ancestor(&state.git, &base_path, &tip, &pr.head_oid).await?, - None => true, - } - } else { - true - }; - let required = if rule.required_checks.is_empty() { - Vec::new() - } else { - let statuses = state.store.statuses_for(&repo.id, &pr.head_oid).await?; - rule.required_checks - .iter() - .map(|context| RequiredCheck { - context: context.clone(), - state: statuses - .iter() - .find(|s| &s.context == context) - .map(|s| s.state), - }) - .collect() - }; - Ok(MergeGate { - rule, - approvals, - changes_requested, - up_to_date, - draft: pr.draft, - required, - }) -} - -/// Merges `pr` into its base branch in `repo` as `viewer`. -/// -/// The base tip is `expected_base` when given, otherwise the current tip of the base branch. The -/// merge is checked and built against that tip, and the ref moves only if it still points there. -/// `message` replaces the default commit message (not used by fast-forward). Refusals that the -/// viewer can act on come back as `MergeOutcome::Refused`; git and database failures are errors. -pub async fn perform_merge( - state: &AppState, - repo: &forge_core::Repo, - pr: &PullRequest, - viewer: &User, - style: MergeStyle, - message: Option<&str>, - expected_base: Option<&str>, -) -> forge_core::Result<MergeOutcome> { - let base_path = repo_path(&state.git.data_dir, &repo.id)?; - let refname = format!("refs/heads/{}", pr.base_branch); - let base_tip = match expected_base { - Some(oid) => oid.to_owned(), - None => match default_branch_commit(&base_path, &pr.base_branch)? { - Some(oid) => oid, - None => { - return Ok(refused(StatusCode::CONFLICT, BASE_MISSING_MSG)); - } - }, - }; - let new = match merge_commit(state, repo, pr, viewer, style, message, &base_tip).await? { - Ok(new) => new, - Err(refusal) => return Ok(refusal), - }; - - match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await { - Ok(()) => {} - Err(forge_git::error::Error::RefMoved(_)) => { - return Ok(refused(StatusCode::CONFLICT, MOVED_MSG)); - } - Err(e) => return Err(e.into()), - } - - finish_merge(state, repo, pr, viewer, &refname, &base_tip, &new).await; - Ok(MergeOutcome::Merged { commit: new }) -} - -/// The commit that merging `pr` into `base_tip` makes in `style`, committed as `committer`. No ref -/// moves. A refusal the caller can act on comes back as the inner `Err`. Fast-forward returns the -/// head itself. -pub async fn merge_commit( - state: &AppState, - repo: &forge_core::Repo, - pr: &PullRequest, - committer: &User, - style: MergeStyle, - message: Option<&str>, - base_tip: &str, -) -> forge_core::Result<std::result::Result<String, MergeOutcome>> { - let base_path = repo_path(&state.git.data_dir, &repo.id)?; - let base_tip = base_tip.to_owned(); - let viewer = committer; - let head = pr.head_oid.as_str(); - let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? { - MergeCheck::Clean { tree } => tree, - MergeCheck::Conflict { .. } => { - return Ok(Err(refused(StatusCode::CONFLICT, CONFLICTS_MSG))); - } - MergeCheck::UpToDate => return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))), - }; - - let now = now_unix(); - let committer = Signature { - name: viewer.username.clone(), - email: contact_email(&state.config.base_url, viewer), - time_unix: now, - }; - let new = match style { - MergeStyle::FastForward => { - if !is_ancestor(&state.git, &base_path, &base_tip, head).await? { - return Ok(Err(refused(StatusCode::CONFLICT, FF_MSG))); - } - head.to_owned() - } - MergeStyle::Rebase => { - match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? { - RebaseResult::Clean { tip, count } if count > 0 => tip, - RebaseResult::Clean { .. } => { - return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))); - } - RebaseResult::Conflict { .. } => { - return Ok(Err(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG))); - } - } - } - MergeStyle::Merge => { - let text = match message { - Some(text) => text.to_owned(), - None => default_merge_message(state, pr).await?, - }; - commit_tree( - &state.git, - &base_path, - &tree, - &[base_tip.as_str(), head], - &text, - &committer, - &committer, - ) - .await? - } - MergeStyle::Squash => { - let author = match state.store.user_by_id(&pr.issue.author_id).await? { - Some(author) => Signature { - name: author.username.clone(), - email: contact_email(&state.config.base_url, &author), - time_unix: now, - }, - None => committer.clone(), - }; - let text = match message { - Some(text) => text.to_owned(), - None => { - let commits = - range_log(&state.git, &base_path, &base_tip, head, MAX_SQUASH_COMMITS) - .await?; - squash_message(pr, &commits) - } - }; - commit_tree( - &state.git, - &base_path, - &tree, - &[base_tip.as_str()], - &text, - &author, - &committer, - ) - .await? - } - }; - Ok(Ok(new)) -} - -/// The work after a merge moved `refname` from `base_tip` to `new`: the pull request is marked -/// merged, its events and notifications go out, and the ref update runs its post-update work. -/// Failures here are logged, not reported: the merge is already in place. -pub async fn finish_merge( - state: &AppState, - repo: &forge_core::Repo, - pr: &PullRequest, - viewer: &User, - refname: &str, - base_tip: &str, - new: &str, -) { - match state.store.mark_merged(&pr.issue.id, &viewer.id, new).await { - Ok(()) => { - let sender = Sender::of(viewer); - emit_item_action(state, repo, &sender, true, pr.issue.number, "merged").await; - notify::dispatch(state, repo, &pr.issue, &viewer.id, Activity::Merged, None).await; - } - Err(e) => { - tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "merge: mark_merged failed"); - } - } - trigger_maintenance(&state.git, &repo.id); - // Boxed: the queue lands through this path, and the post-update work can reach the queue again. - if let Err(e) = Box::pin(after_ref_update( - state, repo, &viewer.id, refname, base_tip, new, - )) - .await - { - tracing::error!(error = %e, repo_id = %repo.id, ref_name = %refname, "merge: post-update failed"); - } -} - -/// The address written into a commit for `user`: their email, or a noreply address on this -/// instance's host when they have none. -pub(crate) fn contact_email(base_url: &str, user: &User) -> String { - match user - .email - .as_deref() - .map(str::trim) - .filter(|e| !e.is_empty()) - { - Some(email) => email.to_owned(), - None => format!( - "{}@users.noreply.{}", - user.username, - base_url_host(base_url) - ), - } -} - -fn base_url_host(base_url: &str) -> String { - base_url - .parse::<http::Uri>() - .ok() - .and_then(|uri| uri.host().map(str::to_owned)) - .unwrap_or_else(|| "localhost".to_owned()) -} - -/// `Merge pull request #N from owner/branch`, a blank line, then the pull request title. -async fn default_merge_message(state: &AppState, pr: &PullRequest) -> forge_core::Result<String> { - let head_owner = match pr.head_repo_id.as_deref() { - Some(id) => state - .store - .repo_by_id(id) - .await? - .map(|head| head.owner_name), - None => None, - }; - let head = match head_owner { - Some(owner) => format!("{owner}/{}", pr.head_branch), - None => pr.head_branch.clone(), - }; - Ok(format!( - "Merge pull request #{} from {head}\n\n{}", - pr.issue.number, pr.issue.title - )) -} - -/// `<title> (#N)`, a blank line, then one `- <summary>` line per commit, oldest first. -fn squash_message(pr: &PullRequest, commits: &[CommitInfo]) -> String { - let mut text = format!("{} (#{})\n\n", pr.issue.title, pr.issue.number); - for commit in commits { - text.push_str("- "); - text.push_str(&commit.summary); - text.push('\n'); - } - text -} - #[cfg(test)] mod tests { use std::path::{Path, PathBuf}; diff --git a/crates/forge-web/src/pages/snippets.rs b/crates/forge-web/src/pages/snippets.rs index 6ce6036..69d9d45 100644 --- a/crates/forge-web/src/pages/snippets.rs +++ b/crates/forge-web/src/pages/snippets.rs @@ -22,8 +22,8 @@ use crate::audit::{self, Actor, Target}; use crate::auth::{current_user, require_csrf, require_user}; use crate::i18n::community::{self as g, K}; use crate::i18n::{self, Lang}; -use crate::pages::snippet_raw::snippet_raw_url; use crate::pages::snippets_live::{bump_snippet, item_live_url, list_live_url}; +use crate::raw::snippet_raw::snippet_raw_url; use crate::render::highlight::highlight_lines; use crate::render::markdown::render_markdown; use crate::state::AppState; diff --git a/crates/forge-web/src/pages/media.rs b/crates/forge-web/src/raw/media.rs similarity index 100% rename from crates/forge-web/src/pages/media.rs rename to crates/forge-web/src/raw/media.rs diff --git a/crates/forge-web/src/raw.rs b/crates/forge-web/src/raw/mod.rs similarity index 99% rename from crates/forge-web/src/raw.rs rename to crates/forge-web/src/raw/mod.rs index 493596e..6d54d02 100644 --- a/crates/forge-web/src/raw.rs +++ b/crates/forge-web/src/raw/mod.rs @@ -1,6 +1,9 @@ //! Raw user-content origin (separate listener, explicit routes; never `.discover()`). //! See docs/architecture.md, section 5.5. +pub mod media; +pub mod snippet_raw; + use std::path::Path; use std::process::Stdio; use std::time::{SystemTime, UNIX_EPOCH}; @@ -103,13 +106,13 @@ pub fn router(state: AppState) -> Router { .route(RouteFn::new( vec![Method::GET, Method::HEAD], "/{owner}/{repo}/-/media/{*rest}", - crate::pages::media::media_file, + crate::raw::media::media_file, )) // Snippet files sit under the same reserved `-` segment: `/-/snippets/{id}/{file}`. .route(RouteFn::new( vec![Method::GET, Method::HEAD], "/-/snippets/{id}/{*rest}", - crate::pages::snippet_raw::snippet_file, + crate::raw::snippet_raw::snippet_file, )) .route(RouteFn::new(Method::GET, "/healthz", healthz)) // Responses must match the bytes behind the ETag and Content-Length. diff --git a/crates/forge-web/src/pages/snippet_raw.rs b/crates/forge-web/src/raw/snippet_raw.rs similarity index 100% rename from crates/forge-web/src/pages/snippet_raw.rs rename to crates/forge-web/src/raw/snippet_raw.rs