From 4791c8ae5cde35017045b6d46e37a2203bfd2e5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 20 Oct 2026 09:21:42 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20draft=20PRs,=20rebase=20mer?= =?UTF-8?q?ge,=20required=20checks=20and=20auto-merge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migrations/0052_pull_draft_automerge.sql | 8 + .../migrations/0053_required_checks.sql | 4 + crates/forge-core/src/issues.rs | 3 + crates/forge-core/src/protection.rs | 67 ++- crates/forge-core/src/pulls.rs | 17 +- crates/forge-core/src/store/commit_status.rs | 14 + crates/forge-core/src/store/issues.rs | 13 + crates/forge-core/src/store/migrate.rs | 8 + crates/forge-core/src/store/mod.rs | 105 ++++- crates/forge-core/src/store/pulls.rs | 318 +++++++++++++- .../forge-core/src/store/pulls_list_extra.rs | 19 + crates/forge-git/src/pulls.rs | 195 +++++++++ crates/forge-web/assets/nav.js | 14 + crates/forge-web/src/api/statuses.rs | 1 + crates/forge-web/src/automerge.rs | 105 +++++ crates/forge-web/src/ci/mod.rs | 2 + crates/forge-web/src/i18n/issues.rs | 44 ++ crates/forge-web/src/i18n/pulls.rs | 24 + crates/forge-web/src/i18n/pulls_review.rs | 91 ++++ crates/forge-web/src/i18n/repo_admin.rs | 24 + crates/forge-web/src/main.rs | 1 + crates/forge-web/src/pages/compare.rs | 43 +- crates/forge-web/src/pages/issue_parts.rs | 4 + crates/forge-web/src/pages/issues_list.rs | 38 +- crates/forge-web/src/pages/mod.rs | 1 + crates/forge-web/src/pages/pull_flow.rs | 165 +++++++ crates/forge-web/src/pages/pull_reviews.rs | 1 + crates/forge-web/src/pages/pull_view.rs | 156 ++++++- crates/forge-web/src/pages/pulls_list.rs | 24 +- crates/forge-web/src/pages/pulls_merge.rs | 409 +++++++++++++++++- crates/forge-web/src/pages/repo_settings.rs | 52 ++- crates/forge-web/src/pulls_sync.rs | 12 + crates/forge-web/src/webhooks/payload.rs | 3 + style/main.scss | 112 +++++ 34 files changed, 2053 insertions(+), 44 deletions(-) create mode 100644 crates/forge-core/migrations/0052_pull_draft_automerge.sql create mode 100644 crates/forge-core/migrations/0053_required_checks.sql create mode 100644 crates/forge-web/src/automerge.rs create mode 100644 crates/forge-web/src/pages/pull_flow.rs diff --git a/crates/forge-core/migrations/0052_pull_draft_automerge.sql b/crates/forge-core/migrations/0052_pull_draft_automerge.sql new file mode 100644 index 0000000..95183fa --- /dev/null +++ b/crates/forge-core/migrations/0052_pull_draft_automerge.sql @@ -0,0 +1,8 @@ +-- Draft pull requests and auto-merge. Applied by store/migrate.rs. +-- draft: a draft cannot be merged and does not notify reviewers until marked ready. +-- auto_merge_style / auto_merge_user: set while auto-merge is enabled; the merge runs as that +-- user with that style once the merge gate passes. Cleared on merge, on disable and on a new push. + +ALTER TABLE pull_requests ADD COLUMN draft INTEGER NOT NULL DEFAULT 0; +ALTER TABLE pull_requests ADD COLUMN auto_merge_style TEXT NULL; +ALTER TABLE pull_requests ADD COLUMN auto_merge_user TEXT NULL REFERENCES users(id); diff --git a/crates/forge-core/migrations/0053_required_checks.sql b/crates/forge-core/migrations/0053_required_checks.sql new file mode 100644 index 0000000..cf94e86 --- /dev/null +++ b/crates/forge-core/migrations/0053_required_checks.sql @@ -0,0 +1,4 @@ +-- Required status checks on branch protections. Applied by store/migrate.rs. +-- A JSON array of commit status contexts that must all be success on a pull request head. + +ALTER TABLE branch_protections ADD COLUMN required_checks TEXT NOT NULL DEFAULT '[]'; diff --git a/crates/forge-core/src/issues.rs b/crates/forge-core/src/issues.rs index d93a528..cf237a5 100644 --- a/crates/forge-core/src/issues.rs +++ b/crates/forge-core/src/issues.rs @@ -152,6 +152,8 @@ pub struct IssueFilter { pub assignee: Option, /// Substring of the title, case-insensitive. pub query: Option, + /// Pull requests only: `Some(true)` lists drafts, `Some(false)` lists ready pull requests. + pub draft: Option, pub sort: IssueSort, /// 1-based. pub page: u32, @@ -167,6 +169,7 @@ impl Default for IssueFilter { author: None, assignee: None, query: None, + draft: None, sort: IssueSort::Newest, page: 1, per_page: 25, diff --git a/crates/forge-core/src/protection.rs b/crates/forge-core/src/protection.rs index fa15045..f28e28d 100644 --- a/crates/forge-core/src/protection.rs +++ b/crates/forge-core/src/protection.rs @@ -23,11 +23,14 @@ pub struct BranchRule { /// Direct pushes to the branch are rejected for everyone but repo admins. Merges through /// pull requests are unaffected. pub restrict_push: bool, + /// Commit status contexts (CI job names such as `ci/test`, or any reported context) that must + /// all be `success` on the pull request head before it can merge. + pub required_checks: Vec, pub created_at: String, } /// The settings a rule saves, without its identity. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RuleFlags { pub allow_force_push: bool, pub allow_deletion: bool, @@ -35,6 +38,7 @@ pub struct RuleFlags { pub block_on_changes_requested: bool, pub require_up_to_date: bool, pub restrict_push: bool, + pub required_checks: Vec, } impl RuleFlags { @@ -49,7 +53,7 @@ impl RuleFlags { } /// The settings that apply to one branch. `Default` is the unprotected branch. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Protection { pub allow_force_push: bool, pub allow_deletion: bool, @@ -57,6 +61,7 @@ pub struct Protection { pub block_on_changes_requested: bool, pub require_up_to_date: bool, pub restrict_push: bool, + pub required_checks: Vec, } /// Rejects `required_approvals` above `MAX_REQUIRED_APPROVALS`. @@ -69,6 +74,34 @@ pub fn validate_required_approvals(n: u32) -> Result<()> { Ok(()) } +/// Most required check contexts on one rule. +pub const MAX_REQUIRED_CHECKS: usize = 50; +/// Longest accepted check context, in bytes. +pub const MAX_CHECK_CONTEXT_BYTES: usize = 200; + +/// Trims, drops blanks and duplicates (keeping first-seen order) and validates the contexts. +pub fn normalize_required_checks(raw: &[String]) -> Result> { + let mut out: Vec = Vec::new(); + for item in raw { + let item = item.trim(); + if item.is_empty() || out.iter().any(|c| c == item) { + continue; + } + if item.len() > MAX_CHECK_CONTEXT_BYTES || item.chars().any(char::is_control) { + return Err(Error::Invalid(format!( + "a required check is longer than {MAX_CHECK_CONTEXT_BYTES} bytes or has control characters" + ))); + } + out.push(item.to_owned()); + } + if out.len() > MAX_REQUIRED_CHECKS { + return Err(Error::Invalid(format!( + "at most {MAX_REQUIRED_CHECKS} required checks per rule" + ))); + } + Ok(out) +} + /// Pattern syntax: a literal branch name, `*` matches any run of chars except `/`, `**` matches anything /// including `/`. Max 200 bytes, it must be a valid branch name otherwise (no `..`, no leading `-`, no /// control or space chars, no `~^:?[\`). The pattern must not include the `refs/heads/` prefix. @@ -202,6 +235,7 @@ pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Pr block_on_changes_requested: rule.block_on_changes_requested, require_up_to_date: rule.require_up_to_date, restrict_push: rule.restrict_push, + required_checks: rule.required_checks.clone(), }; } if branch == default_branch { @@ -234,6 +268,7 @@ mod tests { block_on_changes_requested: false, require_up_to_date: false, restrict_push: false, + required_checks: Vec::new(), created_at: created.into(), } } @@ -346,6 +381,7 @@ mod tests { block_on_changes_requested: true, require_up_to_date: true, restrict_push: true, + required_checks: Vec::new(), } ); // Unprotected and built-in default branches carry no merge rules. @@ -370,4 +406,31 @@ mod tests { ); } } + + #[test] + fn normalize_required_checks_trims_dedupes_and_validates() { + let raw = vec![ + " ci/test ".to_owned(), + String::new(), + "lint".to_owned(), + "ci/test".to_owned(), + ]; + assert_eq!( + normalize_required_checks(&raw).unwrap(), + ["ci/test", "lint"] + ); + assert!(normalize_required_checks(&["a\tb".to_owned()]).is_err()); + assert!(normalize_required_checks(&["x".repeat(MAX_CHECK_CONTEXT_BYTES + 1)]).is_err()); + let many: Vec = (0..=MAX_REQUIRED_CHECKS).map(|i| format!("c{i}")).collect(); + assert!(normalize_required_checks(&many).is_err()); + } + + #[test] + fn effective_carries_required_checks() { + let mut r = rule("main", false, false, "2024-01-01"); + r.required_checks = vec!["ci/test".into()]; + let got = effective(&[r], "main", "main"); + assert_eq!(got.required_checks, ["ci/test"]); + assert!(effective(&[], "main", "main").required_checks.is_empty()); + } } diff --git a/crates/forge-core/src/pulls.rs b/crates/forge-core/src/pulls.rs index 68a7c5a..8e2e55d 100644 --- a/crates/forge-core/src/pulls.rs +++ b/crates/forge-core/src/pulls.rs @@ -61,6 +61,17 @@ pub struct PullRequest { pub merged_at: Option, pub merged_by: Option, pub merge_commit: Option, + /// A draft cannot be merged and does not notify reviewers until marked ready. + pub draft: bool, + /// Set while auto-merge is enabled. + pub auto_merge: Option, +} + +/// Auto-merge settings: the merge runs as `user_id` with `style` once the merge gate passes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AutoMerge { + pub style: MergeStyle, + pub user_id: Id, } /// How a pull request is merged into its base branch. @@ -69,6 +80,7 @@ pub enum MergeStyle { Merge, Squash, FastForward, + Rebase, } impl MergeStyle { @@ -78,6 +90,7 @@ impl MergeStyle { MergeStyle::Merge => "merge", MergeStyle::Squash => "squash", MergeStyle::FastForward => "ff", + MergeStyle::Rebase => "rebase", } } } @@ -90,6 +103,7 @@ impl std::str::FromStr for MergeStyle { "merge" => Ok(MergeStyle::Merge), "squash" => Ok(MergeStyle::Squash), "ff" => Ok(MergeStyle::FastForward), + "rebase" => Ok(MergeStyle::Rebase), other => Err(Error::Invalid(format!("merge style {other:?}"))), } } @@ -119,10 +133,11 @@ mod tests { MergeStyle::Merge, MergeStyle::Squash, MergeStyle::FastForward, + MergeStyle::Rebase, ] { assert_eq!(s.as_str().parse::().ok(), Some(s)); } assert_eq!(MergeStyle::FastForward.as_str(), "ff"); - assert!("rebase".parse::().is_err()); + assert!("octopus".parse::().is_err()); } } diff --git a/crates/forge-core/src/store/commit_status.rs b/crates/forge-core/src/store/commit_status.rs index b8bc521..ba2a733 100644 --- a/crates/forge-core/src/store/commit_status.rs +++ b/crates/forge-core/src/store/commit_status.rs @@ -230,6 +230,20 @@ impl Store { .await } + /// Distinct status contexts seen in the repo, most recently reported first. Feeds the + /// required-checks picker in branch protection. + pub async fn recent_status_contexts(&self, repo_id: &str, limit: u32) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT context FROM commit_statuses WHERE repo_id = ?1 GROUP BY context \ + ORDER BY MAX(updated_at) DESC, context LIMIT ?2", + (repo_id.to_string(), i64::from(limit)), + |row| col_text(row, 0), + ) + .await + } + /// The combined state of one commit, or `None` when it has no statuses. pub async fn combined_state(&self, repo_id: &str, sha: &str) -> Result> { let statuses = self.statuses_for(repo_id, sha).await?; diff --git a/crates/forge-core/src/store/issues.rs b/crates/forge-core/src/store/issues.rs index 3c0c085..5881890 100644 --- a/crates/forge-core/src/store/issues.rs +++ b/crates/forge-core/src/store/issues.rs @@ -40,6 +40,10 @@ const EVENT_KINDS: &[&str] = &[ "head_deleted", "head_ref_deleted", "head_ref_restored", + "ready_for_review", + "converted_to_draft", + "auto_merge_enabled", + "auto_merge_disabled", // Pull request reviews (store/reviews.rs). "review_dismissed", "thread_resolved", @@ -394,6 +398,15 @@ impl Store { clauses.push("i.title LIKE ? ESCAPE '\\'"); params.push(Value::Text(like_pattern(query))); } + if let (true, Some(draft)) = (kind == "pull", f.draft) { + { + clauses.push(if draft { + "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 1)" + } else { + "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 0)" + }); + } + } let where_sql = clauses.join(" AND "); let order = match f.sort { IssueSort::Newest => "i.number DESC", diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index d4816c9..4785e69 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -72,6 +72,14 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ include_str!("../../migrations/0046_server_settings.sql"), ), (50, include_str!("../../migrations/0050_run_warnings.sql")), + ( + 52, + include_str!("../../migrations/0052_pull_draft_automerge.sql"), + ), + ( + 53, + include_str!("../../migrations/0053_required_checks.sql"), + ), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 3e0bd51..4b9f378 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -1230,7 +1230,7 @@ impl Store { } const BRANCH_RULE_COLS: &str = "id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \ - required_approvals, block_on_changes_requested, require_up_to_date, restrict_push"; + required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks"; // branch protection impl Store { @@ -1258,15 +1258,19 @@ impl Store { ) -> Result { crate::protection::validate_pattern(pattern)?; validate_required_approvals(flags.required_approvals)?; + let checks = crate::protection::normalize_required_checks(&flags.required_checks)?; + let checks_json = + serde_json::to_string(&checks).map_err(|e| Error::Database(e.to_string()))?; let conn = self.inner.conn.lock().await; conn.execute( "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \ - required_approvals, block_on_changes_requested, require_up_to_date, restrict_push) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) \ + required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) \ ON CONFLICT(repo_id, pattern) DO UPDATE SET allow_force_push = excluded.allow_force_push, \ allow_deletion = excluded.allow_deletion, required_approvals = excluded.required_approvals, \ block_on_changes_requested = excluded.block_on_changes_requested, \ - require_up_to_date = excluded.require_up_to_date, restrict_push = excluded.restrict_push", + require_up_to_date = excluded.require_up_to_date, restrict_push = excluded.restrict_push, \ + required_checks = excluded.required_checks", ( new_id(), repo_id.to_string(), @@ -1278,6 +1282,7 @@ impl Store { i64::from(flags.block_on_changes_requested), i64::from(flags.require_up_to_date), i64::from(flags.restrict_push), + checks_json, ), ) .await @@ -1324,6 +1329,8 @@ fn map_branch_rule(row: &Row) -> Result { block_on_changes_requested: col_bool(row, 7)?, require_up_to_date: col_bool(row, 8)?, restrict_push: col_bool(row, 9)?, + required_checks: serde_json::from_str(&col_text(row, 10)?) + .map_err(|e| Error::Database(format!("required_checks is not a JSON array: {e}")))?, }) } @@ -2020,6 +2027,93 @@ mod tests { )); } + #[tokio::test] + async fn branch_rule_required_checks_round_trip_and_normalise() { + let dir = tempfile::tempdir().unwrap(); + let (store, owner) = store_with_user(&dir).await; + let repo = store + .create_repo(&owner.id, "proj", "", Visibility::Public, "main") + .await + .unwrap(); + let flags = RuleFlags { + required_checks: vec![ + " ci/test ".into(), + "lint".into(), + "ci/test".into(), + " ".into(), + ], + ..RuleFlags::default() + }; + let rule = store + .upsert_branch_rule(&repo.id, "main", flags) + .await + .unwrap(); + assert_eq!(rule.required_checks, vec!["ci/test", "lint"]); + assert_eq!( + store.list_branch_rules(&repo.id).await.unwrap()[0].required_checks, + vec!["ci/test", "lint"] + ); + + // Saving without checks clears them; a control character is refused. + let cleared = store + .upsert_branch_rule(&repo.id, "main", RuleFlags::default()) + .await + .unwrap(); + assert!(cleared.required_checks.is_empty()); + let bad = RuleFlags { + required_checks: vec!["a\nb".into()], + ..RuleFlags::default() + }; + assert!(matches!( + store.upsert_branch_rule(&repo.id, "main", bad).await, + Err(Error::Invalid(_)) + )); + } + + #[tokio::test] + async fn recent_status_contexts_are_distinct_and_newest_first() { + let dir = tempfile::tempdir().unwrap(); + let (store, owner) = store_with_user(&dir).await; + let repo = store + .create_repo(&owner.id, "proj", "", Visibility::Public, "main") + .await + .unwrap(); + let sha_a = "a".repeat(40); + let sha_b = "b".repeat(40); + for (sha, context) in [(&sha_a, "ci/test"), (&sha_b, "ci/test"), (&sha_a, "lint")] { + store + .set_status( + &repo.id, + sha, + context, + crate::store::commit_status::StatusState::Success, + None, + None, + &owner.id, + ) + .await + .unwrap(); + } + let mut seen = store.recent_status_contexts(&repo.id, 10).await.unwrap(); + seen.sort(); + assert_eq!(seen, vec!["ci/test", "lint"]); + assert_eq!( + store + .recent_status_contexts(&repo.id, 1) + .await + .unwrap() + .len(), + 1 + ); + assert!( + store + .recent_status_contexts("nope", 10) + .await + .unwrap() + .is_empty() + ); + } + #[tokio::test] async fn branch_rules_list_upsert_and_update() { let dir = tempfile::tempdir().unwrap(); @@ -2077,9 +2171,10 @@ mod tests { block_on_changes_requested: true, require_up_to_date: true, restrict_push: true, + required_checks: Vec::new(), }; let saved = store - .upsert_branch_rule(&repo.id, "main", flags) + .upsert_branch_rule(&repo.id, "main", flags.clone()) .await .unwrap(); assert_eq!(saved.required_approvals, 20); diff --git a/crates/forge-core/src/store/pulls.rs b/crates/forge-core/src/store/pulls.rs index 9ae1878..260a2a9 100644 --- a/crates/forge-core/src/store/pulls.rs +++ b/crates/forge-core/src/store/pulls.rs @@ -13,15 +13,15 @@ use super::{ use crate::error::{Error, Result}; use crate::issues::{Issue, IssueFilter, IssueListItem, IssueState, validate_body, validate_title}; use crate::model::{Id, Repo}; -use crate::pulls::{Mergeable, PullRequest}; +use crate::pulls::{AutoMerge, MergeStyle, Mergeable, PullRequest}; use crate::time::now_stamp; -/// The issue columns (0 to 14) followed by the `pull_requests` columns (15 to 25). +/// The issue columns (0 to 14) followed by the `pull_requests` columns (15 to 28). const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i.state_reason, \ i.author_id, i.milestone_id, i.comment_count, i.created_at, i.updated_at, \ i.closed_at, i.locked, i.lock_reason, p.base_branch, p.head_repo_id, p.head_branch, p.head_oid, \ p.base_oid, p.merge_base, p.mergeable, p.conflict_files, p.merged_at, \ - p.merged_by, p.merge_commit"; + p.merged_by, p.merge_commit, p.draft, p.auto_merge_style, p.auto_merge_user"; const MERGED_MSG: &str = "pull request is already merged"; @@ -43,6 +43,14 @@ fn map_pull(row: &Row) -> Result { merged_at: col_opt_text(row, 23)?, merged_by: col_opt_text(row, 24)?, merge_commit: col_opt_text(row, 25)?, + draft: col_int(row, 26)? != 0, + auto_merge: match (col_opt_text(row, 27)?, col_opt_text(row, 28)?) { + (Some(style), Some(user_id)) => Some(AutoMerge { + style: parse_db(&style)?, + user_id, + }), + _ => None, + }, }) } @@ -187,6 +195,8 @@ impl Store { merged_at: None, merged_by: None, merge_commit: None, + draft: false, + auto_merge: None, }) } .await; @@ -267,7 +277,8 @@ impl Store { let changed = conn .execute( "UPDATE pull_requests SET head_oid = ?2, merge_base = NULL, mergeable = 'unknown', \ - conflict_files = '[]' WHERE issue_id = ?1", + conflict_files = '[]', auto_merge_style = NULL, auto_merge_user = NULL \ + WHERE issue_id = ?1", (issue_id.to_string(), head_oid.to_string()), ) .await @@ -324,6 +335,135 @@ impl Store { Ok(()) } + /// Sets or clears the draft flag of an open pull request and records a `ready_for_review` or + /// `converted_to_draft` event. Returns whether the flag changed. A merged or closed pull + /// request is `Conflict`. Turning a pull request into a draft also disables auto-merge. + pub async fn set_pull_draft( + &self, + issue_id: &str, + actor_id: Option<&str>, + draft: bool, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let current = load_pull(&tx, issue_id).await?; + if current.merged_at.is_some() { + return Err(Error::Conflict(MERGED_MSG.into())); + } + if current.issue.state == IssueState::Closed { + return Err(Error::Conflict("pull request is closed".into())); + } + if current.draft == draft { + return Ok(false); + } + tx.execute( + "UPDATE pull_requests SET draft = ?2, auto_merge_style = CASE WHEN ?2 = 1 THEN NULL \ + ELSE auto_merge_style END, auto_merge_user = CASE WHEN ?2 = 1 THEN NULL \ + ELSE auto_merge_user END WHERE issue_id = ?1", + (issue_id.to_string(), i64::from(draft)), + ) + .await + .map_err(db_err)?; + let kind = if draft { + "converted_to_draft" + } else { + "ready_for_review" + }; + insert_event(&tx, issue_id, actor_id, kind, &serde_json::json!({})).await?; + Ok(true) + } + .await; + finish(tx, outcome).await + } + + /// Enables auto-merge for an open, unmerged pull request: the merge will run as `user_id` + /// with `style`. Records an `auto_merge_enabled` event. + pub async fn enable_auto_merge( + &self, + issue_id: &str, + user_id: &str, + style: MergeStyle, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let current = load_pull(&tx, issue_id).await?; + if current.merged_at.is_some() { + return Err(Error::Conflict(MERGED_MSG.into())); + } + if current.issue.state == IssueState::Closed { + return Err(Error::Conflict("pull request is closed".into())); + } + tx.execute( + "UPDATE pull_requests SET auto_merge_style = ?2, auto_merge_user = ?3 \ + WHERE issue_id = ?1", + ( + issue_id.to_string(), + style.as_str().to_string(), + user_id.to_string(), + ), + ) + .await + .map_err(db_err)?; + let data = serde_json::json!({ "style": style.as_str() }); + insert_event(&tx, issue_id, Some(user_id), "auto_merge_enabled", &data).await?; + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Disables auto-merge and records an `auto_merge_disabled` event with `reason` (a short + /// machine word such as `manual`, `push` or `refused`). Returns whether it was enabled. + pub async fn disable_auto_merge( + &self, + issue_id: &str, + actor_id: Option<&str>, + reason: &str, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let changed = tx + .execute( + "UPDATE pull_requests SET auto_merge_style = NULL, auto_merge_user = NULL \ + WHERE issue_id = ?1 AND auto_merge_style IS NOT NULL", + (issue_id.to_string(),), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Ok(false); + } + let data = serde_json::json!({ "reason": reason }); + insert_event(&tx, issue_id, actor_id, "auto_merge_disabled", &data).await?; + Ok(true) + } + .await; + finish(tx, outcome).await + } + + /// Open pull requests of this base repo with auto-merge enabled whose head is `sha`. + pub async fn auto_merge_pulls_for_head( + &self, + repo_id: &str, + sha: &str, + ) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {PULL_COLS} FROM issues i JOIN pull_requests p ON p.issue_id = i.id \ + WHERE i.repo_id = ?1 AND p.head_oid = ?2 AND i.state = 'open' AND i.kind = 'pull' \ + AND p.auto_merge_style IS NOT NULL ORDER BY i.number" + ), + (repo_id.to_string(), sha.to_string()), + map_pull, + ) + .await + } + /// Marks a pull request merged. It closes the issue with reason `completed`, sets the merge /// fields and records a `merged` event with `{"commit": merge_commit}`. Fails with `Conflict` /// if it is already merged or closed, and with `NotFound` if `issue_id` is not a pull request. @@ -353,7 +493,8 @@ impl Store { .map_err(db_err)?; tx.execute( "UPDATE pull_requests SET merged_at = ?2, merged_by = ?3, merge_commit = ?4, \ - mergeable = 'merged', conflict_files = '[]' WHERE issue_id = ?1", + mergeable = 'merged', conflict_files = '[]', auto_merge_style = NULL, \ + auto_merge_user = NULL WHERE issue_id = ?1", ( issue_id.to_string(), now, @@ -1044,4 +1185,171 @@ mod tests { .collect(); assert_eq!(kinds, vec!["head_updated", "base_changed", "head_deleted"]); } + + #[tokio::test] + async fn draft_flag_round_trips_with_events_and_list_filter() { + let fx = fixture().await; + let pr = open_pull(&fx, &fx.repo.id, "feature", "wip").await; + let _ready = open_pull(&fx, &fx.repo.id, "other", "ready").await; + assert!(!pr.draft); + + assert!( + fx.store + .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), true) + .await + .unwrap() + ); + // Setting the same value again changes nothing and records no event. + assert!( + !fx.store + .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), true) + .await + .unwrap() + ); + let got = fx + .store + .pull_by_number(&fx.repo.id, pr.issue.number) + .await + .unwrap() + .unwrap(); + assert!(got.draft); + + let only = |draft: Option| IssueFilter { + state: None, + draft, + ..IssueFilter::default() + }; + let (items, total) = fx + .store + .list_pulls(&fx.repo.id, &only(Some(true))) + .await + .unwrap(); + assert_eq!((total, items[0].issue.number), (1, pr.issue.number)); + let (_, total) = fx + .store + .list_pulls(&fx.repo.id, &only(Some(false))) + .await + .unwrap(); + assert_eq!(total, 1); + let (_, total) = fx.store.list_pulls(&fx.repo.id, &only(None)).await.unwrap(); + assert_eq!(total, 2); + let numbers = [pr.issue.number, pr.issue.number + 1]; + let drafts = fx.store.draft_numbers(&fx.repo.id, &numbers).await.unwrap(); + assert_eq!(drafts.len(), 1); + assert!(drafts.contains(&pr.issue.number)); + + assert!( + fx.store + .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), false) + .await + .unwrap() + ); + let kinds: Vec = fx + .store + .list_events(&pr.issue.id) + .await + .unwrap() + .into_iter() + .map(|e| e.kind) + .collect(); + assert_eq!(kinds, vec!["converted_to_draft", "ready_for_review"]); + } + + #[tokio::test] + async fn auto_merge_is_stored_and_cleared_by_push_draft_and_merge() { + let fx = fixture().await; + let pr = open_pull(&fx, &fx.repo.id, "feature", "auto").await; + let head = "a".repeat(40); + let load = || async { + fx.store + .pull_by_number(&fx.repo.id, pr.issue.number) + .await + .unwrap() + .unwrap() + }; + assert!(load().await.auto_merge.is_none()); + assert!( + !fx.store + .disable_auto_merge(&pr.issue.id, None, "manual") + .await + .unwrap() + ); + + fx.store + .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Rebase) + .await + .unwrap(); + let auto = load().await.auto_merge.expect("enabled"); + assert_eq!( + (auto.style, auto.user_id.as_str()), + (MergeStyle::Rebase, fx.bob.id.as_str()) + ); + let found = fx + .store + .auto_merge_pulls_for_head(&fx.repo.id, &head) + .await + .unwrap(); + assert_eq!(found.len(), 1); + assert!( + fx.store + .auto_merge_pulls_for_head(&fx.repo.id, &"d".repeat(40)) + .await + .unwrap() + .is_empty() + ); + + // A new head clears it. + fx.store + .update_pull_head(&pr.issue.id, &"b".repeat(40)) + .await + .unwrap(); + assert!(load().await.auto_merge.is_none()); + + // Converting to a draft clears it. + fx.store + .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Merge) + .await + .unwrap(); + fx.store + .set_pull_draft(&pr.issue.id, None, true) + .await + .unwrap(); + assert!(load().await.auto_merge.is_none()); + + // Disabling records why; merging clears it. + fx.store + .set_pull_draft(&pr.issue.id, None, false) + .await + .unwrap(); + fx.store + .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Squash) + .await + .unwrap(); + assert!( + fx.store + .disable_auto_merge(&pr.issue.id, Some(&fx.bob.id), "refused") + .await + .unwrap() + ); + let events = fx.store.list_events(&pr.issue.id).await.unwrap(); + let last = events.last().unwrap(); + assert_eq!(last.kind, "auto_merge_disabled"); + assert_eq!(last.data["reason"], "refused"); + + fx.store + .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Squash) + .await + .unwrap(); + fx.store + .mark_merged(&pr.issue.id, &fx.bob.id, &"c".repeat(40)) + .await + .unwrap(); + assert!(load().await.auto_merge.is_none()); + assert!( + fx.store + .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Merge) + .await + .is_err() + ); + } } diff --git a/crates/forge-core/src/store/pulls_list_extra.rs b/crates/forge-core/src/store/pulls_list_extra.rs index a0acc62..c9cfc74 100644 --- a/crates/forge-core/src/store/pulls_list_extra.rs +++ b/crates/forge-core/src/store/pulls_list_extra.rs @@ -8,6 +8,25 @@ use super::{Store, col_int, fetch_all}; use crate::error::Result; impl Store { + /// Which of `numbers` are draft pull requests of this repo. + pub async fn draft_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result> { + if numbers.is_empty() { + return Ok(HashSet::new()); + } + let placeholders: Vec = (2..=numbers.len() + 1).map(|i| format!("?{i}")).collect(); + let sql = format!( + "SELECT i.number FROM pull_requests p JOIN issues i ON i.id = p.issue_id \ + WHERE i.repo_id = ?1 AND i.kind = 'pull' AND p.draft = 1 AND i.number IN ({})", + placeholders.join(", ") + ); + let mut params: Vec = Vec::with_capacity(numbers.len() + 1); + params.push(Value::Text(repo_id.to_string())); + params.extend(numbers.iter().map(|n| Value::Integer(*n))); + let conn = self.read_conn().await; + let found = fetch_all(&conn, &sql, params, |row| col_int(row, 0)).await?; + Ok(found.into_iter().collect()) + } + /// Which of `numbers` are merged pull requests of this repo. Numbers that are issues, open /// or closed without a merge are left out. pub async fn merged_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result> { diff --git a/crates/forge-git/src/pulls.rs b/crates/forge-git/src/pulls.rs index 1bc1a88..072e102 100644 --- a/crates/forge-git/src/pulls.rs +++ b/crates/forge-git/src/pulls.rs @@ -492,6 +492,133 @@ pub async fn range_log_with( new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await } +/// Outcome of replaying head commits onto a base tip. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RebaseResult { + /// The commits replay cleanly; `tip` is the new head (the base tip when every commit was + /// already applied) and `count` the number of commits created. + Clean { tip: String, count: usize }, + /// A commit does not apply; `commit` is its id and `files` the conflicted paths. + Conflict { commit: String, files: Vec }, +} + +/// Replays the commits reachable from `head_oid` but not from `base_oid` onto `base_oid`, oldest +/// first, keeping each author and message. The committer is `committer`. Merge commits in the +/// range are skipped and a commit whose changes the base already has is dropped. Nothing is +/// written but objects: no ref moves. +pub async fn rebase_commits( + env: &GitEnv, + repo: &Path, + base_oid: &str, + head_oid: &str, + committer: &Signature, +) -> Result { + validate_oid(base_oid)?; + validate_oid(head_oid)?; + let negated = format!("^{base_oid}"); + let cmd = git(env, "rev-list") + .git_dir(repo) + .arg("--reverse") + .arg("--topo-order") + .arg("--no-merges") + .user_revs(&[head_oid, negated.as_str()])?; + let out = run_raw(cmd, None).await?; + if !out.status.success() { + return Err(failed("rev-list", &out)); + } + let commits: Vec = String::from_utf8_lossy(&out.stdout) + .lines() + .map(str::to_owned) + .collect(); + let mut tip = base_oid.to_owned(); + let mut count = 0usize; + for commit in commits { + validate_oid(&commit)?; + let cmd = git(env, "log") + .git_dir(repo) + .arg("-1") + .arg("--format=%P%x00%an%x00%ae%x00%at%x00%B") + .user_revs(&[commit.as_str()])?; + let out = run_raw(cmd, None).await?; + if !out.status.success() { + return Err(failed("log", &out)); + } + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + let mut parts = text.splitn(5, '\0'); + let parents = parts.next().unwrap_or_default(); + let name = parts.next().unwrap_or_default().to_owned(); + let email = parts.next().unwrap_or_default().to_owned(); + let time_unix = parts + .next() + .and_then(|t| t.trim().parse::().ok()) + .unwrap_or(committer.time_unix); + let message = parts.next().unwrap_or_default().to_owned(); + let Some(parent) = parents.split_whitespace().next() else { + return Err(Error::InvalidInput( + "cannot rebase a root commit onto the base".into(), + )); + }; + validate_oid(parent)?; + let cmd = git(env, "merge-tree") + .git_dir(repo) + .arg("--write-tree") + .arg("--name-only") + .arg("--no-messages") + .user_opt("--merge-base", parent)? + .user_revs(&[tip.as_str(), commit.as_str()])?; + let out = run_raw(cmd, None).await?; + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + let tree = match out.status.code() { + Some(0) => text.lines().next().unwrap_or_default().trim().to_owned(), + Some(1) => { + let mut files: Vec = Vec::new(); + for line in text + .lines() + .skip(1) + .map(str::trim) + .filter(|l| !l.is_empty()) + { + if !files.iter().any(|f| f == line) { + files.push(line.to_owned()); + } + } + return Ok(RebaseResult::Conflict { commit, files }); + } + _ => return Err(failed("merge-tree", &out)), + }; + validate_oid(&tree)?; + let tip_tree = format!("{tip}^{{tree}}"); + let cmd = git(env, "rev-parse") + .git_dir(repo) + .arg("--verify") + .user_revs(&[tip_tree.as_str()])?; + let out = run_raw(cmd, None).await?; + if !out.status.success() { + return Err(failed("rev-parse", &out)); + } + if stdout_trimmed(&out) == tree { + continue; + } + let author = Signature { + name, + email, + time_unix, + }; + tip = commit_tree( + env, + repo, + &tree, + &[tip.as_str()], + message.trim_end_matches('\n'), + &author, + committer, + ) + .await?; + count += 1; + } + Ok(RebaseResult::Clean { tip, count }) +} + #[cfg(test)] mod tests { use super::*; @@ -1072,4 +1199,72 @@ mod tests { .map(|_| ()), ); } + + #[tokio::test] + async fn rebase_replays_commits_keeping_authors() { + let sb = Sandbox::new(); + let env = sb.env(); + let w = sb.repo("repo"); + w.write("a.txt", "1\n"); + w.commit("c0"); + w.git(&["switch", "-q", "-c", "feature"]); + w.write("b.txt", "one\n"); + w.commit("first"); + w.write("b.txt", "two\n"); + let head = w.commit("second"); + w.git(&["switch", "-q", "main"]); + w.write("c.txt", "main\n"); + let base = w.commit("main work"); + let gd = w.git_dir(); + let committer = Signature { + name: "tahinli".into(), + email: "tahinli@example.com".into(), + time_unix: 1_700_000_000, + }; + let (tip, count) = match rebase_commits(&env, &gd, &base, &head, &committer) + .await + .expect("rebase") + { + RebaseResult::Clean { tip, count } => (tip, count), + other => panic!("expected clean, got {other:?}"), + }; + assert_eq!(count, 2); + assert_eq!(w.git(&["rev-parse", &format!("{tip}~2")]), base); + assert_eq!( + w.git(&["log", "-1", "--format=%an|%cn|%s", &tip]), + "Tester|tahinli|second" + ); + assert_eq!(w.git(&["show", &format!("{tip}:b.txt")]), "two"); + assert_eq!(w.git(&["show", &format!("{tip}:c.txt")]), "main"); + } + + #[tokio::test] + async fn rebase_reports_conflicts() { + let sb = Sandbox::new(); + let env = sb.env(); + let w = sb.repo("repo"); + w.write("a.txt", "1\n"); + w.commit("c0"); + w.git(&["switch", "-q", "-c", "feature"]); + w.write("a.txt", "feature\n"); + let head = w.commit("feature edit"); + w.git(&["switch", "-q", "main"]); + w.write("a.txt", "main\n"); + let base = w.commit("main edit"); + let committer = Signature { + name: "tahinli".into(), + email: "tahinli@example.com".into(), + time_unix: 1_700_000_000, + }; + match rebase_commits(&env, &w.git_dir(), &base, &head, &committer) + .await + .expect("rebase") + { + RebaseResult::Conflict { commit, files } => { + assert_eq!(commit, head); + assert_eq!(files, vec!["a.txt".to_owned()]); + } + other => panic!("expected conflict, got {other:?}"), + } + } } diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index cb51695..bbcf79e 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -422,6 +422,20 @@ } }, false); + // Branch rule form: a suggested check context is added to the required checks field. + document.addEventListener('click', function (e) { + var chip = e.target && e.target.closest ? e.target.closest('[data-check-add]') : null; + if (!chip) { return; } + var form = chip.closest('form'); + var input = form ? form.querySelector('input[name="required_checks"]') : null; + if (!input) { return; } + e.preventDefault(); + var context = chip.getAttribute('data-check-add') || ''; + var parts = input.value.split(/[,\n]/).map(function (p) { return p.trim(); }).filter(Boolean); + if (parts.indexOf(context) < 0) { parts.push(context); } + input.value = parts.join(', '); + }, false); + document.addEventListener('click', function (e) { if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; } var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; diff --git a/crates/forge-web/src/api/statuses.rs b/crates/forge-web/src/api/statuses.rs index 8b167dc..9fe1bf2 100644 --- a/crates/forge-web/src/api/statuses.rs +++ b/crates/forge-web/src/api/statuses.rs @@ -107,6 +107,7 @@ async fn report_status(cx: &Cx, body: Body) -> topcoat::Result { } Err(e) => return Ok(*api::internal(e)), }; + crate::automerge::on_status(state, &repo.id, &sha).await; Ok(api::json(StatusCode::CREATED, &status_json(&saved))) } diff --git a/crates/forge-web/src/automerge.rs b/crates/forge-web/src/automerge.rs new file mode 100644 index 0000000..424458d --- /dev/null +++ b/crates/forge-web/src/automerge.rs @@ -0,0 +1,105 @@ +//! Auto-merge: a pull request with auto-merge enabled merges by itself, as the user who enabled +//! it, the moment its merge gate passes. +//! +//! The gate (`pulls_merge::merge_gate`) is re-evaluated whenever something that can clear it +//! arrives: a commit status (the token API, CI job completion) or a review. A new push to the head +//! branch disables auto-merge (see `pulls_sync`). Nothing here polls; every call is a reaction to +//! an event. + +use forge_core::{Action, IssueState, PullRequest, Repo, authorize}; + +use crate::pages::pulls_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 +/// `sha`. Called after a commit status for `sha` was written. Failures are logged: the status +/// that triggered this has already been stored. +pub async fn on_status(state: &AppState, repo_id: &str, sha: &str) { + let pulls = match state.store.auto_merge_pulls_for_head(repo_id, sha).await { + Ok(pulls) => pulls, + Err(e) => { + tracing::error!(error = %e, repo_id, "auto-merge: listing pull requests failed"); + return; + } + }; + if pulls.is_empty() { + return; + } + let repo = match state.store.repo_by_id(repo_id).await { + Ok(Some(repo)) => repo, + Ok(None) => return, + Err(e) => { + tracing::error!(error = %e, repo_id, "auto-merge: loading repo failed"); + return; + } + }; + for pr in pulls { + evaluate_logged(state, &repo, &pr).await; + } +} + +/// Re-evaluates one pull request, reloaded from the store. Called after a review arrived. +pub async fn on_pull(state: &AppState, repo: &Repo, number: i64) { + match state.store.pull_by_number(&repo.id, number).await { + Ok(Some(pr)) => evaluate_logged(state, repo, &pr).await, + Ok(None) => {} + Err(e) => { + tracing::error!(error = %e, repo_id = %repo.id, number, "auto-merge: loading pull failed"); + } + } +} + +async fn evaluate_logged(state: &AppState, repo: &Repo, pr: &PullRequest) { + if let Err(e) = Box::pin(evaluate(state, repo, pr)).await { + tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "auto-merge: evaluation failed"); + } +} + +/// Merges `pr` when auto-merge is on and nothing blocks it any more. Returns whether it merged. +/// +/// The merge runs as the user who enabled auto-merge, and only while that user still has Write on +/// the repo; otherwise auto-merge is switched off with a timeline notice. A merge the repository +/// refuses (a conflict, a moved base) also switches it off, so it never retries forever. +pub async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_core::Result { + let Some(auto) = pr.auto_merge.as_ref() else { + return Ok(false); + }; + if pr.merged_at.is_some() || pr.issue.state != IssueState::Open || repo.archived { + return Ok(false); + } + if pr.draft || pr.head_repo_id.is_none() { + return Ok(false); + } + if merge_gate(state, repo, pr).await?.blocked().is_some() { + return Ok(false); + } + let Some(user) = state.store.user_by_id(&auto.user_id).await? else { + state + .store + .disable_auto_merge(&pr.issue.id, None, "permission") + .await?; + return Ok(false); + }; + let collaborator = state.store.collaborator_role(&repo.id, &user.id).await?; + let org = state + .store + .org_repo_role(&repo.owner_id, &user.id, &repo.id) + .await?; + if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() { + state + .store + .disable_auto_merge(&pr.issue.id, None, "permission") + .await?; + return Ok(false); + } + match perform_merge(state, repo, pr, &user, auto.style, None, None).await? { + MergeOutcome::Merged { .. } => Ok(true), + MergeOutcome::Refused { .. } => { + state + .store + .disable_auto_merge(&pr.issue.id, Some(&user.id), "refused") + .await?; + Ok(false) + } + } +} diff --git a/crates/forge-web/src/ci/mod.rs b/crates/forge-web/src/ci/mod.rs index 0be24e3..f6a7aa1 100644 --- a/crates/forge-web/src/ci/mod.rs +++ b/crates/forge-web/src/ci/mod.rs @@ -108,7 +108,9 @@ pub(crate) async fn publish( .await { tracing::error!(error = %e, run_id = %run.id, context, "ci: writing commit status failed"); + return; } + crate::automerge::on_status(state, &repo.id, &run.commit_oid).await; } /// The person a CI status is recorded for: the run's actor, or the repo owner for a system run. diff --git a/crates/forge-web/src/i18n/issues.rs b/crates/forge-web/src/i18n/issues.rs index f4385bf..117e567 100644 --- a/crates/forge-web/src/i18n/issues.rs +++ b/crates/forge-web/src/i18n/issues.rs @@ -773,6 +773,50 @@ pub fn event_branch_restored(lang: Lang, branch: &str) -> String { } } +pub fn event_ready_for_review(lang: Lang) -> String { + match lang { + Lang::En => "marked this pull request as ready for review".to_owned(), + Lang::Tr => "bu çekme isteğini incelemeye hazır olarak işaretledi".to_owned(), + } +} + +pub fn event_converted_to_draft(lang: Lang) -> String { + match lang { + Lang::En => "converted this pull request to a draft".to_owned(), + Lang::Tr => "bu çekme isteğini taslağa çevirdi".to_owned(), + } +} + +pub fn event_auto_merge_enabled(lang: Lang, style: &str) -> String { + match lang { + Lang::En => format!("enabled auto-merge ({style})"), + Lang::Tr => format!("otomatik birleştirmeyi açtı ({style})"), + } +} + +pub fn event_auto_merge_disabled(lang: Lang, reason: &str) -> String { + match (lang, reason) { + (Lang::En, "push") => "Auto-merge was disabled because new commits were pushed".to_owned(), + (Lang::Tr, "push") => { + "Yeni commit'ler gönderildiği için otomatik birleştirme kapatıldı".to_owned() + } + (Lang::En, "refused") => { + "Auto-merge was disabled because the merge could not be completed".to_owned() + } + (Lang::Tr, "refused") => { + "Birleştirme tamamlanamadığı için otomatik birleştirme kapatıldı".to_owned() + } + (Lang::En, "permission") => { + "Auto-merge was disabled because its user can no longer merge".to_owned() + } + (Lang::Tr, "permission") => { + "Kullanıcı artık birleştiremediği için otomatik birleştirme kapatıldı".to_owned() + } + (Lang::En, _) => "disabled auto-merge".to_owned(), + (Lang::Tr, _) => "otomatik birleştirmeyi kapattı".to_owned(), + } +} + pub fn event_thread_resolved(lang: Lang, path: &str) -> String { match lang { Lang::En => format!("resolved a conversation on {path}"), diff --git a/crates/forge-web/src/i18n/pulls.rs b/crates/forge-web/src/i18n/pulls.rs index f52811f..a5943a8 100644 --- a/crates/forge-web/src/i18n/pulls.rs +++ b/crates/forge-web/src/i18n/pulls.rs @@ -61,6 +61,12 @@ pub enum K { TitleLabel, DescriptionLabel, CreatePullRequest, + CreateDraftPullRequest, + DraftBadge, + DraftFilterLabel, + DraftAny, + DraftOnly, + DraftReadyOnly, AlreadyOpen, ViewIt, ArchivedNoPulls, @@ -189,6 +195,18 @@ pub fn t(lang: Lang, key: K) -> &'static str { (DescriptionLabel, Tr) => "Açıklama", (CreatePullRequest, En) => "Create pull request", (CreatePullRequest, Tr) => "Çekme isteği oluştur", + (CreateDraftPullRequest, En) => "Create draft pull request", + (CreateDraftPullRequest, Tr) => "Taslak çekme isteği oluştur", + (DraftBadge, En) => "Draft", + (DraftBadge, Tr) => "Taslak", + (DraftFilterLabel, En) => "Draft status", + (DraftFilterLabel, Tr) => "Taslak durumu", + (DraftAny, En) => "Drafts and ready", + (DraftAny, Tr) => "Taslak ve hazır", + (DraftOnly, En) => "Drafts only", + (DraftOnly, Tr) => "Yalnızca taslaklar", + (DraftReadyOnly, En) => "Ready for review only", + (DraftReadyOnly, Tr) => "Yalnızca incelemeye hazır olanlar", (AlreadyOpen, En) => "A pull request is already open for this comparison: ", (AlreadyOpen, Tr) => "Bu karşılaştırma için zaten açık bir çekme isteği var. ", (ViewIt, En) => "view it", @@ -335,6 +353,12 @@ mod tests { K::TitleLabel, K::DescriptionLabel, K::CreatePullRequest, + K::CreateDraftPullRequest, + K::DraftBadge, + K::DraftFilterLabel, + K::DraftAny, + K::DraftOnly, + K::DraftReadyOnly, K::AlreadyOpen, K::ViewIt, K::ArchivedNoPulls, diff --git a/crates/forge-web/src/i18n/pulls_review.rs b/crates/forge-web/src/i18n/pulls_review.rs index 82aa84c..25b0528 100644 --- a/crates/forge-web/src/i18n/pulls_review.rs +++ b/crates/forge-web/src/i18n/pulls_review.rs @@ -26,6 +26,23 @@ pub enum K { StyleMergeCommit, StyleSquash, StyleFastForward, + StyleRebase, + ErrDraft, + ErrNeedsChecks, + ErrRebaseConflict, + ErrAutoMergeBlocked, + DraftBadge, + ReadyForReview, + ConvertToDraft, + RequiredChecksHeading, + CheckPassing, + CheckPending, + CheckFailing, + CheckErrored, + CheckMissing, + EnableAutoMerge, + AutoMergeHint, + DisableAutoMerge, MergeMessageLabel, MergeButton, MergedByPrefix, @@ -115,6 +132,56 @@ pub fn t(lang: Lang, key: K) -> &'static str { (StyleSquash, Tr) => " Sıkıştır ve birleştir", (StyleFastForward, En) => " Fast-forward", (StyleFastForward, Tr) => " İleri sarma (fast-forward)", + (StyleRebase, En) => " Rebase and merge", + (StyleRebase, Tr) => " Yeniden temellendir ve birleştir (rebase)", + (ErrDraft, En) => "This pull request is a draft. Mark it ready for review to merge it.", + (ErrDraft, Tr) => { + "Bu çekme isteği bir taslak. Birleştirmek için önce incelemeye hazır olarak işaretleyin." + } + (ErrNeedsChecks, En) => "Every required status check must pass before this can be merged.", + (ErrNeedsChecks, Tr) => { + "Birleştirmeden önce gerekli tüm durum denetimlerinin geçmesi gerekir." + } + (ErrRebaseConflict, En) => { + "Rebase failed: a commit does not apply cleanly on the base branch. Resolve the conflicts or use another merge style." + } + (ErrRebaseConflict, Tr) => { + "Rebase başarısız: bir commit temel dala temiz uygulanamıyor. Çakışmaları çözün ya da başka bir birleştirme yöntemi seçin." + } + (ErrAutoMergeBlocked, En) => { + "Auto-merge can only be enabled while the pull request waits for checks or approvals." + } + (ErrAutoMergeBlocked, Tr) => { + "Otomatik birleştirme yalnızca çekme isteği denetimleri veya onayları beklerken açılabilir." + } + (DraftBadge, En) => "Draft", + (DraftBadge, Tr) => "Taslak", + (ReadyForReview, En) => "Ready for review", + (ReadyForReview, Tr) => "İncelemeye hazır", + (ConvertToDraft, En) => "Convert to draft", + (ConvertToDraft, Tr) => "Taslağa çevir", + (RequiredChecksHeading, En) => "Required checks", + (RequiredChecksHeading, Tr) => "Gerekli denetimler", + (CheckPassing, En) => "Passing", + (CheckPassing, Tr) => "Başarılı", + (CheckPending, En) => "Pending", + (CheckPending, Tr) => "Bekliyor", + (CheckFailing, En) => "Failing", + (CheckFailing, Tr) => "Başarısız", + (CheckErrored, En) => "Errored", + (CheckErrored, Tr) => "Hata verdi", + (CheckMissing, En) => "Waiting for status", + (CheckMissing, Tr) => "Durum bekleniyor", + (EnableAutoMerge, En) => "Enable auto-merge", + (EnableAutoMerge, Tr) => "Otomatik birleştirmeyi aç", + (AutoMergeHint, En) => { + "The pull request merges by itself as soon as the required checks and approvals pass." + } + (AutoMergeHint, Tr) => { + "Gerekli denetimler ve onaylar tamamlanır tamamlanmaz çekme isteği kendiliğinden birleşir." + } + (DisableAutoMerge, En) => "Disable auto-merge", + (DisableAutoMerge, Tr) => "Otomatik birleştirmeyi kapat", (MergeMessageLabel, En) => "Merge commit message (optional)", (MergeMessageLabel, Tr) => "Birleştirme commit mesajı (isteğe bağlı)", (MergeButton, En) => "Merge pull request", @@ -286,6 +353,13 @@ pub fn branch_deleted(lang: Lang, branch: &str) -> String { } /// "2 of 3 required approvals". +pub fn auto_merge_on(lang: Lang, style: &str, who: &str) -> String { + match lang { + Lang::En => format!("Auto-merge is on ({style}), enabled by {who}."), + Lang::Tr => format!("Otomatik birleştirme açık ({style}), {who} açtı."), + } +} + pub fn approvals_of(lang: Lang, have: impl Display, need: impl Display) -> String { match lang { Lang::En => format!("{have} of {need} required approvals"), @@ -356,6 +430,23 @@ pub const ALL: &[K] = &[ K::StyleMergeCommit, K::StyleSquash, K::StyleFastForward, + K::StyleRebase, + K::ErrDraft, + K::ErrNeedsChecks, + K::ErrRebaseConflict, + K::ErrAutoMergeBlocked, + K::DraftBadge, + K::ReadyForReview, + K::ConvertToDraft, + K::RequiredChecksHeading, + K::CheckPassing, + K::CheckPending, + K::CheckFailing, + K::CheckErrored, + K::CheckMissing, + K::EnableAutoMerge, + K::AutoMergeHint, + K::DisableAutoMerge, K::MergeMessageLabel, K::MergeButton, K::MergedByPrefix, diff --git a/crates/forge-web/src/i18n/repo_admin.rs b/crates/forge-web/src/i18n/repo_admin.rs index 8630096..8d6d5a5 100644 --- a/crates/forge-web/src/i18n/repo_admin.rs +++ b/crates/forge-web/src/i18n/repo_admin.rs @@ -103,6 +103,9 @@ pub enum K { RuleChangesBlock, RuleRestrictPush, RuleUpToDate, + RequiredChecks, + RequiredChecksHelp, + RecentContexts, SaveGeneral, SaveRole, SaveRule, @@ -403,6 +406,16 @@ pub fn t(lang: Lang, key: K) -> &'static str { (RuleChangesBlock, Tr) => "değişiklik istenmesi birleştirmeyi engeller", (RuleRestrictPush, En) => "direct pushes limited to admins", (RuleRestrictPush, Tr) => "doğrudan gönderimler yöneticilerle sınırlı", + (RequiredChecks, En) => "Required status checks", + (RequiredChecks, Tr) => "Gerekli durum denetimleri", + (RequiredChecksHelp, En) => { + "Contexts that must be successful on the pull request head before it can merge, separated by commas. CI jobs report as ci/." + } + (RequiredChecksHelp, Tr) => { + "Birleştirmeden önce çekme isteğinin son commit'inde başarılı olması gereken bağlamlar, virgülle ayrılır. CI işleri ci/ olarak bildirilir." + } + (RecentContexts, En) => "Recently seen:", + (RecentContexts, Tr) => "Son görülenler:", (RuleUpToDate, En) => "head must be up to date with base", (RuleUpToDate, Tr) => "kaynak dal, hedef dalın güncel hâlini içermelidir", (SaveGeneral, En) => "Save general settings", @@ -622,6 +635,14 @@ pub fn yes_no(lang: Lang, value: bool) -> &'static str { } } +/// The number of required status checks in a rule summary. +pub fn checks_count(lang: Lang, n: usize) -> String { + match lang { + Lang::En => format!("{n} required check{}", if n == 1 { "" } else { "s" }), + Lang::Tr => format!("{n} gerekli denetim"), + } +} + /// The number of required approvals in a rule summary. pub fn approvals_count(lang: Lang, n: u32) -> String { match lang { @@ -734,6 +755,9 @@ mod tests { K::RuleChangesBlock, K::RuleRestrictPush, K::RuleUpToDate, + K::RequiredChecks, + K::RequiredChecksHelp, + K::RecentContexts, K::SaveGeneral, K::SaveRole, K::SaveRule, diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 74a45ec..b2f407b 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -16,6 +16,7 @@ mod advisories; mod api; mod audit; mod auth; +mod automerge; mod backup; mod blobs; mod boot; diff --git a/crates/forge-web/src/pages/compare.rs b/crates/forge-web/src/pages/compare.rs index 5aa0b8f..44e680d 100644 --- a/crates/forge-web/src/pages/compare.rs +++ b/crates/forge-web/src/pages/compare.rs @@ -359,7 +359,10 @@ async fn compare_view(

-

+

+ + +

} @@ -474,6 +477,9 @@ struct PullForm { base: String, #[serde(default)] head: String, + /// Non-empty when the pull request opens as a draft. + #[serde(default)] + draft: String, } /// Opens a pull request from a comparison: `POST /{owner}/{repo}/pulls`. @@ -546,16 +552,33 @@ async fn pull_create(cx: &Cx, Form(form): Form) -> Result { } Err(e) => return Err(e.into()), }; + let as_draft = !form.draft.is_empty(); + let pr = if as_draft { + state + .store + .set_pull_draft(&pr.issue.id, Some(&user.id), true) + .await?; + state + .store + .pull_by_number(&ctx.repo.id, pr.issue.number) + .await? + .unwrap_or(pr) + } else { + pr + }; emit_pull(state, &ctx.repo, &Sender::of(&user), "opened", &pr).await; - notify::dispatch( - state, - &ctx.repo, - &pr.issue, - &user.id, - Activity::Opened, - Some(&pr.issue.body), - ) - .await; + if !as_draft { + // A draft tells nobody until it is marked ready for review. + notify::dispatch( + state, + &ctx.repo, + &pr.issue, + &user.id, + Activity::Opened, + Some(&pr.issue.body), + ) + .await; + } let number = pr.issue.number; pulls::fetch_into_pull_ref(&state.git, &ctx.path, &cmp.head.path, &cmp.head_oid, number) .await?; diff --git a/crates/forge-web/src/pages/issue_parts.rs b/crates/forge-web/src/pages/issue_parts.rs index 94dd294..ce6303b 100644 --- a/crates/forge-web/src/pages/issue_parts.rs +++ b/crates/forge-web/src/pages/issue_parts.rs @@ -342,6 +342,10 @@ fn event_line( "pinned" => g::t(lang, K::PinnedThisIssue).to_owned(), "unpinned" => g::t(lang, K::UnpinnedThisIssue).to_owned(), "merged" => g::t(lang, K::MergedCommit).to_owned(), + "ready_for_review" => g::event_ready_for_review(lang), + "converted_to_draft" => g::event_converted_to_draft(lang), + "auto_merge_enabled" => g::event_auto_merge_enabled(lang, &text("style")), + "auto_merge_disabled" => g::event_auto_merge_disabled(lang, &text("reason")), "head_updated" => g::t(lang, K::PushedNewCommits).to_owned(), "head_deleted" => g::t(lang, K::DeletedHeadBranch).to_owned(), "head_ref_deleted" => g::event_branch_deleted(lang, &text("branch")), diff --git a/crates/forge-web/src/pages/issues_list.rs b/crates/forge-web/src/pages/issues_list.rs index 9665805..adc0854 100644 --- a/crates/forge-web/src/pages/issues_list.rs +++ b/crates/forge-web/src/pages/issues_list.rs @@ -48,6 +48,7 @@ pub(crate) struct ListQuery { author: Option, assignee: Option, q: Option, + draft: Option, sort: Option, page: Option, } @@ -61,6 +62,9 @@ pub(crate) struct Selection { pub(crate) author: String, pub(crate) assignee: String, pub(crate) query: String, + /// Pull requests only: `true` (drafts), `false` (ready) or empty (both). A `draft:true` or + /// `draft:false` word in the search text sets it too. + pub(crate) draft: &'static str, /// `newest`, `oldest` or `updated`. pub(crate) sort: &'static str, pub(crate) page: u32, @@ -83,7 +87,30 @@ fn non_empty(value: &str) -> Option { impl Selection { pub(crate) fn parse(query: &ListQuery) -> Self { + let mut draft = match query.draft.as_deref().map(str::trim) { + Some("true") => "true", + Some("false") => "false", + _ => "", + }; + // `draft:true` / `draft:false` words in the search text become the draft filter. + let raw_query = clean(query.q.as_deref()); + let words: Vec<&str> = raw_query + .split_whitespace() + .filter(|word| match *word { + "draft:true" => { + draft = "true"; + false + } + "draft:false" => { + draft = "false"; + false + } + _ => true, + }) + .collect(); + let query_text = words.join(" "); Self { + draft, state: match query.state.as_deref() { Some("closed") => "closed", Some("all") => "all", @@ -93,7 +120,7 @@ impl Selection { milestone: clean(query.milestone.as_deref()), author: clean(query.author.as_deref()), assignee: clean(query.assignee.as_deref()), - query: clean(query.q.as_deref()), + query: query_text, sort: match query.sort.as_deref() { Some("oldest") => "oldest", Some("updated") => "updated", @@ -120,6 +147,11 @@ impl Selection { author: non_empty(&self.author), assignee: non_empty(&self.assignee), query: non_empty(&self.query), + draft: match self.draft { + "true" => Some(true), + "false" => Some(false), + _ => None, + }, sort: match self.sort { "oldest" => IssueSort::Oldest, "updated" => IssueSort::RecentlyUpdated, @@ -136,7 +168,8 @@ impl Selection { && self.milestone.is_empty() && self.author.is_empty() && self.assignee.is_empty() - && self.query.is_empty()) + && self.query.is_empty() + && self.draft.is_empty()) } /// The list URL with this selection, but a different state and page. @@ -156,6 +189,7 @@ impl Selection { ("author", self.author.as_str()), ("assignee", self.assignee.as_str()), ("q", self.query.as_str()), + ("draft", self.draft), ("sort", sort), ("page", page_text.as_str()), ], diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index aad48ad..a43d5d2 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -56,6 +56,7 @@ pub mod profile; pub mod profile_pins; pub mod pull_branch; pub mod pull_files; +pub mod pull_flow; pub mod pull_reviews; pub mod pull_view; pub mod pulls_list; diff --git a/crates/forge-web/src/pages/pull_flow.rs b/crates/forge-web/src/pages/pull_flow.rs new file mode 100644 index 0000000..d0e08e2 --- /dev/null +++ b/crates/forge-web/src/pages/pull_flow.rs @@ -0,0 +1,165 @@ +//! Pull request flow controls: draft state and auto-merge. +//! +//! - `POST /{owner}/{repo}/pulls/{number}/ready` marks a draft ready for review. +//! - `POST /{owner}/{repo}/pulls/{number}/draft` converts an open pull request back to a draft. +//! - `POST /{owner}/{repo}/pulls/{number}/auto-merge` enables auto-merge with a style. +//! - `POST /{owner}/{repo}/pulls/{number}/auto-merge/disable` switches it off. +//! +//! Draft changes are for the pull request author and for Write holders. Auto-merge needs Write, +//! a signed-in viewer with a valid CSRF token, and a pull request that is blocked only by checks +//! or approvals that can still arrive. All of them answer with a redirect back to the pull +//! request (the soft-nav script follows it without a reload). + +use forge_core::{Action, IssueState, MergeStyle, PullRequest, authorize}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{bad_request, forbidden, not_found, see_other}; +use topcoat::router::response::Response; +use topcoat::router::{path_param, route}; + +use crate::auth::require_csrf; +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; +use crate::webhooks::emit::{Sender, emit_item_action}; + +path_param!(owner); +path_param!(repo); +path_param!(number); + +#[derive(Deserialize)] +struct FlowForm { + #[serde(default)] + csrf: String, + #[serde(default)] + style: String, +} + +fn pull_href(ctx: &RepoCtx, number: i64) -> String { + repo_href( + &ctx.repo.owner_name, + &ctx.repo.name, + "pulls", + &number.to_string(), + ) +} + +fn can_write(ctx: &RepoCtx, user: &forge_core::User) -> bool { + authorize(Some(user), &ctx.repo, ctx.role, ctx.org_role, Action::Write).is_ok() +} + +async fn load(cx: &Cx, ctx: &RepoCtx, number: i64) -> Result { + let state = app_context::(cx); + match state.store.pull_by_number(&ctx.repo.id, number).await? { + Some(pr) => Ok(pr), + None => Err(not_found().into()), + } +} + +#[route(POST "/{owner}/{repo}/pulls/{number}/ready")] +async fn ready_post(cx: &Cx, Form(form): Form) -> Result { + set_draft(cx, &form.csrf, false).await +} + +#[route(POST "/{owner}/{repo}/pulls/{number}/draft")] +async fn draft_post(cx: &Cx, Form(form): Form) -> Result { + set_draft(cx, &form.csrf, true).await +} + +async fn set_draft(cx: &Cx, csrf: &str, draft: bool) -> Result { + let number = parse_number(path_param::(cx))?; + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let (user, _) = require_csrf(cx, csrf).await?; + let state = app_context::(cx); + let pr = load(cx, &ctx, number).await?; + if ctx.repo.archived || !(can_write(&ctx, &user) || user.id == pr.issue.author_id) { + return Err(forbidden().into()); + } + let href = pull_href(&ctx, number); + if pr.merged_at.is_some() || pr.issue.state != IssueState::Open { + return Err(see_other(href).into()); + } + let changed = match state + .store + .set_pull_draft(&pr.issue.id, Some(&user.id), draft) + .await + { + Ok(changed) => changed, + Err(forge_core::Error::Conflict(_)) => false, + Err(e) => return Err(e.into()), + }; + if changed { + let action = if draft { + "converted_to_draft" + } else { + "ready_for_review" + }; + emit_item_action(state, &ctx.repo, &Sender::of(&user), true, number, action).await; + if !draft { + // Reviewers hear about the pull request now, not when it was opened as a draft. + notify::dispatch( + state, + &ctx.repo, + &pr.issue, + &user.id, + Activity::Opened, + Some(&pr.issue.body), + ) + .await; + } + } + Err(see_other(href).into()) +} + +#[route(POST "/{owner}/{repo}/pulls/{number}/auto-merge")] +async fn auto_merge_enable(cx: &Cx, Form(form): Form) -> Result { + let number = parse_number(path_param::(cx))?; + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let (user, _) = require_csrf(cx, &form.csrf).await?; + if ctx.repo.archived || !can_write(&ctx, &user) { + return Err(forbidden().into()); + } + let state = app_context::(cx); + let pr = load(cx, &ctx, number).await?; + let style = form + .style + .parse::() + .map_err(|e| bad_request(e.to_string()))?; + let href = pull_href(&ctx, number); + if pr.merged_at.is_some() || pr.issue.state != IssueState::Open || pr.head_repo_id.is_none() { + return Err(see_other(href).into()); + } + let gate = merge_gate(state, &ctx.repo, &pr).await?; + if !gate.waiting_only() { + return Err(see_other(format!("{href}?merge_error={ERR_AUTO_MERGE_BLOCKED}")).into()); + } + state + .store + .enable_auto_merge(&pr.issue.id, &user.id, style) + .await?; + // Nothing may be missing by now: merge right away instead of waiting for an event. + crate::automerge::on_pull(state, &ctx.repo, number).await; + Err(see_other(href).into()) +} + +#[route(POST "/{owner}/{repo}/pulls/{number}/auto-merge/disable")] +async fn auto_merge_disable(cx: &Cx, Form(form): Form) -> Result { + let number = parse_number(path_param::(cx))?; + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let (user, _) = require_csrf(cx, &form.csrf).await?; + if ctx.repo.archived || !can_write(&ctx, &user) { + return Err(forbidden().into()); + } + let state = app_context::(cx); + let pr = load(cx, &ctx, number).await?; + state + .store + .disable_auto_merge(&pr.issue.id, Some(&user.id), "manual") + .await?; + Err(see_other(pull_href(&ctx, number)).into()) +} diff --git a/crates/forge-web/src/pages/pull_reviews.rs b/crates/forge-web/src/pages/pull_reviews.rs index b9396b7..672d162 100644 --- a/crates/forge-web/src/pages/pull_reviews.rs +++ b/crates/forge-web/src/pages/pull_reviews.rs @@ -530,6 +530,7 @@ async fn review_submit(cx: &Cx, Form(form): Form) -> Result Ok(refusal(&tab, ERR_OWN_PR, "")), diff --git a/crates/forge-web/src/pages/pull_view.rs b/crates/forge-web/src/pages/pull_view.rs index 61e6ee1..2eba0da 100644 --- a/crates/forge-web/src/pages/pull_view.rs +++ b/crates/forge-web/src/pages/pull_view.rs @@ -6,6 +6,7 @@ use std::collections::HashMap; +use forge_core::store::commit_status::StatusState; use forge_core::{Action, IssueState, Mergeable, PullRequest, Review, ReviewState, authorize}; use forge_git::browse::CommitInfo; use forge_git::history::CommitDiff; @@ -32,9 +33,10 @@ 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_BASE_MISSING, ERR_BASE_MOVED, ERR_CHANGES_REQUESTED, ERR_CONFLICT, - ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING, ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NOT_OPEN, - ERR_NOT_UP_TO_DATE, ERR_UP_TO_DATE, merge_gate, + 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_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, ERR_NOT_UP_TO_DATE, + ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, merge_gate, }; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, load_repo}; @@ -154,6 +156,8 @@ pub(crate) async fn frame_in( let (state_class, state_text) = if is_merged(pr) { ("issue-badge issue-badge-merged", g::t(lang, K::StateMerged)) + } else if matches!(pr.issue.state, IssueState::Open) && pr.draft { + ("issue-badge issue-badge-draft", g::t(lang, K::DraftBadge)) } else if matches!(pr.issue.state, IssueState::Open) { ("issue-badge issue-badge-open", g::t(lang, K::StateOpen)) } else { @@ -273,6 +277,24 @@ struct MergeForm { ff: bool, } +/// One required check as the merge box lists it. +struct CheckRow { + context: String, + label: &'static str, + class: &'static str, +} + +/// The flow controls of the merge box: the draft toggle and auto-merge. +struct FlowView { + csrf: String, + /// `(action, button label)` of the draft toggle. + draft_toggle: Option<(String, &'static str)>, + /// Auto-merge is on: the status line and the disable action. + auto_on: Option<(String, String)>, + /// Auto-merge can be enabled: the action. + auto_enable: Option, +} + /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of /// `ok`, `bad` or `muted` and picks the box colors. #[component] @@ -286,9 +308,24 @@ async fn merge_box( approvals: Option, blocked: Option, checks: Option, + required: Vec, + flow: FlowView, lang: Lang, ) -> Result { let class = format!("merge-box merge-{tone}"); + let required_heading = g::t(lang, K::RequiredChecksHeading); + let style_rebase = g::t(lang, K::StyleRebase); + let style_merge_option = g::t(lang, K::StyleMergeCommit); + let style_squash_option = g::t(lang, K::StyleSquash); + let enable_auto = g::t(lang, K::EnableAutoMerge); + let auto_hint = g::t(lang, K::AutoMergeHint); + let disable_auto = g::t(lang, K::DisableAutoMerge); + let FlowView { + csrf: flow_csrf, + draft_toggle, + auto_on, + auto_enable, + } = flow; let reload_text = g::t(lang, K::ReloadToCheck); let style_legend = g::t(lang, K::MergeStyleLegend); let style_merge = g::t(lang, K::StyleMergeCommit); @@ -305,6 +342,16 @@ async fn merge_box( if let Some(summary) = checks { checks_summary(summary: summary, lang: StatusLang(lang)) } + if !required.is_empty() { +
+

(required_heading)

+
    + for row in required.iter() { +
  • (row.context.as_str())(row.label)
  • + } +
+
+ } if let Some(text) = approvals {

(text.as_str())

} @@ -328,6 +375,7 @@ async fn merge_box( (style_legend) + if f.ff { } @@ -339,6 +387,31 @@ async fn merge_box(
} + if let Some((text, action)) = auto_on { +
+ +

(text.as_str())

+ +
+ } + if let Some(action) = auto_enable { +
+ +

(auto_hint)

+ + +
+ } + if let Some((action, label)) = draft_toggle { +
+ + +
+ } }) } @@ -580,6 +653,76 @@ async fn pull_conversation( gate.rule.required_approvals, ) }); + let auto_merge_user = match pr.auto_merge.as_ref() { + Some(auto) => state + .store + .usernames_by_ids(std::slice::from_ref(&auto.user_id)) + .await? + .get(&auto.user_id) + .map(|(display, _)| display.clone()) + .unwrap_or_else(|| g::t(lang, K::Unknown).to_owned()), + None => String::new(), + }; + let required: Vec = gate + .as_ref() + .map(|gate| { + gate.required + .iter() + .map(|check| { + let (class, label) = match check.state { + Some(StatusState::Success) => ("check-ok", g::t(lang, K::CheckPassing)), + Some(StatusState::Pending) => { + ("check-pending", g::t(lang, K::CheckPending)) + } + Some(StatusState::Failure) => ("check-bad", g::t(lang, K::CheckFailing)), + Some(StatusState::Error) => ("check-bad", g::t(lang, K::CheckErrored)), + None => ("check-pending", g::t(lang, K::CheckMissing)), + }; + CheckRow { + context: check.context.clone(), + label, + class, + } + }) + .collect() + }) + .unwrap_or_default(); + let auto_waiting = gate + .as_ref() + .is_some_and(|gate| !gate.blockers().is_empty() && gate.waiting_only()); + let flow = FlowView { + csrf: csrf.clone(), + draft_toggle: (open + && !archived + && ctx + .viewer + .as_ref() + .is_some_and(|(user, _)| can_write || user.id == pr.issue.author_id)) + .then(|| { + if pr.draft { + (format!("{href}/ready"), g::t(lang, K::ReadyForReview)) + } else { + (format!("{href}/draft"), g::t(lang, K::ConvertToDraft)) + } + }), + auto_on: pr + .auto_merge + .as_ref() + .filter(|_| open && can_write) + .map(|auto| { + ( + g::auto_merge_on(lang, auto.style.as_str(), &auto_merge_user), + format!("{href}/auto-merge/disable"), + ) + }), + auto_enable: (open + && can_write + && pr.auto_merge.is_none() + && auto_waiting + && pr.mergeable != Mergeable::Conflict + && pr.head_repo_id.is_some()) + .then(|| format!("{href}/auto-merge")), + }; let merge_form = if open && can_write && pr.mergeable == Mergeable::Clean @@ -660,7 +803,8 @@ async fn pull_conversation( if open { merge_box(headline: headline, tone: tone.to_owned(), conflicts: conflicts, reload: reload, form: merge_form, merge_error: merge_error, - approvals: approvals, blocked: blocked, checks: checks, lang: lang) + approvals: approvals, blocked: blocked, checks: checks, + required: required, flow: flow, lang: lang) } if let Some(when) = merged_when { merged_notice(who: merged_who, when: when, commit: merge_commit, @@ -706,6 +850,10 @@ fn merge_error_text(lang: Lang, code: &str) -> Option<&'static str> { ERR_CHANGES_REQUESTED => g::t(lang, K::ErrChangesRequested), ERR_NOT_UP_TO_DATE => g::t(lang, K::ErrNotUpToDate), ERR_MESSAGE_INVALID => g::t(lang, K::ErrMessageInvalid), + ERR_DRAFT => g::t(lang, K::ErrDraft), + ERR_NEEDS_CHECKS => g::t(lang, K::ErrNeedsChecks), + ERR_REBASE_CONFLICT => g::t(lang, K::ErrRebaseConflict), + ERR_AUTO_MERGE_BLOCKED => g::t(lang, K::ErrAutoMergeBlocked), _ => return None, }) } diff --git a/crates/forge-web/src/pages/pulls_list.rs b/crates/forge-web/src/pages/pulls_list.rs index 33ad732..03e223c 100644 --- a/crates/forge-web/src/pages/pulls_list.rs +++ b/crates/forge-web/src/pages/pulls_list.rs @@ -47,6 +47,7 @@ struct PullRowView { assignees: Vec, has_comments: bool, comments_text: String, + draft: bool, } /// The row's icon and badge: green for open, purple for merged, red for closed without a merge. @@ -91,7 +92,7 @@ struct RowEnv<'a> { } /// One row, built from the page's shared values and the item's own `merged` flag. -fn row_view(env: &RowEnv<'_>, item: &IssueListItem, merged: bool) -> PullRowView { +fn row_view(env: &RowEnv<'_>, item: &IssueListItem, merged: bool, draft: bool) -> PullRowView { let RowEnv { lang, base, @@ -144,6 +145,7 @@ fn row_view(env: &RowEnv<'_>, item: &IssueListItem, merged: bool) -> PullRowView .collect(), has_comments: comments > 0, comments_text: g::comments(lang, comments), + draft: draft && open, } } @@ -161,6 +163,7 @@ async fn pulls_list_page(cx: &Cx) -> Result { let (open_count, closed_count) = state.store.pull_counts(&ctx.repo.id).await?; let numbers: Vec = items.iter().map(|item| item.issue.number).collect(); let merged = state.store.merged_numbers(&ctx.repo.id, &numbers).await?; + let drafts = state.store.draft_numbers(&ctx.repo.id, &numbers).await?; let milestones: HashMap = state .store .list_milestones(&ctx.repo.id, None) @@ -184,7 +187,14 @@ async fn pulls_list_page(cx: &Cx) -> Result { }; let rows: Vec = items .iter() - .map(|item| row_view(&env, item, merged.contains(&item.issue.number))) + .map(|item| { + row_view( + &env, + item, + merged.contains(&item.issue.number), + drafts.contains(&item.issue.number), + ) + }) .collect(); let last_page = total.div_ceil(u64::from(PER_PAGE)).max(1); @@ -226,6 +236,8 @@ async fn pulls_list_page(cx: &Cx) -> Result { g::t(lang, K::NoPullRequestsMatch) }; let state_word = sel.state; + let draft_label = g::t(lang, K::DraftBadge); + let draft_sel = sel.draft; let header = ctx.head(state, "pulls").await?; Ok(view! { @@ -250,6 +262,11 @@ async fn pulls_list_page(cx: &Cx) -> Result { + (g::t(lang, K::RestrictPush)) + +

(g::t(lang, K::RequiredChecksHelp))

+ if !contexts.is_empty() { +
+ (g::t(lang, K::RecentContexts)) + for context in contexts.iter() { + + } +
+ }
@@ -570,6 +599,7 @@ struct RuleDraft { block_on_changes_requested: bool, require_up_to_date: bool, restrict_push: bool, + required_checks: String, error: Option, } @@ -584,6 +614,7 @@ impl RuleDraft { block_on_changes_requested: false, require_up_to_date: false, restrict_push: false, + required_checks: String::new(), error: None, } } @@ -596,6 +627,8 @@ struct SettingsView { notice: Option<(K, bool)>, draft: RuleDraft, delete_error: Option, + /// Recently reported status contexts, offered as required-check suggestions. + contexts: Vec, } /// The settings body: the repo header tabs with Settings active, the sub-navigation, the General @@ -623,6 +656,7 @@ async fn settings_body( notice, draft, delete_error, + contexts, } = page; let (description, visibility) = (head.description.clone(), head.visibility); let discussions_on = head.discussions; @@ -651,6 +685,7 @@ async fn settings_body( required_approvals: draft.required_approvals, block_on_changes_requested: draft.block_on_changes_requested, require_up_to_date: draft.require_up_to_date, restrict_push: draft.restrict_push, + required_checks: draft.required_checks, contexts: contexts, error: draft.error) discussions_card(lang: lang, action: format!("/{title}/settings/discussions"), csrf: csrf.clone(), enabled: discussions_on) @@ -705,6 +740,10 @@ async fn settings_page(cx: &Cx) -> Result { notice: take_settings_notice(cx), draft: RuleDraft::for_default_branch(&ctx.repo.default_branch), delete_error: None, + contexts: app_context::(cx) + .store + .recent_status_contexts(&ctx.repo.id, 20) + .await?, }; let csrf = session.csrf_token.clone(); let frame = SettingsFrame::new(&ctx, app_context::(cx), lang).await?; @@ -1006,6 +1045,10 @@ async fn settings_delete(cx: &Cx, Form(form): Form) -> Result(cx) + .store + .recent_status_contexts(&ctx.repo.id, 20) + .await?, }; let csrf = session.csrf_token.clone(); let frame = SettingsFrame::new(&ctx, app_context::(cx), lang).await?; @@ -1054,9 +1097,14 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form) -> Result(cx) + .store + .recent_status_contexts(&ctx.repo.id, 20) + .await?, }; let csrf = session.csrf_token.clone(); let frame = SettingsFrame::new(&ctx, app_context::(cx), lang).await?; @@ -1073,7 +1121,7 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form) -> Result(cx); state .store - .upsert_branch_rule(&ctx.repo.id, &pattern, flags) + .upsert_branch_rule(&ctx.repo.id, &pattern, flags.clone()) .await?; tracing::info!( actor_id = %user.id, diff --git a/crates/forge-web/src/pulls_sync.rs b/crates/forge-web/src/pulls_sync.rs index 2ef61d0..21dc10b 100644 --- a/crates/forge-web/src/pulls_sync.rs +++ b/crates/forge-web/src/pulls_sync.rs @@ -103,6 +103,18 @@ async fn sync_head( let head_path = forge_git::repo::repo_path(&state.git.data_dir, &head_repo.id)?; fetch_into_pull_ref(&state.git, &base_path, &head_path, new, number).await?; state.store.update_pull_head(issue_id, new).await?; + if pr.auto_merge.is_some() { + // `update_pull_head` already cleared the setting; tell the timeline why. + state + .store + .add_event( + issue_id, + actor, + "auto_merge_disabled", + json!({"reason": "push"}), + ) + .await?; + } mark_outdated_threads(state, &base_path, issue_id, new).await; state .store diff --git a/crates/forge-web/src/webhooks/payload.rs b/crates/forge-web/src/webhooks/payload.rs index 72bda37..68b448c 100644 --- a/crates/forge-web/src/webhooks/payload.rs +++ b/crates/forge-web/src/webhooks/payload.rs @@ -175,6 +175,7 @@ fn pull_object(base_url: &str, repo: &Repo, pr: &PullRequest) -> Value { "body": pr.issue.body, "state": pr.issue.state.as_str(), "merged": pr.merged_at.is_some(), + "draft": pr.draft, "base": { "ref": pr.base_branch, "sha": pr.base_oid }, "head": { "ref": pr.head_branch, "sha": pr.head_oid }, "html_url": item_url(base_url, repo, "pulls", pr.issue.number), @@ -242,6 +243,8 @@ mod tests { merged_at: None, merged_by: None, merge_commit: None, + draft: false, + auto_merge: None, } } diff --git a/style/main.scss b/style/main.scss index 358b5fd..4dc07b2 100644 --- a/style/main.scss +++ b/style/main.scss @@ -6148,3 +6148,115 @@ button.ci-job-last { .srv-form .actions { margin-top: 16px; } + +// Draft pull requests: a neutral grey badge, distinct from open (green) and merged (purple). +.issue-badge.issue-badge-draft { + background: var(--code-bg); + color: var(--muted); + border: 1px solid var(--border); +} + +// Required checks and flow controls inside the merge box. +.required-checks { + display: flex; + flex-direction: column; + gap: 0.35rem; + + p { + margin: 0; + } +} + +.required-check-list { + display: flex; + flex-direction: column; + gap: 0.25rem; + margin: 0; + padding: 0; + list-style: none; + + li { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + padding: 0.3rem 0.6rem; + border: 1px solid var(--border); + border-radius: var(--radius-md, var(--radius-lg)); + background: var(--surface); + font-size: 0.9rem; + overflow-wrap: anywhere; + } + + .check-ok span { + color: var(--add-text); + font-weight: 600; + } + + .check-pending span { + color: var(--muted); + } + + .check-bad span { + color: var(--danger); + font-weight: 600; + } +} + +.merge-flow { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem 0.75rem; + margin: 0; + + p { + flex: 1 1 14rem; + margin: 0; + } +} + +// Suggested required-check contexts under the branch rule form. +.context-picker { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.4rem; +} + +.context-chip { + padding: 2px 10px; + border: 1px solid var(--border); + border-radius: var(--radius-full); + background: var(--surface); + font-family: var(--mono); + font-size: 0.8rem; + cursor: pointer; +} + +.form-actions { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} + +// Secondary actions in the merge box (auto-merge, draft toggle): quiet buttons, not full width. +.merge-box .merge-flow button[type="submit"] { + width: auto; + padding: 0 14px; + border-color: var(--border); + background: var(--surface); + color: var(--text); + font-weight: 500; + + &:hover { + border-color: var(--accent); + background: var(--surface); + } +} + +.merge-box .merge-flow select { + width: auto; + min-width: 12rem; +}