forge
Explore
Log in

Don't you dare go Hollow

Draft PRs, rebase merge, required checks and auto-merge

Browse files at this commit

4791c8ae5cde35017045b6d46e37a2203bfd2e5bAhmet Kaan GümüşParent: 264395d
  • feat
    • draft PRs, rebase merge, required checks and auto-merge
Show full message
✨ feat: draft PRs, rebase merge, required checks and auto-merge
crates/forge-core/migrations/0052_pull_draft_automerge.sqladded+8 -0
@@ -0,0 +1,8 @@
1+-- Draft pull requests and auto-merge. Applied by store/migrate.rs.
2+-- draft: a draft cannot be merged and does not notify reviewers until marked ready.
3+-- auto_merge_style / auto_merge_user: set while auto-merge is enabled; the merge runs as that
4+-- user with that style once the merge gate passes. Cleared on merge, on disable and on a new push.
5+
6+ALTER TABLE pull_requests ADD COLUMN draft INTEGER NOT NULL DEFAULT 0;
7+ALTER TABLE pull_requests ADD COLUMN auto_merge_style TEXT NULL;
8+ALTER TABLE pull_requests ADD COLUMN auto_merge_user TEXT NULL REFERENCES users(id);
crates/forge-core/migrations/0053_required_checks.sqladded+4 -0
@@ -0,0 +1,4 @@
1+-- Required status checks on branch protections. Applied by store/migrate.rs.
2+-- A JSON array of commit status contexts that must all be success on a pull request head.
3+
4+ALTER TABLE branch_protections ADD COLUMN required_checks TEXT NOT NULL DEFAULT '[]';
crates/forge-core/src/issues.rsmodified+3 -0
@@ -152,6 +152,8 @@ pub struct IssueFilter {
152 pub assignee: Option<String>,152 pub assignee: Option<String>,
153 /// Substring of the title, case-insensitive.153 /// Substring of the title, case-insensitive.
154 pub query: Option<String>,154 pub query: Option<String>,
155+ /// Pull requests only: `Some(true)` lists drafts, `Some(false)` lists ready pull requests.
156+ pub draft: Option<bool>,
155 pub sort: IssueSort,157 pub sort: IssueSort,
156 /// 1-based.158 /// 1-based.
157 pub page: u32,159 pub page: u32,
@@ -167,6 +169,7 @@ impl Default for IssueFilter {
167 author: None,169 author: None,
168 assignee: None,170 assignee: None,
169 query: None,171 query: None,
172+ draft: None,
170 sort: IssueSort::Newest,173 sort: IssueSort::Newest,
171 page: 1,174 page: 1,
172 per_page: 25,175 per_page: 25,
crates/forge-core/src/protection.rsmodified+65 -2
@@ -23,11 +23,14 @@ pub struct BranchRule {
23 /// Direct pushes to the branch are rejected for everyone but repo admins. Merges through23 /// Direct pushes to the branch are rejected for everyone but repo admins. Merges through
24 /// pull requests are unaffected.24 /// pull requests are unaffected.
25 pub restrict_push: bool,25 pub restrict_push: bool,
26+ /// Commit status contexts (CI job names such as `ci/test`, or any reported context) that must
27+ /// all be `success` on the pull request head before it can merge.
28+ pub required_checks: Vec<String>,
26 pub created_at: String,29 pub created_at: String,
27 }30 }
28 31
29 /// The settings a rule saves, without its identity.32 /// The settings a rule saves, without its identity.
30-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]33+#[derive(Debug, Clone, Default, PartialEq, Eq)]
31 pub struct RuleFlags {34 pub struct RuleFlags {
32 pub allow_force_push: bool,35 pub allow_force_push: bool,
33 pub allow_deletion: bool,36 pub allow_deletion: bool,
@@ -35,6 +38,7 @@ pub struct RuleFlags {
35 pub block_on_changes_requested: bool,38 pub block_on_changes_requested: bool,
36 pub require_up_to_date: bool,39 pub require_up_to_date: bool,
37 pub restrict_push: bool,40 pub restrict_push: bool,
41+ pub required_checks: Vec<String>,
38 }42 }
39 43
40 impl RuleFlags {44 impl RuleFlags {
@@ -49,7 +53,7 @@ impl RuleFlags {
49 }53 }
50 54
51 /// The settings that apply to one branch. `Default` is the unprotected branch.55 /// The settings that apply to one branch. `Default` is the unprotected branch.
52-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]56+#[derive(Debug, Clone, Default, PartialEq, Eq)]
53 pub struct Protection {57 pub struct Protection {
54 pub allow_force_push: bool,58 pub allow_force_push: bool,
55 pub allow_deletion: bool,59 pub allow_deletion: bool,
@@ -57,6 +61,7 @@ pub struct Protection {
57 pub block_on_changes_requested: bool,61 pub block_on_changes_requested: bool,
58 pub require_up_to_date: bool,62 pub require_up_to_date: bool,
59 pub restrict_push: bool,63 pub restrict_push: bool,
64+ pub required_checks: Vec<String>,
60 }65 }
61 66
62 /// Rejects `required_approvals` above `MAX_REQUIRED_APPROVALS`.67 /// Rejects `required_approvals` above `MAX_REQUIRED_APPROVALS`.
@@ -69,6 +74,34 @@ pub fn validate_required_approvals(n: u32) -> Result<()> {
69 Ok(())74 Ok(())
70 }75 }
71 76
77+/// Most required check contexts on one rule.
78+pub const MAX_REQUIRED_CHECKS: usize = 50;
79+/// Longest accepted check context, in bytes.
80+pub const MAX_CHECK_CONTEXT_BYTES: usize = 200;
81+
82+/// Trims, drops blanks and duplicates (keeping first-seen order) and validates the contexts.
83+pub fn normalize_required_checks(raw: &[String]) -> Result<Vec<String>> {
84+ let mut out: Vec<String> = Vec::new();
85+ for item in raw {
86+ let item = item.trim();
87+ if item.is_empty() || out.iter().any(|c| c == item) {
88+ continue;
89+ }
90+ if item.len() > MAX_CHECK_CONTEXT_BYTES || item.chars().any(char::is_control) {
91+ return Err(Error::Invalid(format!(
92+ "a required check is longer than {MAX_CHECK_CONTEXT_BYTES} bytes or has control characters"
93+ )));
94+ }
95+ out.push(item.to_owned());
96+ }
97+ if out.len() > MAX_REQUIRED_CHECKS {
98+ return Err(Error::Invalid(format!(
99+ "at most {MAX_REQUIRED_CHECKS} required checks per rule"
100+ )));
101+ }
102+ Ok(out)
103+}
104+
72 /// Pattern syntax: a literal branch name, `*` matches any run of chars except `/`, `**` matches anything105 /// Pattern syntax: a literal branch name, `*` matches any run of chars except `/`, `**` matches anything
73 /// including `/`. Max 200 bytes, it must be a valid branch name otherwise (no `..`, no leading `-`, no106 /// including `/`. Max 200 bytes, it must be a valid branch name otherwise (no `..`, no leading `-`, no
74 /// control or space chars, no `~^:?[\`). The pattern must not include the `refs/heads/` prefix.107 /// 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
202 block_on_changes_requested: rule.block_on_changes_requested,235 block_on_changes_requested: rule.block_on_changes_requested,
203 require_up_to_date: rule.require_up_to_date,236 require_up_to_date: rule.require_up_to_date,
204 restrict_push: rule.restrict_push,237 restrict_push: rule.restrict_push,
238+ required_checks: rule.required_checks.clone(),
205 };239 };
206 }240 }
207 if branch == default_branch {241 if branch == default_branch {
@@ -234,6 +268,7 @@ mod tests {
234 block_on_changes_requested: false,268 block_on_changes_requested: false,
235 require_up_to_date: false,269 require_up_to_date: false,
236 restrict_push: false,270 restrict_push: false,
271+ required_checks: Vec::new(),
237 created_at: created.into(),272 created_at: created.into(),
238 }273 }
239 }274 }
@@ -346,6 +381,7 @@ mod tests {
346 block_on_changes_requested: true,381 block_on_changes_requested: true,
347 require_up_to_date: true,382 require_up_to_date: true,
348 restrict_push: true,383 restrict_push: true,
384+ required_checks: Vec::new(),
349 }385 }
350 );386 );
351 // Unprotected and built-in default branches carry no merge rules.387 // Unprotected and built-in default branches carry no merge rules.
@@ -370,4 +406,31 @@ mod tests {
370 );406 );
371 }407 }
372 }408 }
409+
410+ #[test]
411+ fn normalize_required_checks_trims_dedupes_and_validates() {
412+ let raw = vec![
413+ " ci/test ".to_owned(),
414+ String::new(),
415+ "lint".to_owned(),
416+ "ci/test".to_owned(),
417+ ];
418+ assert_eq!(
419+ normalize_required_checks(&raw).unwrap(),
420+ ["ci/test", "lint"]
421+ );
422+ assert!(normalize_required_checks(&["a\tb".to_owned()]).is_err());
423+ assert!(normalize_required_checks(&["x".repeat(MAX_CHECK_CONTEXT_BYTES + 1)]).is_err());
424+ let many: Vec<String> = (0..=MAX_REQUIRED_CHECKS).map(|i| format!("c{i}")).collect();
425+ assert!(normalize_required_checks(&many).is_err());
426+ }
427+
428+ #[test]
429+ fn effective_carries_required_checks() {
430+ let mut r = rule("main", false, false, "2024-01-01");
431+ r.required_checks = vec!["ci/test".into()];
432+ let got = effective(&[r], "main", "main");
433+ assert_eq!(got.required_checks, ["ci/test"]);
434+ assert!(effective(&[], "main", "main").required_checks.is_empty());
435+ }
373 }436 }
crates/forge-core/src/pulls.rsmodified+16 -1
@@ -61,6 +61,17 @@ pub struct PullRequest {
61 pub merged_at: Option<String>,61 pub merged_at: Option<String>,
62 pub merged_by: Option<Id>,62 pub merged_by: Option<Id>,
63 pub merge_commit: Option<String>,63 pub merge_commit: Option<String>,
64+ /// A draft cannot be merged and does not notify reviewers until marked ready.
65+ pub draft: bool,
66+ /// Set while auto-merge is enabled.
67+ pub auto_merge: Option<AutoMerge>,
68+}
69+
70+/// Auto-merge settings: the merge runs as `user_id` with `style` once the merge gate passes.
71+#[derive(Debug, Clone, PartialEq, Eq)]
72+pub struct AutoMerge {
73+ pub style: MergeStyle,
74+ pub user_id: Id,
64 }75 }
65 76
66 /// How a pull request is merged into its base branch.77 /// How a pull request is merged into its base branch.
@@ -69,6 +80,7 @@ pub enum MergeStyle {
69 Merge,80 Merge,
70 Squash,81 Squash,
71 FastForward,82 FastForward,
83+ Rebase,
72 }84 }
73 85
74 impl MergeStyle {86 impl MergeStyle {
@@ -78,6 +90,7 @@ impl MergeStyle {
78 MergeStyle::Merge => "merge",90 MergeStyle::Merge => "merge",
79 MergeStyle::Squash => "squash",91 MergeStyle::Squash => "squash",
80 MergeStyle::FastForward => "ff",92 MergeStyle::FastForward => "ff",
93+ MergeStyle::Rebase => "rebase",
81 }94 }
82 }95 }
83 }96 }
@@ -90,6 +103,7 @@ impl std::str::FromStr for MergeStyle {
90 "merge" => Ok(MergeStyle::Merge),103 "merge" => Ok(MergeStyle::Merge),
91 "squash" => Ok(MergeStyle::Squash),104 "squash" => Ok(MergeStyle::Squash),
92 "ff" => Ok(MergeStyle::FastForward),105 "ff" => Ok(MergeStyle::FastForward),
106+ "rebase" => Ok(MergeStyle::Rebase),
93 other => Err(Error::Invalid(format!("merge style {other:?}"))),107 other => Err(Error::Invalid(format!("merge style {other:?}"))),
94 }108 }
95 }109 }
@@ -119,10 +133,11 @@ mod tests {
119 MergeStyle::Merge,133 MergeStyle::Merge,
120 MergeStyle::Squash,134 MergeStyle::Squash,
121 MergeStyle::FastForward,135 MergeStyle::FastForward,
136+ MergeStyle::Rebase,
122 ] {137 ] {
123 assert_eq!(s.as_str().parse::<MergeStyle>().ok(), Some(s));138 assert_eq!(s.as_str().parse::<MergeStyle>().ok(), Some(s));
124 }139 }
125 assert_eq!(MergeStyle::FastForward.as_str(), "ff");140 assert_eq!(MergeStyle::FastForward.as_str(), "ff");
126- assert!("rebase".parse::<MergeStyle>().is_err());141+ assert!("octopus".parse::<MergeStyle>().is_err());
127 }142 }
128 }143 }
crates/forge-core/src/store/commit_status.rsmodified+14 -0
@@ -230,6 +230,20 @@ impl Store {
230 .await230 .await
231 }231 }
232 232
233+ /// Distinct status contexts seen in the repo, most recently reported first. Feeds the
234+ /// required-checks picker in branch protection.
235+ pub async fn recent_status_contexts(&self, repo_id: &str, limit: u32) -> Result<Vec<String>> {
236+ let conn = self.read_conn().await;
237+ fetch_all(
238+ &conn,
239+ "SELECT context FROM commit_statuses WHERE repo_id = ?1 GROUP BY context \
240+ ORDER BY MAX(updated_at) DESC, context LIMIT ?2",
241+ (repo_id.to_string(), i64::from(limit)),
242+ |row| col_text(row, 0),
243+ )
244+ .await
245+ }
246+
233 /// The combined state of one commit, or `None` when it has no statuses.247 /// The combined state of one commit, or `None` when it has no statuses.
234 pub async fn combined_state(&self, repo_id: &str, sha: &str) -> Result<Option<StatusState>> {248 pub async fn combined_state(&self, repo_id: &str, sha: &str) -> Result<Option<StatusState>> {
235 let statuses = self.statuses_for(repo_id, sha).await?;249 let statuses = self.statuses_for(repo_id, sha).await?;
crates/forge-core/src/store/issues.rsmodified+13 -0
@@ -40,6 +40,10 @@ const EVENT_KINDS: &[&str] = &[
40 "head_deleted",40 "head_deleted",
41 "head_ref_deleted",41 "head_ref_deleted",
42 "head_ref_restored",42 "head_ref_restored",
43+ "ready_for_review",
44+ "converted_to_draft",
45+ "auto_merge_enabled",
46+ "auto_merge_disabled",
43 // Pull request reviews (store/reviews.rs).47 // Pull request reviews (store/reviews.rs).
44 "review_dismissed",48 "review_dismissed",
45 "thread_resolved",49 "thread_resolved",
@@ -394,6 +398,15 @@ impl Store {
394 clauses.push("i.title LIKE ? ESCAPE '\\'");398 clauses.push("i.title LIKE ? ESCAPE '\\'");
395 params.push(Value::Text(like_pattern(query)));399 params.push(Value::Text(like_pattern(query)));
396 }400 }
401+ if let (true, Some(draft)) = (kind == "pull", f.draft) {
402+ {
403+ clauses.push(if draft {
404+ "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 1)"
405+ } else {
406+ "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 0)"
407+ });
408+ }
409+ }
397 let where_sql = clauses.join(" AND ");410 let where_sql = clauses.join(" AND ");
398 let order = match f.sort {411 let order = match f.sort {
399 IssueSort::Newest => "i.number DESC",412 IssueSort::Newest => "i.number DESC",
crates/forge-core/src/store/migrate.rsmodified+8 -0
@@ -72,6 +72,14 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
72 include_str!("../../migrations/0046_server_settings.sql"),72 include_str!("../../migrations/0046_server_settings.sql"),
73 ),73 ),
74 (50, include_str!("../../migrations/0050_run_warnings.sql")),74 (50, include_str!("../../migrations/0050_run_warnings.sql")),
75+ (
76+ 52,
77+ include_str!("../../migrations/0052_pull_draft_automerge.sql"),
78+ ),
79+ (
80+ 53,
81+ include_str!("../../migrations/0053_required_checks.sql"),
82+ ),
75 ];83 ];
76 84
77 /// The highest migration version this binary knows about.85 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+100 -5
@@ -1230,7 +1230,7 @@ impl Store {
1230 }1230 }
1231 1231
1232 const BRANCH_RULE_COLS: &str = "id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \1232 const BRANCH_RULE_COLS: &str = "id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \
1233- required_approvals, block_on_changes_requested, require_up_to_date, restrict_push";1233+ required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks";
1234 1234
1235 // branch protection1235 // branch protection
1236 impl Store {1236 impl Store {
@@ -1258,15 +1258,19 @@ impl Store {
1258 ) -> Result<BranchRule> {1258 ) -> Result<BranchRule> {
1259 crate::protection::validate_pattern(pattern)?;1259 crate::protection::validate_pattern(pattern)?;
1260 validate_required_approvals(flags.required_approvals)?;1260 validate_required_approvals(flags.required_approvals)?;
1261+ let checks = crate::protection::normalize_required_checks(&flags.required_checks)?;
1262+ let checks_json =
1263+ serde_json::to_string(&checks).map_err(|e| Error::Database(e.to_string()))?;
1261 let conn = self.inner.conn.lock().await;1264 let conn = self.inner.conn.lock().await;
1262 conn.execute(1265 conn.execute(
1263 "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \1266 "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \
1264- required_approvals, block_on_changes_requested, require_up_to_date, restrict_push) \1267+ required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks) \
1265- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) \1268+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) \
1266 ON CONFLICT(repo_id, pattern) DO UPDATE SET allow_force_push = excluded.allow_force_push, \1269 ON CONFLICT(repo_id, pattern) DO UPDATE SET allow_force_push = excluded.allow_force_push, \
1267 allow_deletion = excluded.allow_deletion, required_approvals = excluded.required_approvals, \1270 allow_deletion = excluded.allow_deletion, required_approvals = excluded.required_approvals, \
1268 block_on_changes_requested = excluded.block_on_changes_requested, \1271 block_on_changes_requested = excluded.block_on_changes_requested, \
1269- require_up_to_date = excluded.require_up_to_date, restrict_push = excluded.restrict_push",1272+ require_up_to_date = excluded.require_up_to_date, restrict_push = excluded.restrict_push, \
1273+ required_checks = excluded.required_checks",
1270 (1274 (
1271 new_id(),1275 new_id(),
1272 repo_id.to_string(),1276 repo_id.to_string(),
@@ -1278,6 +1282,7 @@ impl Store {
1278 i64::from(flags.block_on_changes_requested),1282 i64::from(flags.block_on_changes_requested),
1279 i64::from(flags.require_up_to_date),1283 i64::from(flags.require_up_to_date),
1280 i64::from(flags.restrict_push),1284 i64::from(flags.restrict_push),
1285+ checks_json,
1281 ),1286 ),
1282 )1287 )
1283 .await1288 .await
@@ -1324,6 +1329,8 @@ fn map_branch_rule(row: &Row) -> Result<BranchRule> {
1324 block_on_changes_requested: col_bool(row, 7)?,1329 block_on_changes_requested: col_bool(row, 7)?,
1325 require_up_to_date: col_bool(row, 8)?,1330 require_up_to_date: col_bool(row, 8)?,
1326 restrict_push: col_bool(row, 9)?,1331 restrict_push: col_bool(row, 9)?,
1332+ required_checks: serde_json::from_str(&col_text(row, 10)?)
1333+ .map_err(|e| Error::Database(format!("required_checks is not a JSON array: {e}")))?,
1327 })1334 })
1328 }1335 }
1329 1336
@@ -2020,6 +2027,93 @@ mod tests {
2020 ));2027 ));
2021 }2028 }
2022 2029
2030+ #[tokio::test]
2031+ async fn branch_rule_required_checks_round_trip_and_normalise() {
2032+ let dir = tempfile::tempdir().unwrap();
2033+ let (store, owner) = store_with_user(&dir).await;
2034+ let repo = store
2035+ .create_repo(&owner.id, "proj", "", Visibility::Public, "main")
2036+ .await
2037+ .unwrap();
2038+ let flags = RuleFlags {
2039+ required_checks: vec![
2040+ " ci/test ".into(),
2041+ "lint".into(),
2042+ "ci/test".into(),
2043+ " ".into(),
2044+ ],
2045+ ..RuleFlags::default()
2046+ };
2047+ let rule = store
2048+ .upsert_branch_rule(&repo.id, "main", flags)
2049+ .await
2050+ .unwrap();
2051+ assert_eq!(rule.required_checks, vec!["ci/test", "lint"]);
2052+ assert_eq!(
2053+ store.list_branch_rules(&repo.id).await.unwrap()[0].required_checks,
2054+ vec!["ci/test", "lint"]
2055+ );
2056+
2057+ // Saving without checks clears them; a control character is refused.
2058+ let cleared = store
2059+ .upsert_branch_rule(&repo.id, "main", RuleFlags::default())
2060+ .await
2061+ .unwrap();
2062+ assert!(cleared.required_checks.is_empty());
2063+ let bad = RuleFlags {
2064+ required_checks: vec!["a\nb".into()],
2065+ ..RuleFlags::default()
2066+ };
2067+ assert!(matches!(
2068+ store.upsert_branch_rule(&repo.id, "main", bad).await,
2069+ Err(Error::Invalid(_))
2070+ ));
2071+ }
2072+
2073+ #[tokio::test]
2074+ async fn recent_status_contexts_are_distinct_and_newest_first() {
2075+ let dir = tempfile::tempdir().unwrap();
2076+ let (store, owner) = store_with_user(&dir).await;
2077+ let repo = store
2078+ .create_repo(&owner.id, "proj", "", Visibility::Public, "main")
2079+ .await
2080+ .unwrap();
2081+ let sha_a = "a".repeat(40);
2082+ let sha_b = "b".repeat(40);
2083+ for (sha, context) in [(&sha_a, "ci/test"), (&sha_b, "ci/test"), (&sha_a, "lint")] {
2084+ store
2085+ .set_status(
2086+ &repo.id,
2087+ sha,
2088+ context,
2089+ crate::store::commit_status::StatusState::Success,
2090+ None,
2091+ None,
2092+ &owner.id,
2093+ )
2094+ .await
2095+ .unwrap();
2096+ }
2097+ let mut seen = store.recent_status_contexts(&repo.id, 10).await.unwrap();
2098+ seen.sort();
2099+ assert_eq!(seen, vec!["ci/test", "lint"]);
2100+ assert_eq!(
2101+ store
2102+ .recent_status_contexts(&repo.id, 1)
2103+ .await
2104+ .unwrap()
2105+ .len(),
2106+ 1
2107+ );
2108+ assert!(
2109+ store
2110+ .recent_status_contexts("nope", 10)
2111+ .await
2112+ .unwrap()
2113+ .is_empty()
2114+ );
2115+ }
2116+
2023 #[tokio::test]2117 #[tokio::test]
2024 async fn branch_rules_list_upsert_and_update() {2118 async fn branch_rules_list_upsert_and_update() {
2025 let dir = tempfile::tempdir().unwrap();2119 let dir = tempfile::tempdir().unwrap();
@@ -2077,9 +2171,10 @@ mod tests {
2077 block_on_changes_requested: true,2171 block_on_changes_requested: true,
2078 require_up_to_date: true,2172 require_up_to_date: true,
2079 restrict_push: true,2173 restrict_push: true,
2174+ required_checks: Vec::new(),
2080 };2175 };
2081 let saved = store2176 let saved = store
2082- .upsert_branch_rule(&repo.id, "main", flags)2177+ .upsert_branch_rule(&repo.id, "main", flags.clone())
2083 .await2178 .await
2084 .unwrap();2179 .unwrap();
2085 assert_eq!(saved.required_approvals, 20);2180 assert_eq!(saved.required_approvals, 20);
crates/forge-core/src/store/pulls.rsmodified+313 -5
@@ -13,15 +13,15 @@ use super::{
13 use crate::error::{Error, Result};13 use crate::error::{Error, Result};
14 use crate::issues::{Issue, IssueFilter, IssueListItem, IssueState, validate_body, validate_title};14 use crate::issues::{Issue, IssueFilter, IssueListItem, IssueState, validate_body, validate_title};
15 use crate::model::{Id, Repo};15 use crate::model::{Id, Repo};
16-use crate::pulls::{Mergeable, PullRequest};16+use crate::pulls::{AutoMerge, MergeStyle, Mergeable, PullRequest};
17 use crate::time::now_stamp;17 use crate::time::now_stamp;
18 18
19-/// The issue columns (0 to 14) followed by the `pull_requests` columns (15 to 25).19+/// The issue columns (0 to 14) followed by the `pull_requests` columns (15 to 28).
20 const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i.state_reason, \20 const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i.state_reason, \
21 i.author_id, i.milestone_id, i.comment_count, i.created_at, i.updated_at, \21 i.author_id, i.milestone_id, i.comment_count, i.created_at, i.updated_at, \
22 i.closed_at, i.locked, i.lock_reason, p.base_branch, p.head_repo_id, p.head_branch, p.head_oid, \22 i.closed_at, i.locked, i.lock_reason, p.base_branch, p.head_repo_id, p.head_branch, p.head_oid, \
23 p.base_oid, p.merge_base, p.mergeable, p.conflict_files, p.merged_at, \23 p.base_oid, p.merge_base, p.mergeable, p.conflict_files, p.merged_at, \
24- p.merged_by, p.merge_commit";24+ p.merged_by, p.merge_commit, p.draft, p.auto_merge_style, p.auto_merge_user";
25 25
26 const MERGED_MSG: &str = "pull request is already merged";26 const MERGED_MSG: &str = "pull request is already merged";
27 27
@@ -43,6 +43,14 @@ fn map_pull(row: &Row) -> Result<PullRequest> {
43 merged_at: col_opt_text(row, 23)?,43 merged_at: col_opt_text(row, 23)?,
44 merged_by: col_opt_text(row, 24)?,44 merged_by: col_opt_text(row, 24)?,
45 merge_commit: col_opt_text(row, 25)?,45 merge_commit: col_opt_text(row, 25)?,
46+ draft: col_int(row, 26)? != 0,
47+ auto_merge: match (col_opt_text(row, 27)?, col_opt_text(row, 28)?) {
48+ (Some(style), Some(user_id)) => Some(AutoMerge {
49+ style: parse_db(&style)?,
50+ user_id,
51+ }),
52+ _ => None,
53+ },
46 })54 })
47 }55 }
48 56
@@ -187,6 +195,8 @@ impl Store {
187 merged_at: None,195 merged_at: None,
188 merged_by: None,196 merged_by: None,
189 merge_commit: None,197 merge_commit: None,
198+ draft: false,
199+ auto_merge: None,
190 })200 })
191 }201 }
192 .await;202 .await;
@@ -267,7 +277,8 @@ impl Store {
267 let changed = conn277 let changed = conn
268 .execute(278 .execute(
269 "UPDATE pull_requests SET head_oid = ?2, merge_base = NULL, mergeable = 'unknown', \279 "UPDATE pull_requests SET head_oid = ?2, merge_base = NULL, mergeable = 'unknown', \
270- conflict_files = '[]' WHERE issue_id = ?1",280+ conflict_files = '[]', auto_merge_style = NULL, auto_merge_user = NULL \
281+ WHERE issue_id = ?1",
271 (issue_id.to_string(), head_oid.to_string()),282 (issue_id.to_string(), head_oid.to_string()),
272 )283 )
273 .await284 .await
@@ -324,6 +335,135 @@ impl Store {
324 Ok(())335 Ok(())
325 }336 }
326 337
338+ /// Sets or clears the draft flag of an open pull request and records a `ready_for_review` or
339+ /// `converted_to_draft` event. Returns whether the flag changed. A merged or closed pull
340+ /// request is `Conflict`. Turning a pull request into a draft also disables auto-merge.
341+ pub async fn set_pull_draft(
342+ &self,
343+ issue_id: &str,
344+ actor_id: Option<&str>,
345+ draft: bool,
346+ ) -> Result<bool> {
347+ let conn = self.inner.conn.lock().await;
348+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
349+ let outcome: Result<bool> = async {
350+ let current = load_pull(&tx, issue_id).await?;
351+ if current.merged_at.is_some() {
352+ return Err(Error::Conflict(MERGED_MSG.into()));
353+ }
354+ if current.issue.state == IssueState::Closed {
355+ return Err(Error::Conflict("pull request is closed".into()));
356+ }
357+ if current.draft == draft {
358+ return Ok(false);
359+ }
360+ tx.execute(
361+ "UPDATE pull_requests SET draft = ?2, auto_merge_style = CASE WHEN ?2 = 1 THEN NULL \
362+ ELSE auto_merge_style END, auto_merge_user = CASE WHEN ?2 = 1 THEN NULL \
363+ ELSE auto_merge_user END WHERE issue_id = ?1",
364+ (issue_id.to_string(), i64::from(draft)),
365+ )
366+ .await
367+ .map_err(db_err)?;
368+ let kind = if draft {
369+ "converted_to_draft"
370+ } else {
371+ "ready_for_review"
372+ };
373+ insert_event(&tx, issue_id, actor_id, kind, &serde_json::json!({})).await?;
374+ Ok(true)
375+ }
376+ .await;
377+ finish(tx, outcome).await
378+ }
379+
380+ /// Enables auto-merge for an open, unmerged pull request: the merge will run as `user_id`
381+ /// with `style`. Records an `auto_merge_enabled` event.
382+ pub async fn enable_auto_merge(
383+ &self,
384+ issue_id: &str,
385+ user_id: &str,
386+ style: MergeStyle,
387+ ) -> Result<()> {
388+ let conn = self.inner.conn.lock().await;
389+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
390+ let outcome: Result<()> = async {
391+ let current = load_pull(&tx, issue_id).await?;
392+ if current.merged_at.is_some() {
393+ return Err(Error::Conflict(MERGED_MSG.into()));
394+ }
395+ if current.issue.state == IssueState::Closed {
396+ return Err(Error::Conflict("pull request is closed".into()));
397+ }
398+ tx.execute(
399+ "UPDATE pull_requests SET auto_merge_style = ?2, auto_merge_user = ?3 \
400+ WHERE issue_id = ?1",
401+ (
402+ issue_id.to_string(),
403+ style.as_str().to_string(),
404+ user_id.to_string(),
405+ ),
406+ )
407+ .await
408+ .map_err(db_err)?;
409+ let data = serde_json::json!({ "style": style.as_str() });
410+ insert_event(&tx, issue_id, Some(user_id), "auto_merge_enabled", &data).await?;
411+ Ok(())
412+ }
413+ .await;
414+ finish(tx, outcome).await
415+ }
416+
417+ /// Disables auto-merge and records an `auto_merge_disabled` event with `reason` (a short
418+ /// machine word such as `manual`, `push` or `refused`). Returns whether it was enabled.
419+ pub async fn disable_auto_merge(
420+ &self,
421+ issue_id: &str,
422+ actor_id: Option<&str>,
423+ reason: &str,
424+ ) -> Result<bool> {
425+ let conn = self.inner.conn.lock().await;
426+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
427+ let outcome: Result<bool> = async {
428+ let changed = tx
429+ .execute(
430+ "UPDATE pull_requests SET auto_merge_style = NULL, auto_merge_user = NULL \
431+ WHERE issue_id = ?1 AND auto_merge_style IS NOT NULL",
432+ (issue_id.to_string(),),
433+ )
434+ .await
435+ .map_err(db_err)?;
436+ if changed == 0 {
437+ return Ok(false);
438+ }
439+ let data = serde_json::json!({ "reason": reason });
440+ insert_event(&tx, issue_id, actor_id, "auto_merge_disabled", &data).await?;
441+ Ok(true)
442+ }
443+ .await;
444+ finish(tx, outcome).await
445+ }
446+
447+ /// Open pull requests of this base repo with auto-merge enabled whose head is `sha`.
448+ pub async fn auto_merge_pulls_for_head(
449+ &self,
450+ repo_id: &str,
451+ sha: &str,
452+ ) -> Result<Vec<PullRequest>> {
453+ let conn = self.read_conn().await;
454+ fetch_all(
455+ &conn,
456+ &format!(
457+ "SELECT {PULL_COLS} FROM issues i JOIN pull_requests p ON p.issue_id = i.id \
458+ WHERE i.repo_id = ?1 AND p.head_oid = ?2 AND i.state = 'open' AND i.kind = 'pull' \
459+ AND p.auto_merge_style IS NOT NULL ORDER BY i.number"
460+ ),
461+ (repo_id.to_string(), sha.to_string()),
462+ map_pull,
463+ )
464+ .await
465+ }
466+
327 /// Marks a pull request merged. It closes the issue with reason `completed`, sets the merge467 /// Marks a pull request merged. It closes the issue with reason `completed`, sets the merge
328 /// fields and records a `merged` event with `{"commit": merge_commit}`. Fails with `Conflict`468 /// fields and records a `merged` event with `{"commit": merge_commit}`. Fails with `Conflict`
329 /// if it is already merged or closed, and with `NotFound` if `issue_id` is not a pull request.469 /// if it is already merged or closed, and with `NotFound` if `issue_id` is not a pull request.
@@ -353,7 +493,8 @@ impl Store {
353 .map_err(db_err)?;493 .map_err(db_err)?;
354 tx.execute(494 tx.execute(
355 "UPDATE pull_requests SET merged_at = ?2, merged_by = ?3, merge_commit = ?4, \495 "UPDATE pull_requests SET merged_at = ?2, merged_by = ?3, merge_commit = ?4, \
356- mergeable = 'merged', conflict_files = '[]' WHERE issue_id = ?1",496+ mergeable = 'merged', conflict_files = '[]', auto_merge_style = NULL, \
497+ auto_merge_user = NULL WHERE issue_id = ?1",
357 (498 (
358 issue_id.to_string(),499 issue_id.to_string(),
359 now,500 now,
@@ -1044,4 +1185,171 @@ mod tests {
1044 .collect();1185 .collect();
1045 assert_eq!(kinds, vec!["head_updated", "base_changed", "head_deleted"]);1186 assert_eq!(kinds, vec!["head_updated", "base_changed", "head_deleted"]);
1046 }1187 }
1188+
1189+ #[tokio::test]
1190+ async fn draft_flag_round_trips_with_events_and_list_filter() {
1191+ let fx = fixture().await;
1192+ let pr = open_pull(&fx, &fx.repo.id, "feature", "wip").await;
1193+ let _ready = open_pull(&fx, &fx.repo.id, "other", "ready").await;
1194+ assert!(!pr.draft);
1195+
1196+ assert!(
1197+ fx.store
1198+ .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), true)
1199+ .await
1200+ .unwrap()
1201+ );
1202+ // Setting the same value again changes nothing and records no event.
1203+ assert!(
1204+ !fx.store
1205+ .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), true)
1206+ .await
1207+ .unwrap()
1208+ );
1209+ let got = fx
1210+ .store
1211+ .pull_by_number(&fx.repo.id, pr.issue.number)
1212+ .await
1213+ .unwrap()
1214+ .unwrap();
1215+ assert!(got.draft);
1216+
1217+ let only = |draft: Option<bool>| IssueFilter {
1218+ state: None,
1219+ draft,
1220+ ..IssueFilter::default()
1221+ };
1222+ let (items, total) = fx
1223+ .store
1224+ .list_pulls(&fx.repo.id, &only(Some(true)))
1225+ .await
1226+ .unwrap();
1227+ assert_eq!((total, items[0].issue.number), (1, pr.issue.number));
1228+ let (_, total) = fx
1229+ .store
1230+ .list_pulls(&fx.repo.id, &only(Some(false)))
1231+ .await
1232+ .unwrap();
1233+ assert_eq!(total, 1);
1234+ let (_, total) = fx.store.list_pulls(&fx.repo.id, &only(None)).await.unwrap();
1235+ assert_eq!(total, 2);
1236+ let numbers = [pr.issue.number, pr.issue.number + 1];
1237+ let drafts = fx.store.draft_numbers(&fx.repo.id, &numbers).await.unwrap();
1238+ assert_eq!(drafts.len(), 1);
1239+ assert!(drafts.contains(&pr.issue.number));
1240+
1241+ assert!(
1242+ fx.store
1243+ .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), false)
1244+ .await
1245+ .unwrap()
1246+ );
1247+ let kinds: Vec<String> = fx
1248+ .store
1249+ .list_events(&pr.issue.id)
1250+ .await
1251+ .unwrap()
1252+ .into_iter()
1253+ .map(|e| e.kind)
1254+ .collect();
1255+ assert_eq!(kinds, vec!["converted_to_draft", "ready_for_review"]);
1256+ }
1257+
1258+ #[tokio::test]
1259+ async fn auto_merge_is_stored_and_cleared_by_push_draft_and_merge() {
1260+ let fx = fixture().await;
1261+ let pr = open_pull(&fx, &fx.repo.id, "feature", "auto").await;
1262+ let head = "a".repeat(40);
1263+ let load = || async {
1264+ fx.store
1265+ .pull_by_number(&fx.repo.id, pr.issue.number)
1266+ .await
1267+ .unwrap()
1268+ .unwrap()
1269+ };
1270+ assert!(load().await.auto_merge.is_none());
1271+ assert!(
1272+ !fx.store
1273+ .disable_auto_merge(&pr.issue.id, None, "manual")
1274+ .await
1275+ .unwrap()
1276+ );
1277+
1278+ fx.store
1279+ .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Rebase)
1280+ .await
1281+ .unwrap();
1282+ let auto = load().await.auto_merge.expect("enabled");
1283+ assert_eq!(
1284+ (auto.style, auto.user_id.as_str()),
1285+ (MergeStyle::Rebase, fx.bob.id.as_str())
1286+ );
1287+ let found = fx
1288+ .store
1289+ .auto_merge_pulls_for_head(&fx.repo.id, &head)
1290+ .await
1291+ .unwrap();
1292+ assert_eq!(found.len(), 1);
1293+ assert!(
1294+ fx.store
1295+ .auto_merge_pulls_for_head(&fx.repo.id, &"d".repeat(40))
1296+ .await
1297+ .unwrap()
1298+ .is_empty()
1299+ );
1300+
1301+ // A new head clears it.
1302+ fx.store
1303+ .update_pull_head(&pr.issue.id, &"b".repeat(40))
1304+ .await
1305+ .unwrap();
1306+ assert!(load().await.auto_merge.is_none());
1307+
1308+ // Converting to a draft clears it.
1309+ fx.store
1310+ .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Merge)
1311+ .await
1312+ .unwrap();
1313+ fx.store
1314+ .set_pull_draft(&pr.issue.id, None, true)
1315+ .await
1316+ .unwrap();
1317+ assert!(load().await.auto_merge.is_none());
1318+
1319+ // Disabling records why; merging clears it.
1320+ fx.store
1321+ .set_pull_draft(&pr.issue.id, None, false)
1322+ .await
1323+ .unwrap();
1324+ fx.store
1325+ .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Squash)
1326+ .await
1327+ .unwrap();
1328+ assert!(
1329+ fx.store
1330+ .disable_auto_merge(&pr.issue.id, Some(&fx.bob.id), "refused")
1331+ .await
1332+ .unwrap()
1333+ );
1334+ let events = fx.store.list_events(&pr.issue.id).await.unwrap();
1335+ let last = events.last().unwrap();
1336+ assert_eq!(last.kind, "auto_merge_disabled");
1337+ assert_eq!(last.data["reason"], "refused");
1338+
1339+ fx.store
1340+ .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Squash)
1341+ .await
1342+ .unwrap();
1343+ fx.store
1344+ .mark_merged(&pr.issue.id, &fx.bob.id, &"c".repeat(40))
1345+ .await
1346+ .unwrap();
1347+ assert!(load().await.auto_merge.is_none());
1348+ assert!(
1349+ fx.store
1350+ .enable_auto_merge(&pr.issue.id, &fx.bob.id, MergeStyle::Merge)
1351+ .await
1352+ .is_err()
1353+ );
1354+ }
1047 }1355 }
crates/forge-core/src/store/pulls_list_extra.rsmodified+19 -0
@@ -8,6 +8,25 @@ use super::{Store, col_int, fetch_all};
8 use crate::error::Result;8 use crate::error::Result;
9 9
10 impl Store {10 impl Store {
11+ /// Which of `numbers` are draft pull requests of this repo.
12+ pub async fn draft_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {
13+ if numbers.is_empty() {
14+ return Ok(HashSet::new());
15+ }
16+ let placeholders: Vec<String> = (2..=numbers.len() + 1).map(|i| format!("?{i}")).collect();
17+ let sql = format!(
18+ "SELECT i.number FROM pull_requests p JOIN issues i ON i.id = p.issue_id \
19+ WHERE i.repo_id = ?1 AND i.kind = 'pull' AND p.draft = 1 AND i.number IN ({})",
20+ placeholders.join(", ")
21+ );
22+ let mut params: Vec<Value> = Vec::with_capacity(numbers.len() + 1);
23+ params.push(Value::Text(repo_id.to_string()));
24+ params.extend(numbers.iter().map(|n| Value::Integer(*n)));
25+ let conn = self.read_conn().await;
26+ let found = fetch_all(&conn, &sql, params, |row| col_int(row, 0)).await?;
27+ Ok(found.into_iter().collect())
28+ }
29+
11 /// Which of `numbers` are merged pull requests of this repo. Numbers that are issues, open30 /// Which of `numbers` are merged pull requests of this repo. Numbers that are issues, open
12 /// or closed without a merge are left out.31 /// or closed without a merge are left out.
13 pub async fn merged_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {32 pub async fn merged_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {
crates/forge-git/src/pulls.rsmodified+195 -0
@@ -492,6 +492,133 @@ pub async fn range_log_with(
492 new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await492 new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await
493 }493 }
494 494
495+/// Outcome of replaying head commits onto a base tip.
496+#[derive(Debug, Clone, PartialEq, Eq)]
497+pub enum RebaseResult {
498+ /// The commits replay cleanly; `tip` is the new head (the base tip when every commit was
499+ /// already applied) and `count` the number of commits created.
500+ Clean { tip: String, count: usize },
501+ /// A commit does not apply; `commit` is its id and `files` the conflicted paths.
502+ Conflict { commit: String, files: Vec<String> },
503+}
504+
505+/// Replays the commits reachable from `head_oid` but not from `base_oid` onto `base_oid`, oldest
506+/// first, keeping each author and message. The committer is `committer`. Merge commits in the
507+/// range are skipped and a commit whose changes the base already has is dropped. Nothing is
508+/// written but objects: no ref moves.
509+pub async fn rebase_commits(
510+ env: &GitEnv,
511+ repo: &Path,
512+ base_oid: &str,
513+ head_oid: &str,
514+ committer: &Signature,
515+) -> Result<RebaseResult> {
516+ validate_oid(base_oid)?;
517+ validate_oid(head_oid)?;
518+ let negated = format!("^{base_oid}");
519+ let cmd = git(env, "rev-list")
520+ .git_dir(repo)
521+ .arg("--reverse")
522+ .arg("--topo-order")
523+ .arg("--no-merges")
524+ .user_revs(&[head_oid, negated.as_str()])?;
525+ let out = run_raw(cmd, None).await?;
526+ if !out.status.success() {
527+ return Err(failed("rev-list", &out));
528+ }
529+ let commits: Vec<String> = String::from_utf8_lossy(&out.stdout)
530+ .lines()
531+ .map(str::to_owned)
532+ .collect();
533+ let mut tip = base_oid.to_owned();
534+ let mut count = 0usize;
535+ for commit in commits {
536+ validate_oid(&commit)?;
537+ let cmd = git(env, "log")
538+ .git_dir(repo)
539+ .arg("-1")
540+ .arg("--format=%P%x00%an%x00%ae%x00%at%x00%B")
541+ .user_revs(&[commit.as_str()])?;
542+ let out = run_raw(cmd, None).await?;
543+ if !out.status.success() {
544+ return Err(failed("log", &out));
545+ }
546+ let text = String::from_utf8_lossy(&out.stdout).into_owned();
547+ let mut parts = text.splitn(5, '\0');
548+ let parents = parts.next().unwrap_or_default();
549+ let name = parts.next().unwrap_or_default().to_owned();
550+ let email = parts.next().unwrap_or_default().to_owned();
551+ let time_unix = parts
552+ .next()
553+ .and_then(|t| t.trim().parse::<i64>().ok())
554+ .unwrap_or(committer.time_unix);
555+ let message = parts.next().unwrap_or_default().to_owned();
556+ let Some(parent) = parents.split_whitespace().next() else {
557+ return Err(Error::InvalidInput(
558+ "cannot rebase a root commit onto the base".into(),
559+ ));
560+ };
561+ validate_oid(parent)?;
562+ let cmd = git(env, "merge-tree")
563+ .git_dir(repo)
564+ .arg("--write-tree")
565+ .arg("--name-only")
566+ .arg("--no-messages")
567+ .user_opt("--merge-base", parent)?
568+ .user_revs(&[tip.as_str(), commit.as_str()])?;
569+ let out = run_raw(cmd, None).await?;
570+ let text = String::from_utf8_lossy(&out.stdout).into_owned();
571+ let tree = match out.status.code() {
572+ Some(0) => text.lines().next().unwrap_or_default().trim().to_owned(),
573+ Some(1) => {
574+ let mut files: Vec<String> = Vec::new();
575+ for line in text
576+ .lines()
577+ .skip(1)
578+ .map(str::trim)
579+ .filter(|l| !l.is_empty())
580+ {
581+ if !files.iter().any(|f| f == line) {
582+ files.push(line.to_owned());
583+ }
584+ }
585+ return Ok(RebaseResult::Conflict { commit, files });
586+ }
587+ _ => return Err(failed("merge-tree", &out)),
588+ };
589+ validate_oid(&tree)?;
590+ let tip_tree = format!("{tip}^{{tree}}");
591+ let cmd = git(env, "rev-parse")
592+ .git_dir(repo)
593+ .arg("--verify")
594+ .user_revs(&[tip_tree.as_str()])?;
595+ let out = run_raw(cmd, None).await?;
596+ if !out.status.success() {
597+ return Err(failed("rev-parse", &out));
598+ }
599+ if stdout_trimmed(&out) == tree {
600+ continue;
601+ }
602+ let author = Signature {
603+ name,
604+ email,
605+ time_unix,
606+ };
607+ tip = commit_tree(
608+ env,
609+ repo,
610+ &tree,
611+ &[tip.as_str()],
612+ message.trim_end_matches('\n'),
613+ &author,
614+ committer,
615+ )
616+ .await?;
617+ count += 1;
618+ }
619+ Ok(RebaseResult::Clean { tip, count })
620+}
621+
495 #[cfg(test)]622 #[cfg(test)]
496 mod tests {623 mod tests {
497 use super::*;624 use super::*;
@@ -1072,4 +1199,72 @@ mod tests {
1072 .map(|_| ()),1199 .map(|_| ()),
1073 );1200 );
1074 }1201 }
1202+
1203+ #[tokio::test]
1204+ async fn rebase_replays_commits_keeping_authors() {
1205+ let sb = Sandbox::new();
1206+ let env = sb.env();
1207+ let w = sb.repo("repo");
1208+ w.write("a.txt", "1\n");
1209+ w.commit("c0");
1210+ w.git(&["switch", "-q", "-c", "feature"]);
1211+ w.write("b.txt", "one\n");
1212+ w.commit("first");
1213+ w.write("b.txt", "two\n");
1214+ let head = w.commit("second");
1215+ w.git(&["switch", "-q", "main"]);
1216+ w.write("c.txt", "main\n");
1217+ let base = w.commit("main work");
1218+ let gd = w.git_dir();
1219+ let committer = Signature {
1220+ name: "tahinli".into(),
1221+ email: "tahinli@example.com".into(),
1222+ time_unix: 1_700_000_000,
1223+ };
1224+ let (tip, count) = match rebase_commits(&env, &gd, &base, &head, &committer)
1225+ .await
1226+ .expect("rebase")
1227+ {
1228+ RebaseResult::Clean { tip, count } => (tip, count),
1229+ other => panic!("expected clean, got {other:?}"),
1230+ };
1231+ assert_eq!(count, 2);
1232+ assert_eq!(w.git(&["rev-parse", &format!("{tip}~2")]), base);
1233+ assert_eq!(
1234+ w.git(&["log", "-1", "--format=%an|%cn|%s", &tip]),
1235+ "Tester|tahinli|second"
1236+ );
1237+ assert_eq!(w.git(&["show", &format!("{tip}:b.txt")]), "two");
1238+ assert_eq!(w.git(&["show", &format!("{tip}:c.txt")]), "main");
1239+ }
1240+
1241+ #[tokio::test]
1242+ async fn rebase_reports_conflicts() {
1243+ let sb = Sandbox::new();
1244+ let env = sb.env();
1245+ let w = sb.repo("repo");
1246+ w.write("a.txt", "1\n");
1247+ w.commit("c0");
1248+ w.git(&["switch", "-q", "-c", "feature"]);
1249+ w.write("a.txt", "feature\n");
1250+ let head = w.commit("feature edit");
1251+ w.git(&["switch", "-q", "main"]);
1252+ w.write("a.txt", "main\n");
1253+ let base = w.commit("main edit");
1254+ let committer = Signature {
1255+ name: "tahinli".into(),
1256+ email: "tahinli@example.com".into(),
1257+ time_unix: 1_700_000_000,
1258+ };
1259+ match rebase_commits(&env, &w.git_dir(), &base, &head, &committer)
1260+ .await
1261+ .expect("rebase")
1262+ {
1263+ RebaseResult::Conflict { commit, files } => {
1264+ assert_eq!(commit, head);
1265+ assert_eq!(files, vec!["a.txt".to_owned()]);
1266+ }
1267+ other => panic!("expected conflict, got {other:?}"),
1268+ }
1269+ }
1075 }1270 }
crates/forge-web/assets/nav.jsmodified+14 -0
@@ -422,6 +422,20 @@
422 }422 }
423 }, false);423 }, false);
424 424
425+ // Branch rule form: a suggested check context is added to the required checks field.
426+ document.addEventListener('click', function (e) {
427+ var chip = e.target && e.target.closest ? e.target.closest('[data-check-add]') : null;
428+ if (!chip) { return; }
429+ var form = chip.closest('form');
430+ var input = form ? form.querySelector('input[name="required_checks"]') : null;
431+ if (!input) { return; }
432+ e.preventDefault();
433+ var context = chip.getAttribute('data-check-add') || '';
434+ var parts = input.value.split(/[,\n]/).map(function (p) { return p.trim(); }).filter(Boolean);
435+ if (parts.indexOf(context) < 0) { parts.push(context); }
436+ input.value = parts.join(', ');
437+ }, false);
438+
425 document.addEventListener('click', function (e) {439 document.addEventListener('click', function (e) {
426 if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; }440 if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; }
427 var a = e.target && e.target.closest ? e.target.closest('a[href]') : null;441 var a = e.target && e.target.closest ? e.target.closest('a[href]') : null;
crates/forge-web/src/api/statuses.rsmodified+1 -0
@@ -107,6 +107,7 @@ async fn report_status(cx: &Cx, body: Body) -> topcoat::Result<Response> {
107 }107 }
108 Err(e) => return Ok(*api::internal(e)),108 Err(e) => return Ok(*api::internal(e)),
109 };109 };
110+ crate::automerge::on_status(state, &repo.id, &sha).await;
110 Ok(api::json(StatusCode::CREATED, &status_json(&saved)))111 Ok(api::json(StatusCode::CREATED, &status_json(&saved)))
111 }112 }
112 113
crates/forge-web/src/automerge.rsadded+105 -0
@@ -0,0 +1,105 @@
1+//! Auto-merge: a pull request with auto-merge enabled merges by itself, as the user who enabled
2+//! it, the moment its merge gate passes.
3+//!
4+//! The gate (`pulls_merge::merge_gate`) is re-evaluated whenever something that can clear it
5+//! arrives: a commit status (the token API, CI job completion) or a review. A new push to the head
6+//! branch disables auto-merge (see `pulls_sync`). Nothing here polls; every call is a reaction to
7+//! an event.
8+
9+use forge_core::{Action, IssueState, PullRequest, Repo, authorize};
10+
11+use crate::pages::pulls_merge::{MergeOutcome, merge_gate, perform_merge};
12+use crate::state::AppState;
13+
14+/// Re-evaluates every open pull request of `repo_id` that has auto-merge on and whose head is
15+/// `sha`. Called after a commit status for `sha` was written. Failures are logged: the status
16+/// that triggered this has already been stored.
17+pub async fn on_status(state: &AppState, repo_id: &str, sha: &str) {
18+ let pulls = match state.store.auto_merge_pulls_for_head(repo_id, sha).await {
19+ Ok(pulls) => pulls,
20+ Err(e) => {
21+ tracing::error!(error = %e, repo_id, "auto-merge: listing pull requests failed");
22+ return;
23+ }
24+ };
25+ if pulls.is_empty() {
26+ return;
27+ }
28+ let repo = match state.store.repo_by_id(repo_id).await {
29+ Ok(Some(repo)) => repo,
30+ Ok(None) => return,
31+ Err(e) => {
32+ tracing::error!(error = %e, repo_id, "auto-merge: loading repo failed");
33+ return;
34+ }
35+ };
36+ for pr in pulls {
37+ evaluate_logged(state, &repo, &pr).await;
38+ }
39+}
40+
41+/// Re-evaluates one pull request, reloaded from the store. Called after a review arrived.
42+pub async fn on_pull(state: &AppState, repo: &Repo, number: i64) {
43+ match state.store.pull_by_number(&repo.id, number).await {
44+ Ok(Some(pr)) => evaluate_logged(state, repo, &pr).await,
45+ Ok(None) => {}
46+ Err(e) => {
47+ tracing::error!(error = %e, repo_id = %repo.id, number, "auto-merge: loading pull failed");
48+ }
49+ }
50+}
51+
52+async fn evaluate_logged(state: &AppState, repo: &Repo, pr: &PullRequest) {
53+ if let Err(e) = Box::pin(evaluate(state, repo, pr)).await {
54+ tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "auto-merge: evaluation failed");
55+ }
56+}
57+
58+/// Merges `pr` when auto-merge is on and nothing blocks it any more. Returns whether it merged.
59+///
60+/// The merge runs as the user who enabled auto-merge, and only while that user still has Write on
61+/// the repo; otherwise auto-merge is switched off with a timeline notice. A merge the repository
62+/// refuses (a conflict, a moved base) also switches it off, so it never retries forever.
63+pub async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_core::Result<bool> {
64+ let Some(auto) = pr.auto_merge.as_ref() else {
65+ return Ok(false);
66+ };
67+ if pr.merged_at.is_some() || pr.issue.state != IssueState::Open || repo.archived {
68+ return Ok(false);
69+ }
70+ if pr.draft || pr.head_repo_id.is_none() {
71+ return Ok(false);
72+ }
73+ if merge_gate(state, repo, pr).await?.blocked().is_some() {
74+ return Ok(false);
75+ }
76+ let Some(user) = state.store.user_by_id(&auto.user_id).await? else {
77+ state
78+ .store
79+ .disable_auto_merge(&pr.issue.id, None, "permission")
80+ .await?;
81+ return Ok(false);
82+ };
83+ let collaborator = state.store.collaborator_role(&repo.id, &user.id).await?;
84+ let org = state
85+ .store
86+ .org_repo_role(&repo.owner_id, &user.id, &repo.id)
87+ .await?;
88+ if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() {
89+ state
90+ .store
91+ .disable_auto_merge(&pr.issue.id, None, "permission")
92+ .await?;
93+ return Ok(false);
94+ }
95+ match perform_merge(state, repo, pr, &user, auto.style, None, None).await? {
96+ MergeOutcome::Merged { .. } => Ok(true),
97+ MergeOutcome::Refused { .. } => {
98+ state
99+ .store
100+ .disable_auto_merge(&pr.issue.id, Some(&user.id), "refused")
101+ .await?;
102+ Ok(false)
103+ }
104+ }
105+}
crates/forge-web/src/ci/mod.rsmodified+2 -0
@@ -108,7 +108,9 @@ pub(crate) async fn publish(
108 .await108 .await
109 {109 {
110 tracing::error!(error = %e, run_id = %run.id, context, "ci: writing commit status failed");110 tracing::error!(error = %e, run_id = %run.id, context, "ci: writing commit status failed");
111+ return;
111 }112 }
113+ crate::automerge::on_status(state, &repo.id, &run.commit_oid).await;
112 }114 }
113 115
114 /// The person a CI status is recorded for: the run's actor, or the repo owner for a system run.116 /// The person a CI status is recorded for: the run's actor, or the repo owner for a system run.
crates/forge-web/src/i18n/issues.rsmodified+44 -0
@@ -773,6 +773,50 @@ pub fn event_branch_restored(lang: Lang, branch: &str) -> String {
773 }773 }
774 }774 }
775 775
776+pub fn event_ready_for_review(lang: Lang) -> String {
777+ match lang {
778+ Lang::En => "marked this pull request as ready for review".to_owned(),
779+ Lang::Tr => "bu çekme isteğini incelemeye hazır olarak işaretledi".to_owned(),
780+ }
781+}
782+
783+pub fn event_converted_to_draft(lang: Lang) -> String {
784+ match lang {
785+ Lang::En => "converted this pull request to a draft".to_owned(),
786+ Lang::Tr => "bu çekme isteğini taslağa çevirdi".to_owned(),
787+ }
788+}
789+
790+pub fn event_auto_merge_enabled(lang: Lang, style: &str) -> String {
791+ match lang {
792+ Lang::En => format!("enabled auto-merge ({style})"),
793+ Lang::Tr => format!("otomatik birleştirmeyi açtı ({style})"),
794+ }
795+}
796+
797+pub fn event_auto_merge_disabled(lang: Lang, reason: &str) -> String {
798+ match (lang, reason) {
799+ (Lang::En, "push") => "Auto-merge was disabled because new commits were pushed".to_owned(),
800+ (Lang::Tr, "push") => {
801+ "Yeni commit'ler gönderildiği için otomatik birleştirme kapatıldı".to_owned()
802+ }
803+ (Lang::En, "refused") => {
804+ "Auto-merge was disabled because the merge could not be completed".to_owned()
805+ }
806+ (Lang::Tr, "refused") => {
807+ "Birleştirme tamamlanamadığı için otomatik birleştirme kapatıldı".to_owned()
808+ }
809+ (Lang::En, "permission") => {
810+ "Auto-merge was disabled because its user can no longer merge".to_owned()
811+ }
812+ (Lang::Tr, "permission") => {
813+ "Kullanıcı artık birleştiremediği için otomatik birleştirme kapatıldı".to_owned()
814+ }
815+ (Lang::En, _) => "disabled auto-merge".to_owned(),
816+ (Lang::Tr, _) => "otomatik birleştirmeyi kapattı".to_owned(),
817+ }
818+}
819+
776 pub fn event_thread_resolved(lang: Lang, path: &str) -> String {820 pub fn event_thread_resolved(lang: Lang, path: &str) -> String {
777 match lang {821 match lang {
778 Lang::En => format!("resolved a conversation on {path}"),822 Lang::En => format!("resolved a conversation on {path}"),
crates/forge-web/src/i18n/pulls.rsmodified+24 -0
@@ -61,6 +61,12 @@ pub enum K {
61 TitleLabel,61 TitleLabel,
62 DescriptionLabel,62 DescriptionLabel,
63 CreatePullRequest,63 CreatePullRequest,
64+ CreateDraftPullRequest,
65+ DraftBadge,
66+ DraftFilterLabel,
67+ DraftAny,
68+ DraftOnly,
69+ DraftReadyOnly,
64 AlreadyOpen,70 AlreadyOpen,
65 ViewIt,71 ViewIt,
66 ArchivedNoPulls,72 ArchivedNoPulls,
@@ -189,6 +195,18 @@ pub fn t(lang: Lang, key: K) -> &'static str {
189 (DescriptionLabel, Tr) => "Açıklama",195 (DescriptionLabel, Tr) => "Açıklama",
190 (CreatePullRequest, En) => "Create pull request",196 (CreatePullRequest, En) => "Create pull request",
191 (CreatePullRequest, Tr) => "Çekme isteği oluştur",197 (CreatePullRequest, Tr) => "Çekme isteği oluştur",
198+ (CreateDraftPullRequest, En) => "Create draft pull request",
199+ (CreateDraftPullRequest, Tr) => "Taslak çekme isteği oluştur",
200+ (DraftBadge, En) => "Draft",
201+ (DraftBadge, Tr) => "Taslak",
202+ (DraftFilterLabel, En) => "Draft status",
203+ (DraftFilterLabel, Tr) => "Taslak durumu",
204+ (DraftAny, En) => "Drafts and ready",
205+ (DraftAny, Tr) => "Taslak ve hazır",
206+ (DraftOnly, En) => "Drafts only",
207+ (DraftOnly, Tr) => "Yalnızca taslaklar",
208+ (DraftReadyOnly, En) => "Ready for review only",
209+ (DraftReadyOnly, Tr) => "Yalnızca incelemeye hazır olanlar",
192 (AlreadyOpen, En) => "A pull request is already open for this comparison: ",210 (AlreadyOpen, En) => "A pull request is already open for this comparison: ",
193 (AlreadyOpen, Tr) => "Bu karşılaştırma için zaten açık bir çekme isteği var. ",211 (AlreadyOpen, Tr) => "Bu karşılaştırma için zaten açık bir çekme isteği var. ",
194 (ViewIt, En) => "view it",212 (ViewIt, En) => "view it",
@@ -335,6 +353,12 @@ mod tests {
335 K::TitleLabel,353 K::TitleLabel,
336 K::DescriptionLabel,354 K::DescriptionLabel,
337 K::CreatePullRequest,355 K::CreatePullRequest,
356+ K::CreateDraftPullRequest,
357+ K::DraftBadge,
358+ K::DraftFilterLabel,
359+ K::DraftAny,
360+ K::DraftOnly,
361+ K::DraftReadyOnly,
338 K::AlreadyOpen,362 K::AlreadyOpen,
339 K::ViewIt,363 K::ViewIt,
340 K::ArchivedNoPulls,364 K::ArchivedNoPulls,
crates/forge-web/src/i18n/pulls_review.rsmodified+91 -0
@@ -26,6 +26,23 @@ pub enum K {
26 StyleMergeCommit,26 StyleMergeCommit,
27 StyleSquash,27 StyleSquash,
28 StyleFastForward,28 StyleFastForward,
29+ StyleRebase,
30+ ErrDraft,
31+ ErrNeedsChecks,
32+ ErrRebaseConflict,
33+ ErrAutoMergeBlocked,
34+ DraftBadge,
35+ ReadyForReview,
36+ ConvertToDraft,
37+ RequiredChecksHeading,
38+ CheckPassing,
39+ CheckPending,
40+ CheckFailing,
41+ CheckErrored,
42+ CheckMissing,
43+ EnableAutoMerge,
44+ AutoMergeHint,
45+ DisableAutoMerge,
29 MergeMessageLabel,46 MergeMessageLabel,
30 MergeButton,47 MergeButton,
31 MergedByPrefix,48 MergedByPrefix,
@@ -115,6 +132,56 @@ pub fn t(lang: Lang, key: K) -> &'static str {
115 (StyleSquash, Tr) => " Sıkıştır ve birleştir",132 (StyleSquash, Tr) => " Sıkıştır ve birleştir",
116 (StyleFastForward, En) => " Fast-forward",133 (StyleFastForward, En) => " Fast-forward",
117 (StyleFastForward, Tr) => " İleri sarma (fast-forward)",134 (StyleFastForward, Tr) => " İleri sarma (fast-forward)",
135+ (StyleRebase, En) => " Rebase and merge",
136+ (StyleRebase, Tr) => " Yeniden temellendir ve birleştir (rebase)",
137+ (ErrDraft, En) => "This pull request is a draft. Mark it ready for review to merge it.",
138+ (ErrDraft, Tr) => {
139+ "Bu çekme isteği bir taslak. Birleştirmek için önce incelemeye hazır olarak işaretleyin."
140+ }
141+ (ErrNeedsChecks, En) => "Every required status check must pass before this can be merged.",
142+ (ErrNeedsChecks, Tr) => {
143+ "Birleştirmeden önce gerekli tüm durum denetimlerinin geçmesi gerekir."
144+ }
145+ (ErrRebaseConflict, En) => {
146+ "Rebase failed: a commit does not apply cleanly on the base branch. Resolve the conflicts or use another merge style."
147+ }
148+ (ErrRebaseConflict, Tr) => {
149+ "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."
150+ }
151+ (ErrAutoMergeBlocked, En) => {
152+ "Auto-merge can only be enabled while the pull request waits for checks or approvals."
153+ }
154+ (ErrAutoMergeBlocked, Tr) => {
155+ "Otomatik birleştirme yalnızca çekme isteği denetimleri veya onayları beklerken açılabilir."
156+ }
157+ (DraftBadge, En) => "Draft",
158+ (DraftBadge, Tr) => "Taslak",
159+ (ReadyForReview, En) => "Ready for review",
160+ (ReadyForReview, Tr) => "İncelemeye hazır",
161+ (ConvertToDraft, En) => "Convert to draft",
162+ (ConvertToDraft, Tr) => "Taslağa çevir",
163+ (RequiredChecksHeading, En) => "Required checks",
164+ (RequiredChecksHeading, Tr) => "Gerekli denetimler",
165+ (CheckPassing, En) => "Passing",
166+ (CheckPassing, Tr) => "Başarılı",
167+ (CheckPending, En) => "Pending",
168+ (CheckPending, Tr) => "Bekliyor",
169+ (CheckFailing, En) => "Failing",
170+ (CheckFailing, Tr) => "Başarısız",
171+ (CheckErrored, En) => "Errored",
172+ (CheckErrored, Tr) => "Hata verdi",
173+ (CheckMissing, En) => "Waiting for status",
174+ (CheckMissing, Tr) => "Durum bekleniyor",
175+ (EnableAutoMerge, En) => "Enable auto-merge",
176+ (EnableAutoMerge, Tr) => "Otomatik birleştirmeyi aç",
177+ (AutoMergeHint, En) => {
178+ "The pull request merges by itself as soon as the required checks and approvals pass."
179+ }
180+ (AutoMergeHint, Tr) => {
181+ "Gerekli denetimler ve onaylar tamamlanır tamamlanmaz çekme isteği kendiliğinden birleşir."
182+ }
183+ (DisableAutoMerge, En) => "Disable auto-merge",
184+ (DisableAutoMerge, Tr) => "Otomatik birleştirmeyi kapat",
118 (MergeMessageLabel, En) => "Merge commit message (optional)",185 (MergeMessageLabel, En) => "Merge commit message (optional)",
119 (MergeMessageLabel, Tr) => "Birleştirme commit mesajı (isteğe bağlı)",186 (MergeMessageLabel, Tr) => "Birleştirme commit mesajı (isteğe bağlı)",
120 (MergeButton, En) => "Merge pull request",187 (MergeButton, En) => "Merge pull request",
@@ -286,6 +353,13 @@ pub fn branch_deleted(lang: Lang, branch: &str) -> String {
286 }353 }
287 354
288 /// "2 of 3 required approvals".355 /// "2 of 3 required approvals".
356+pub fn auto_merge_on(lang: Lang, style: &str, who: &str) -> String {
357+ match lang {
358+ Lang::En => format!("Auto-merge is on ({style}), enabled by {who}."),
359+ Lang::Tr => format!("Otomatik birleştirme açık ({style}), {who} açtı."),
360+ }
361+}
362+
289 pub fn approvals_of(lang: Lang, have: impl Display, need: impl Display) -> String {363 pub fn approvals_of(lang: Lang, have: impl Display, need: impl Display) -> String {
290 match lang {364 match lang {
291 Lang::En => format!("{have} of {need} required approvals"),365 Lang::En => format!("{have} of {need} required approvals"),
@@ -356,6 +430,23 @@ pub const ALL: &[K] = &[
356 K::StyleMergeCommit,430 K::StyleMergeCommit,
357 K::StyleSquash,431 K::StyleSquash,
358 K::StyleFastForward,432 K::StyleFastForward,
433+ K::StyleRebase,
434+ K::ErrDraft,
435+ K::ErrNeedsChecks,
436+ K::ErrRebaseConflict,
437+ K::ErrAutoMergeBlocked,
438+ K::DraftBadge,
439+ K::ReadyForReview,
440+ K::ConvertToDraft,
441+ K::RequiredChecksHeading,
442+ K::CheckPassing,
443+ K::CheckPending,
444+ K::CheckFailing,
445+ K::CheckErrored,
446+ K::CheckMissing,
447+ K::EnableAutoMerge,
448+ K::AutoMergeHint,
449+ K::DisableAutoMerge,
359 K::MergeMessageLabel,450 K::MergeMessageLabel,
360 K::MergeButton,451 K::MergeButton,
361 K::MergedByPrefix,452 K::MergedByPrefix,
crates/forge-web/src/i18n/repo_admin.rsmodified+24 -0
@@ -103,6 +103,9 @@ pub enum K {
103 RuleChangesBlock,103 RuleChangesBlock,
104 RuleRestrictPush,104 RuleRestrictPush,
105 RuleUpToDate,105 RuleUpToDate,
106+ RequiredChecks,
107+ RequiredChecksHelp,
108+ RecentContexts,
106 SaveGeneral,109 SaveGeneral,
107 SaveRole,110 SaveRole,
108 SaveRule,111 SaveRule,
@@ -403,6 +406,16 @@ pub fn t(lang: Lang, key: K) -> &'static str {
403 (RuleChangesBlock, Tr) => "değişiklik istenmesi birleştirmeyi engeller",406 (RuleChangesBlock, Tr) => "değişiklik istenmesi birleştirmeyi engeller",
404 (RuleRestrictPush, En) => "direct pushes limited to admins",407 (RuleRestrictPush, En) => "direct pushes limited to admins",
405 (RuleRestrictPush, Tr) => "doğrudan gönderimler yöneticilerle sınırlı",408 (RuleRestrictPush, Tr) => "doğrudan gönderimler yöneticilerle sınırlı",
409+ (RequiredChecks, En) => "Required status checks",
410+ (RequiredChecks, Tr) => "Gerekli durum denetimleri",
411+ (RequiredChecksHelp, En) => {
412+ "Contexts that must be successful on the pull request head before it can merge, separated by commas. CI jobs report as ci/<job name>."
413+ }
414+ (RequiredChecksHelp, Tr) => {
415+ "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/<iş adı> olarak bildirilir."
416+ }
417+ (RecentContexts, En) => "Recently seen:",
418+ (RecentContexts, Tr) => "Son görülenler:",
406 (RuleUpToDate, En) => "head must be up to date with base",419 (RuleUpToDate, En) => "head must be up to date with base",
407 (RuleUpToDate, Tr) => "kaynak dal, hedef dalın güncel hâlini içermelidir",420 (RuleUpToDate, Tr) => "kaynak dal, hedef dalın güncel hâlini içermelidir",
408 (SaveGeneral, En) => "Save general settings",421 (SaveGeneral, En) => "Save general settings",
@@ -622,6 +635,14 @@ pub fn yes_no(lang: Lang, value: bool) -> &'static str {
622 }635 }
623 }636 }
624 637
638+/// The number of required status checks in a rule summary.
639+pub fn checks_count(lang: Lang, n: usize) -> String {
640+ match lang {
641+ Lang::En => format!("{n} required check{}", if n == 1 { "" } else { "s" }),
642+ Lang::Tr => format!("{n} gerekli denetim"),
643+ }
644+}
645+
625 /// The number of required approvals in a rule summary.646 /// The number of required approvals in a rule summary.
626 pub fn approvals_count(lang: Lang, n: u32) -> String {647 pub fn approvals_count(lang: Lang, n: u32) -> String {
627 match lang {648 match lang {
@@ -734,6 +755,9 @@ mod tests {
734 K::RuleChangesBlock,755 K::RuleChangesBlock,
735 K::RuleRestrictPush,756 K::RuleRestrictPush,
736 K::RuleUpToDate,757 K::RuleUpToDate,
758+ K::RequiredChecks,
759+ K::RequiredChecksHelp,
760+ K::RecentContexts,
737 K::SaveGeneral,761 K::SaveGeneral,
738 K::SaveRole,762 K::SaveRole,
739 K::SaveRule,763 K::SaveRule,
crates/forge-web/src/main.rsmodified+1 -0
@@ -16,6 +16,7 @@ mod advisories;
16 mod api;16 mod api;
17 mod audit;17 mod audit;
18 mod auth;18 mod auth;
19+mod automerge;
19 mod backup;20 mod backup;
20 mod blobs;21 mod blobs;
21 mod boot;22 mod boot;
crates/forge-web/src/pages/compare.rsmodified+24 -1
@@ -359,7 +359,10 @@ async fn compare_view(
359 <input type="hidden" name="head" value=(head_for_form.as_str())>359 <input type="hidden" name="head" value=(head_for_form.as_str())>
360 <p><label>(g::t(lang, K::TitleLabel)) <input type="text" name="title" value=(form_title.as_str())></label></p>360 <p><label>(g::t(lang, K::TitleLabel)) <input type="text" name="title" value=(form_title.as_str())></label></p>
361 <p><label>(g::t(lang, K::DescriptionLabel)) <textarea name="body" rows="8">(form_body.as_str())</textarea></label></p>361 <p><label>(g::t(lang, K::DescriptionLabel)) <textarea name="body" rows="8">(form_body.as_str())</textarea></label></p>
362- <p><button type="submit" class="primary">(g::t(lang, K::CreatePullRequest))</button></p>362+ <p class="form-actions">
363+ <button type="submit" class="primary">(g::t(lang, K::CreatePullRequest))</button>
364+ <button type="submit" name="draft" value="1">(g::t(lang, K::CreateDraftPullRequest))</button>
365+ </p>
363 </form>366 </form>
364 </section>367 </section>
365 }368 }
@@ -474,6 +477,9 @@ struct PullForm {
474 base: String,477 base: String,
475 #[serde(default)]478 #[serde(default)]
476 head: String,479 head: String,
480+ /// Non-empty when the pull request opens as a draft.
481+ #[serde(default)]
482+ draft: String,
477 }483 }
478 484
479 /// Opens a pull request from a comparison: `POST /{owner}/{repo}/pulls`.485 /// Opens a pull request from a comparison: `POST /{owner}/{repo}/pulls`.
@@ -546,7 +552,23 @@ async fn pull_create(cx: &Cx, Form(form): Form<PullForm>) -> Result<impl View> {
546 }552 }
547 Err(e) => return Err(e.into()),553 Err(e) => return Err(e.into()),
548 };554 };
555+ let as_draft = !form.draft.is_empty();
556+ let pr = if as_draft {
557+ state
558+ .store
559+ .set_pull_draft(&pr.issue.id, Some(&user.id), true)
560+ .await?;
561+ state
562+ .store
563+ .pull_by_number(&ctx.repo.id, pr.issue.number)
564+ .await?
565+ .unwrap_or(pr)
566+ } else {
567+ pr
568+ };
549 emit_pull(state, &ctx.repo, &Sender::of(&user), "opened", &pr).await;569 emit_pull(state, &ctx.repo, &Sender::of(&user), "opened", &pr).await;
570+ if !as_draft {
571+ // A draft tells nobody until it is marked ready for review.
550 notify::dispatch(572 notify::dispatch(
551 state,573 state,
552 &ctx.repo,574 &ctx.repo,
@@ -556,6 +578,7 @@ async fn pull_create(cx: &Cx, Form(form): Form<PullForm>) -> Result<impl View> {
556 Some(&pr.issue.body),578 Some(&pr.issue.body),
557 )579 )
558 .await;580 .await;
581+ }
559 let number = pr.issue.number;582 let number = pr.issue.number;
560 pulls::fetch_into_pull_ref(&state.git, &ctx.path, &cmp.head.path, &cmp.head_oid, number)583 pulls::fetch_into_pull_ref(&state.git, &ctx.path, &cmp.head.path, &cmp.head_oid, number)
561 .await?;584 .await?;
crates/forge-web/src/pages/issue_parts.rsmodified+4 -0
@@ -342,6 +342,10 @@ fn event_line(
342 "pinned" => g::t(lang, K::PinnedThisIssue).to_owned(),342 "pinned" => g::t(lang, K::PinnedThisIssue).to_owned(),
343 "unpinned" => g::t(lang, K::UnpinnedThisIssue).to_owned(),343 "unpinned" => g::t(lang, K::UnpinnedThisIssue).to_owned(),
344 "merged" => g::t(lang, K::MergedCommit).to_owned(),344 "merged" => g::t(lang, K::MergedCommit).to_owned(),
345+ "ready_for_review" => g::event_ready_for_review(lang),
346+ "converted_to_draft" => g::event_converted_to_draft(lang),
347+ "auto_merge_enabled" => g::event_auto_merge_enabled(lang, &text("style")),
348+ "auto_merge_disabled" => g::event_auto_merge_disabled(lang, &text("reason")),
345 "head_updated" => g::t(lang, K::PushedNewCommits).to_owned(),349 "head_updated" => g::t(lang, K::PushedNewCommits).to_owned(),
346 "head_deleted" => g::t(lang, K::DeletedHeadBranch).to_owned(),350 "head_deleted" => g::t(lang, K::DeletedHeadBranch).to_owned(),
347 "head_ref_deleted" => g::event_branch_deleted(lang, &text("branch")),351 "head_ref_deleted" => g::event_branch_deleted(lang, &text("branch")),
crates/forge-web/src/pages/issues_list.rsmodified+36 -2
@@ -48,6 +48,7 @@ pub(crate) struct ListQuery {
48 author: Option<String>,48 author: Option<String>,
49 assignee: Option<String>,49 assignee: Option<String>,
50 q: Option<String>,50 q: Option<String>,
51+ draft: Option<String>,
51 sort: Option<String>,52 sort: Option<String>,
52 page: Option<String>,53 page: Option<String>,
53 }54 }
@@ -61,6 +62,9 @@ pub(crate) struct Selection {
61 pub(crate) author: String,62 pub(crate) author: String,
62 pub(crate) assignee: String,63 pub(crate) assignee: String,
63 pub(crate) query: String,64 pub(crate) query: String,
65+ /// Pull requests only: `true` (drafts), `false` (ready) or empty (both). A `draft:true` or
66+ /// `draft:false` word in the search text sets it too.
67+ pub(crate) draft: &'static str,
64 /// `newest`, `oldest` or `updated`.68 /// `newest`, `oldest` or `updated`.
65 pub(crate) sort: &'static str,69 pub(crate) sort: &'static str,
66 pub(crate) page: u32,70 pub(crate) page: u32,
@@ -83,7 +87,30 @@ fn non_empty(value: &str) -> Option<String> {
83 87
84 impl Selection {88 impl Selection {
85 pub(crate) fn parse(query: &ListQuery) -> Self {89 pub(crate) fn parse(query: &ListQuery) -> Self {
90+ let mut draft = match query.draft.as_deref().map(str::trim) {
91+ Some("true") => "true",
92+ Some("false") => "false",
93+ _ => "",
94+ };
95+ // `draft:true` / `draft:false` words in the search text become the draft filter.
96+ let raw_query = clean(query.q.as_deref());
97+ let words: Vec<&str> = raw_query
98+ .split_whitespace()
99+ .filter(|word| match *word {
100+ "draft:true" => {
101+ draft = "true";
102+ false
103+ }
104+ "draft:false" => {
105+ draft = "false";
106+ false
107+ }
108+ _ => true,
109+ })
110+ .collect();
111+ let query_text = words.join(" ");
86 Self {112 Self {
113+ draft,
87 state: match query.state.as_deref() {114 state: match query.state.as_deref() {
88 Some("closed") => "closed",115 Some("closed") => "closed",
89 Some("all") => "all",116 Some("all") => "all",
@@ -93,7 +120,7 @@ impl Selection {
93 milestone: clean(query.milestone.as_deref()),120 milestone: clean(query.milestone.as_deref()),
94 author: clean(query.author.as_deref()),121 author: clean(query.author.as_deref()),
95 assignee: clean(query.assignee.as_deref()),122 assignee: clean(query.assignee.as_deref()),
96- query: clean(query.q.as_deref()),123+ query: query_text,
97 sort: match query.sort.as_deref() {124 sort: match query.sort.as_deref() {
98 Some("oldest") => "oldest",125 Some("oldest") => "oldest",
99 Some("updated") => "updated",126 Some("updated") => "updated",
@@ -120,6 +147,11 @@ impl Selection {
120 author: non_empty(&self.author),147 author: non_empty(&self.author),
121 assignee: non_empty(&self.assignee),148 assignee: non_empty(&self.assignee),
122 query: non_empty(&self.query),149 query: non_empty(&self.query),
150+ draft: match self.draft {
151+ "true" => Some(true),
152+ "false" => Some(false),
153+ _ => None,
154+ },
123 sort: match self.sort {155 sort: match self.sort {
124 "oldest" => IssueSort::Oldest,156 "oldest" => IssueSort::Oldest,
125 "updated" => IssueSort::RecentlyUpdated,157 "updated" => IssueSort::RecentlyUpdated,
@@ -136,7 +168,8 @@ impl Selection {
136 && self.milestone.is_empty()168 && self.milestone.is_empty()
137 && self.author.is_empty()169 && self.author.is_empty()
138 && self.assignee.is_empty()170 && self.assignee.is_empty()
139- && self.query.is_empty())171+ && self.query.is_empty()
172+ && self.draft.is_empty())
140 }173 }
141 174
142 /// The list URL with this selection, but a different state and page.175 /// The list URL with this selection, but a different state and page.
@@ -156,6 +189,7 @@ impl Selection {
156 ("author", self.author.as_str()),189 ("author", self.author.as_str()),
157 ("assignee", self.assignee.as_str()),190 ("assignee", self.assignee.as_str()),
158 ("q", self.query.as_str()),191 ("q", self.query.as_str()),
192+ ("draft", self.draft),
159 ("sort", sort),193 ("sort", sort),
160 ("page", page_text.as_str()),194 ("page", page_text.as_str()),
161 ],195 ],
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -56,6 +56,7 @@ pub mod profile;
56 pub mod profile_pins;56 pub mod profile_pins;
57 pub mod pull_branch;57 pub mod pull_branch;
58 pub mod pull_files;58 pub mod pull_files;
59+pub mod pull_flow;
59 pub mod pull_reviews;60 pub mod pull_reviews;
60 pub mod pull_view;61 pub mod pull_view;
61 pub mod pulls_list;62 pub mod pulls_list;
crates/forge-web/src/pages/pull_flow.rsadded+165 -0
@@ -0,0 +1,165 @@
1+//! Pull request flow controls: draft state and auto-merge.
2+//!
3+//! - `POST /{owner}/{repo}/pulls/{number}/ready` marks a draft ready for review.
4+//! - `POST /{owner}/{repo}/pulls/{number}/draft` converts an open pull request back to a draft.
5+//! - `POST /{owner}/{repo}/pulls/{number}/auto-merge` enables auto-merge with a style.
6+//! - `POST /{owner}/{repo}/pulls/{number}/auto-merge/disable` switches it off.
7+//!
8+//! Draft changes are for the pull request author and for Write holders. Auto-merge needs Write,
9+//! a signed-in viewer with a valid CSRF token, and a pull request that is blocked only by checks
10+//! or approvals that can still arrive. All of them answer with a redirect back to the pull
11+//! request (the soft-nav script follows it without a reload).
12+
13+use forge_core::{Action, IssueState, MergeStyle, PullRequest, authorize};
14+use serde::Deserialize;
15+use topcoat::Result;
16+use topcoat::context::{Cx, app_context};
17+use topcoat::router::content::Form;
18+use topcoat::router::error::{bad_request, forbidden, not_found, see_other};
19+use topcoat::router::response::Response;
20+use topcoat::router::{path_param, route};
21+
22+use crate::auth::require_csrf;
23+use crate::notify::{self, Activity};
24+use crate::pages::issue_parts::parse_number;
25+use crate::pages::pulls_merge::{ERR_AUTO_MERGE_BLOCKED, merge_gate};
26+use crate::pages::repo_ctx::{RepoCtx, load_repo};
27+use crate::state::AppState;
28+use crate::views::repo_href;
29+use crate::webhooks::emit::{Sender, emit_item_action};
30+
31+path_param!(owner);
32+path_param!(repo);
33+path_param!(number);
34+
35+#[derive(Deserialize)]
36+struct FlowForm {
37+ #[serde(default)]
38+ csrf: String,
39+ #[serde(default)]
40+ style: String,
41+}
42+
43+fn pull_href(ctx: &RepoCtx, number: i64) -> String {
44+ repo_href(
45+ &ctx.repo.owner_name,
46+ &ctx.repo.name,
47+ "pulls",
48+ &number.to_string(),
49+ )
50+}
51+
52+fn can_write(ctx: &RepoCtx, user: &forge_core::User) -> bool {
53+ authorize(Some(user), &ctx.repo, ctx.role, ctx.org_role, Action::Write).is_ok()
54+}
55+
56+async fn load(cx: &Cx, ctx: &RepoCtx, number: i64) -> Result<PullRequest> {
57+ let state = app_context::<AppState>(cx);
58+ match state.store.pull_by_number(&ctx.repo.id, number).await? {
59+ Some(pr) => Ok(pr),
60+ None => Err(not_found().into()),
61+ }
62+}
63+
64+#[route(POST "/{owner}/{repo}/pulls/{number}/ready")]
65+async fn ready_post(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Response> {
66+ set_draft(cx, &form.csrf, false).await
67+}
68+
69+#[route(POST "/{owner}/{repo}/pulls/{number}/draft")]
70+async fn draft_post(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Response> {
71+ set_draft(cx, &form.csrf, true).await
72+}
73+
74+async fn set_draft(cx: &Cx, csrf: &str, draft: bool) -> Result<Response> {
75+ let number = parse_number(path_param::<Number>(cx))?;
76+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
77+ let (user, _) = require_csrf(cx, csrf).await?;
78+ let state = app_context::<AppState>(cx);
79+ let pr = load(cx, &ctx, number).await?;
80+ if ctx.repo.archived || !(can_write(&ctx, &user) || user.id == pr.issue.author_id) {
81+ return Err(forbidden().into());
82+ }
83+ let href = pull_href(&ctx, number);
84+ if pr.merged_at.is_some() || pr.issue.state != IssueState::Open {
85+ return Err(see_other(href).into());
86+ }
87+ let changed = match state
88+ .store
89+ .set_pull_draft(&pr.issue.id, Some(&user.id), draft)
90+ .await
91+ {
92+ Ok(changed) => changed,
93+ Err(forge_core::Error::Conflict(_)) => false,
94+ Err(e) => return Err(e.into()),
95+ };
96+ if changed {
97+ let action = if draft {
98+ "converted_to_draft"
99+ } else {
100+ "ready_for_review"
101+ };
102+ emit_item_action(state, &ctx.repo, &Sender::of(&user), true, number, action).await;
103+ if !draft {
104+ // Reviewers hear about the pull request now, not when it was opened as a draft.
105+ notify::dispatch(
106+ state,
107+ &ctx.repo,
108+ &pr.issue,
109+ &user.id,
110+ Activity::Opened,
111+ Some(&pr.issue.body),
112+ )
113+ .await;
114+ }
115+ }
116+ Err(see_other(href).into())
117+}
118+
119+#[route(POST "/{owner}/{repo}/pulls/{number}/auto-merge")]
120+async fn auto_merge_enable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Response> {
121+ let number = parse_number(path_param::<Number>(cx))?;
122+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
123+ let (user, _) = require_csrf(cx, &form.csrf).await?;
124+ if ctx.repo.archived || !can_write(&ctx, &user) {
125+ return Err(forbidden().into());
126+ }
127+ let state = app_context::<AppState>(cx);
128+ let pr = load(cx, &ctx, number).await?;
129+ let style = form
130+ .style
131+ .parse::<MergeStyle>()
132+ .map_err(|e| bad_request(e.to_string()))?;
133+ let href = pull_href(&ctx, number);
134+ if pr.merged_at.is_some() || pr.issue.state != IssueState::Open || pr.head_repo_id.is_none() {
135+ return Err(see_other(href).into());
136+ }
137+ let gate = merge_gate(state, &ctx.repo, &pr).await?;
138+ if !gate.waiting_only() {
139+ return Err(see_other(format!("{href}?merge_error={ERR_AUTO_MERGE_BLOCKED}")).into());
140+ }
141+ state
142+ .store
143+ .enable_auto_merge(&pr.issue.id, &user.id, style)
144+ .await?;
145+ // Nothing may be missing by now: merge right away instead of waiting for an event.
146+ crate::automerge::on_pull(state, &ctx.repo, number).await;
147+ Err(see_other(href).into())
148+}
149+
150+#[route(POST "/{owner}/{repo}/pulls/{number}/auto-merge/disable")]
151+async fn auto_merge_disable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Response> {
152+ let number = parse_number(path_param::<Number>(cx))?;
153+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
154+ let (user, _) = require_csrf(cx, &form.csrf).await?;
155+ if ctx.repo.archived || !can_write(&ctx, &user) {
156+ return Err(forbidden().into());
157+ }
158+ let state = app_context::<AppState>(cx);
159+ let pr = load(cx, &ctx, number).await?;
160+ state
161+ .store
162+ .disable_auto_merge(&pr.issue.id, Some(&user.id), "manual")
163+ .await?;
164+ Err(see_other(pull_href(&ctx, number)).into())
165+}
crates/forge-web/src/pages/pull_reviews.rsmodified+1 -0
@@ -530,6 +530,7 @@ async fn review_submit(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOther
530 Some(&text),530 Some(&text),
531 )531 )
532 .await;532 .await;
533+ crate::automerge::on_pull(state, &ctx.repo, number).await;
533 Ok(see_other(format!("{tab}#review-{}", review.id)))534 Ok(see_other(format!("{tab}#review-{}", review.id)))
534 }535 }
535 Err(forge_core::Error::Forbidden(_)) => Ok(refusal(&tab, ERR_OWN_PR, "")),536 Err(forge_core::Error::Forbidden(_)) => Ok(refusal(&tab, ERR_OWN_PR, "")),
crates/forge-web/src/pages/pull_view.rsmodified+152 -4
@@ -6,6 +6,7 @@
6 6
7 use std::collections::HashMap;7 use std::collections::HashMap;
8 8
9+use forge_core::store::commit_status::StatusState;
9 use forge_core::{Action, IssueState, Mergeable, PullRequest, Review, ReviewState, authorize};10 use forge_core::{Action, IssueState, Mergeable, PullRequest, Review, ReviewState, authorize};
10 use forge_git::browse::CommitInfo;11 use forge_git::browse::CommitInfo;
11 use forge_git::history::CommitDiff;12 use forge_git::history::CommitDiff;
@@ -32,9 +33,10 @@ use crate::pages::notifications::notify_box_for;
32 use crate::pages::pull_branch::{self, branch_box, branch_error_from};33 use crate::pages::pull_branch::{self, branch_box, branch_error_from};
33 use crate::pages::pull_reviews::error_text_in;34 use crate::pages::pull_reviews::error_text_in;
34 use crate::pages::pulls_merge::{35 use crate::pages::pulls_merge::{
35- ERR_ALREADY_MERGED, ERR_BASE_MISSING, ERR_BASE_MOVED, ERR_CHANGES_REQUESTED, ERR_CONFLICT,36+ ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED,
36- ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING, ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NOT_OPEN,37+ ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING,
37- ERR_NOT_UP_TO_DATE, ERR_UP_TO_DATE, merge_gate,38+ ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, ERR_NOT_UP_TO_DATE,
39+ ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, merge_gate,
38 };40 };
39 use crate::pages::repo::repo_head;41 use crate::pages::repo::repo_head;
40 use crate::pages::repo_ctx::{RepoCtx, load_repo};42 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -154,6 +156,8 @@ pub(crate) async fn frame_in(
154 156
155 let (state_class, state_text) = if is_merged(pr) {157 let (state_class, state_text) = if is_merged(pr) {
156 ("issue-badge issue-badge-merged", g::t(lang, K::StateMerged))158 ("issue-badge issue-badge-merged", g::t(lang, K::StateMerged))
159+ } else if matches!(pr.issue.state, IssueState::Open) && pr.draft {
160+ ("issue-badge issue-badge-draft", g::t(lang, K::DraftBadge))
157 } else if matches!(pr.issue.state, IssueState::Open) {161 } else if matches!(pr.issue.state, IssueState::Open) {
158 ("issue-badge issue-badge-open", g::t(lang, K::StateOpen))162 ("issue-badge issue-badge-open", g::t(lang, K::StateOpen))
159 } else {163 } else {
@@ -273,6 +277,24 @@ struct MergeForm {
273 ff: bool,277 ff: bool,
274 }278 }
275 279
280+/// One required check as the merge box lists it.
281+struct CheckRow {
282+ context: String,
283+ label: &'static str,
284+ class: &'static str,
285+}
286+
287+/// The flow controls of the merge box: the draft toggle and auto-merge.
288+struct FlowView {
289+ csrf: String,
290+ /// `(action, button label)` of the draft toggle.
291+ draft_toggle: Option<(String, &'static str)>,
292+ /// Auto-merge is on: the status line and the disable action.
293+ auto_on: Option<(String, String)>,
294+ /// Auto-merge can be enabled: the action.
295+ auto_enable: Option<String>,
296+}
297+
276 /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of298 /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of
277 /// `ok`, `bad` or `muted` and picks the box colors.299 /// `ok`, `bad` or `muted` and picks the box colors.
278 #[component]300 #[component]
@@ -286,9 +308,24 @@ async fn merge_box(
286 approvals: Option<String>,308 approvals: Option<String>,
287 blocked: Option<String>,309 blocked: Option<String>,
288 checks: Option<StatusSummary>,310 checks: Option<StatusSummary>,
311+ required: Vec<CheckRow>,
312+ flow: FlowView,
289 lang: Lang,313 lang: Lang,
290 ) -> Result<impl View> {314 ) -> Result<impl View> {
291 let class = format!("merge-box merge-{tone}");315 let class = format!("merge-box merge-{tone}");
316+ let required_heading = g::t(lang, K::RequiredChecksHeading);
317+ let style_rebase = g::t(lang, K::StyleRebase);
318+ let style_merge_option = g::t(lang, K::StyleMergeCommit);
319+ let style_squash_option = g::t(lang, K::StyleSquash);
320+ let enable_auto = g::t(lang, K::EnableAutoMerge);
321+ let auto_hint = g::t(lang, K::AutoMergeHint);
322+ let disable_auto = g::t(lang, K::DisableAutoMerge);
323+ let FlowView {
324+ csrf: flow_csrf,
325+ draft_toggle,
326+ auto_on,
327+ auto_enable,
328+ } = flow;
292 let reload_text = g::t(lang, K::ReloadToCheck);329 let reload_text = g::t(lang, K::ReloadToCheck);
293 let style_legend = g::t(lang, K::MergeStyleLegend);330 let style_legend = g::t(lang, K::MergeStyleLegend);
294 let style_merge = g::t(lang, K::StyleMergeCommit);331 let style_merge = g::t(lang, K::StyleMergeCommit);
@@ -305,6 +342,16 @@ async fn merge_box(
305 if let Some(summary) = checks {342 if let Some(summary) = checks {
306 checks_summary(summary: summary, lang: StatusLang(lang))343 checks_summary(summary: summary, lang: StatusLang(lang))
307 }344 }
345+ if !required.is_empty() {
346+ <div class="required-checks">
347+ <p class="muted small">(required_heading)</p>
348+ <ul class="required-check-list">
349+ for row in required.iter() {
350+ <li class=(row.class)><code>(row.context.as_str())</code><span>(row.label)</span></li>
351+ }
352+ </ul>
353+ </div>
354+ }
308 if let Some(text) = approvals {355 if let Some(text) = approvals {
309 <p class="muted small">(text.as_str())</p>356 <p class="muted small">(text.as_str())</p>
310 }357 }
@@ -328,6 +375,7 @@ async fn merge_box(
328 <legend>(style_legend)</legend>375 <legend>(style_legend)</legend>
329 <label><input type="radio" name="style" value="merge" checked=(true)>(style_merge)</label>376 <label><input type="radio" name="style" value="merge" checked=(true)>(style_merge)</label>
330 <label><input type="radio" name="style" value="squash">(style_squash)</label>377 <label><input type="radio" name="style" value="squash">(style_squash)</label>
378+ <label><input type="radio" name="style" value="rebase">(style_rebase)</label>
331 if f.ff {379 if f.ff {
332 <label><input type="radio" name="style" value="ff">(style_ff)</label>380 <label><input type="radio" name="style" value="ff">(style_ff)</label>
333 }381 }
@@ -339,6 +387,31 @@ async fn merge_box(
339 <div><button type="submit" class="primary">(merge_button)</button></div>387 <div><button type="submit" class="primary">(merge_button)</button></div>
340 </form>388 </form>
341 }389 }
390+ if let Some((text, action)) = auto_on {
391+ <form method="post" action=(action.as_str()) class="merge-flow">
392+ <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
393+ <p class="muted small">(text.as_str())</p>
394+ <button type="submit">(disable_auto)</button>
395+ </form>
396+ }
397+ if let Some(action) = auto_enable {
398+ <form method="post" action=(action.as_str()) class="merge-flow">
399+ <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
400+ <p class="muted small">(auto_hint)</p>
401+ <select name="style" aria-label=(enable_auto)>
402+ <option value="merge">(style_merge_option.trim())</option>
403+ <option value="squash">(style_squash_option.trim())</option>
404+ <option value="rebase">(style_rebase.trim())</option>
405+ </select>
406+ <button type="submit">(enable_auto)</button>
407+ </form>
408+ }
409+ if let Some((action, label)) = draft_toggle {
410+ <form method="post" action=(action.as_str()) class="merge-flow">
411+ <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
412+ <button type="submit">(label)</button>
413+ </form>
414+ }
342 </section>415 </section>
343 })416 })
344 }417 }
@@ -580,6 +653,76 @@ async fn pull_conversation(
580 gate.rule.required_approvals,653 gate.rule.required_approvals,
581 )654 )
582 });655 });
656+ let auto_merge_user = match pr.auto_merge.as_ref() {
657+ Some(auto) => state
658+ .store
659+ .usernames_by_ids(std::slice::from_ref(&auto.user_id))
660+ .await?
661+ .get(&auto.user_id)
662+ .map(|(display, _)| display.clone())
663+ .unwrap_or_else(|| g::t(lang, K::Unknown).to_owned()),
664+ None => String::new(),
665+ };
666+ let required: Vec<CheckRow> = gate
667+ .as_ref()
668+ .map(|gate| {
669+ gate.required
670+ .iter()
671+ .map(|check| {
672+ let (class, label) = match check.state {
673+ Some(StatusState::Success) => ("check-ok", g::t(lang, K::CheckPassing)),
674+ Some(StatusState::Pending) => {
675+ ("check-pending", g::t(lang, K::CheckPending))
676+ }
677+ Some(StatusState::Failure) => ("check-bad", g::t(lang, K::CheckFailing)),
678+ Some(StatusState::Error) => ("check-bad", g::t(lang, K::CheckErrored)),
679+ None => ("check-pending", g::t(lang, K::CheckMissing)),
680+ };
681+ CheckRow {
682+ context: check.context.clone(),
683+ label,
684+ class,
685+ }
686+ })
687+ .collect()
688+ })
689+ .unwrap_or_default();
690+ let auto_waiting = gate
691+ .as_ref()
692+ .is_some_and(|gate| !gate.blockers().is_empty() && gate.waiting_only());
693+ let flow = FlowView {
694+ csrf: csrf.clone(),
695+ draft_toggle: (open
696+ && !archived
697+ && ctx
698+ .viewer
699+ .as_ref()
700+ .is_some_and(|(user, _)| can_write || user.id == pr.issue.author_id))
701+ .then(|| {
702+ if pr.draft {
703+ (format!("{href}/ready"), g::t(lang, K::ReadyForReview))
704+ } else {
705+ (format!("{href}/draft"), g::t(lang, K::ConvertToDraft))
706+ }
707+ }),
708+ auto_on: pr
709+ .auto_merge
710+ .as_ref()
711+ .filter(|_| open && can_write)
712+ .map(|auto| {
713+ (
714+ g::auto_merge_on(lang, auto.style.as_str(), &auto_merge_user),
715+ format!("{href}/auto-merge/disable"),
716+ )
717+ }),
718+ auto_enable: (open
719+ && can_write
720+ && pr.auto_merge.is_none()
721+ && auto_waiting
722+ && pr.mergeable != Mergeable::Conflict
723+ && pr.head_repo_id.is_some())
724+ .then(|| format!("{href}/auto-merge")),
725+ };
583 let merge_form = if open726 let merge_form = if open
584 && can_write727 && can_write
585 && pr.mergeable == Mergeable::Clean728 && pr.mergeable == Mergeable::Clean
@@ -660,7 +803,8 @@ async fn pull_conversation(
660 if open {803 if open {
661 merge_box(headline: headline, tone: tone.to_owned(), conflicts: conflicts,804 merge_box(headline: headline, tone: tone.to_owned(), conflicts: conflicts,
662 reload: reload, form: merge_form, merge_error: merge_error,805 reload: reload, form: merge_form, merge_error: merge_error,
663- approvals: approvals, blocked: blocked, checks: checks, lang: lang)806+ approvals: approvals, blocked: blocked, checks: checks,
807+ required: required, flow: flow, lang: lang)
664 }808 }
665 if let Some(when) = merged_when {809 if let Some(when) = merged_when {
666 merged_notice(who: merged_who, when: when, commit: merge_commit,810 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> {
706 ERR_CHANGES_REQUESTED => g::t(lang, K::ErrChangesRequested),850 ERR_CHANGES_REQUESTED => g::t(lang, K::ErrChangesRequested),
707 ERR_NOT_UP_TO_DATE => g::t(lang, K::ErrNotUpToDate),851 ERR_NOT_UP_TO_DATE => g::t(lang, K::ErrNotUpToDate),
708 ERR_MESSAGE_INVALID => g::t(lang, K::ErrMessageInvalid),852 ERR_MESSAGE_INVALID => g::t(lang, K::ErrMessageInvalid),
853+ ERR_DRAFT => g::t(lang, K::ErrDraft),
854+ ERR_NEEDS_CHECKS => g::t(lang, K::ErrNeedsChecks),
855+ ERR_REBASE_CONFLICT => g::t(lang, K::ErrRebaseConflict),
856+ ERR_AUTO_MERGE_BLOCKED => g::t(lang, K::ErrAutoMergeBlocked),
709 _ => return None,857 _ => return None,
710 })858 })
711 }859 }
crates/forge-web/src/pages/pulls_list.rsmodified+22 -2
@@ -47,6 +47,7 @@ struct PullRowView {
47 assignees: Vec<AssigneeView>,47 assignees: Vec<AssigneeView>,
48 has_comments: bool,48 has_comments: bool,
49 comments_text: String,49 comments_text: String,
50+ draft: bool,
50 }51 }
51 52
52 /// The row's icon and badge: green for open, purple for merged, red for closed without a merge.53 /// 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> {
91 }92 }
92 93
93 /// One row, built from the page's shared values and the item's own `merged` flag.94 /// One row, built from the page's shared values and the item's own `merged` flag.
94-fn row_view(env: &RowEnv<'_>, item: &IssueListItem, merged: bool) -> PullRowView {95+fn row_view(env: &RowEnv<'_>, item: &IssueListItem, merged: bool, draft: bool) -> PullRowView {
95 let RowEnv {96 let RowEnv {
96 lang,97 lang,
97 base,98 base,
@@ -144,6 +145,7 @@ fn row_view(env: &RowEnv<'_>, item: &IssueListItem, merged: bool) -> PullRowView
144 .collect(),145 .collect(),
145 has_comments: comments > 0,146 has_comments: comments > 0,
146 comments_text: g::comments(lang, comments),147 comments_text: g::comments(lang, comments),
148+ draft: draft && open,
147 }149 }
148 }150 }
149 151
@@ -161,6 +163,7 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
161 let (open_count, closed_count) = state.store.pull_counts(&ctx.repo.id).await?;163 let (open_count, closed_count) = state.store.pull_counts(&ctx.repo.id).await?;
162 let numbers: Vec<i64> = items.iter().map(|item| item.issue.number).collect();164 let numbers: Vec<i64> = items.iter().map(|item| item.issue.number).collect();
163 let merged = state.store.merged_numbers(&ctx.repo.id, &numbers).await?;165 let merged = state.store.merged_numbers(&ctx.repo.id, &numbers).await?;
166+ let drafts = state.store.draft_numbers(&ctx.repo.id, &numbers).await?;
164 let milestones: HashMap<String, String> = state167 let milestones: HashMap<String, String> = state
165 .store168 .store
166 .list_milestones(&ctx.repo.id, None)169 .list_milestones(&ctx.repo.id, None)
@@ -184,7 +187,14 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
184 };187 };
185 let rows: Vec<PullRowView> = items188 let rows: Vec<PullRowView> = items
186 .iter()189 .iter()
187- .map(|item| row_view(&env, item, merged.contains(&item.issue.number)))190+ .map(|item| {
191+ row_view(
192+ &env,
193+ item,
194+ merged.contains(&item.issue.number),
195+ drafts.contains(&item.issue.number),
196+ )
197+ })
188 .collect();198 .collect();
189 199
190 let last_page = total.div_ceil(u64::from(PER_PAGE)).max(1);200 let last_page = total.div_ceil(u64::from(PER_PAGE)).max(1);
@@ -226,6 +236,8 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
226 g::t(lang, K::NoPullRequestsMatch)236 g::t(lang, K::NoPullRequestsMatch)
227 };237 };
228 let state_word = sel.state;238 let state_word = sel.state;
239+ let draft_label = g::t(lang, K::DraftBadge);
240+ let draft_sel = sel.draft;
229 241
230 let header = ctx.head(state, "pulls").await?;242 let header = ctx.head(state, "pulls").await?;
231 Ok(view! {243 Ok(view! {
@@ -250,6 +262,11 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
250 <input type="hidden" name="author" value=(sel.author.as_str())>262 <input type="hidden" name="author" value=(sel.author.as_str())>
251 <input type="hidden" name="assignee" value=(sel.assignee.as_str())>263 <input type="hidden" name="assignee" value=(sel.assignee.as_str())>
252 <input type="search" name="q" value=(sel.query.as_str()) placeholder=(g::t(lang, K::SearchTitles)) aria-label=(g::t(lang, K::SearchTitles)) maxlength="256">264 <input type="search" name="q" value=(sel.query.as_str()) placeholder=(g::t(lang, K::SearchTitles)) aria-label=(g::t(lang, K::SearchTitles)) maxlength="256">
265+ <select name="draft" aria-label=(g::t(lang, K::DraftFilterLabel)) data-autosubmit=(true)>
266+ <option value="" selected=(draft_sel.is_empty())>(g::t(lang, K::DraftAny))</option>
267+ <option value="true" selected=(draft_sel == "true")>(g::t(lang, K::DraftOnly))</option>
268+ <option value="false" selected=(draft_sel == "false")>(g::t(lang, K::DraftReadyOnly))</option>
269+ </select>
253 <select name="sort" aria-label=(g::t(lang, K::SortLabel))>270 <select name="sort" aria-label=(g::t(lang, K::SortLabel))>
254 for option in sort_options.iter() {271 for option in sort_options.iter() {
255 <option value=(option.value) selected=(option.selected)>(option.label)</option>272 <option value=(option.value) selected=(option.selected)>(option.label)</option>
@@ -271,6 +288,9 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
271 <div class="issue-title-line">288 <div class="issue-title-line">
272 <a class="issue-title" href=(row.href.as_str())>(row.title.as_str())</a>289 <a class="issue-title" href=(row.href.as_str())>(row.title.as_str())</a>
273 <span class=(row.badge_class)>(row.badge_label)</span>290 <span class=(row.badge_class)>(row.badge_label)</span>
291+ if row.draft {
292+ <span class="issue-badge issue-badge-draft">(draft_label)</span>
293+ }
274 for chip in row.labels.iter() {294 for chip in row.labels.iter() {
275 <a class=(chip.class.as_str()) href=(chip.href.as_str())>(chip.name.as_str())</a>295 <a class=(chip.class.as_str()) href=(chip.href.as_str())>(chip.name.as_str())</a>
276 }296 }
crates/forge-web/src/pages/pulls_merge.rsmodified+398 -11
@@ -4,18 +4,21 @@
4 //! they cannot read it at all, 403 when they can read but not write). The base repo must not be4 //! they cannot read it at all, 403 when they can read but not write). The base repo must not be
5 //! archived and the pull request must be open with its head repo still present.5 //! archived and the pull request must be open with its head repo still present.
6 //!6 //!
7-//! The merge is computed against the current tip of the base branch. Three styles are supported:7+//! The merge is computed against the current tip of the base branch. Four styles are supported:
8-//! a merge commit, a squash commit authored by the pull request author, and a fast-forward. The8+//! a merge commit, a squash commit authored by the pull request author, a rebase that replays the
9+//! head commits with their authors, and a fast-forward. The
9 //! base ref is moved with a compare-and-swap, so a base branch that moved meanwhile is refused10 //! base ref is moved with a compare-and-swap, so a base branch that moved meanwhile is refused
10 //! with 409 instead of being overwritten. A merge is never a force push, so the pre-receive hook11 //! with 409 instead of being overwritten. A merge is never a force push, so the pre-receive hook
11 //! does not run for it. After the ref moves, the pull request is marked merged and the same12 //! does not run for it. After the ref moves, the pull request is marked merged and the same
12 //! post-update work a push gets runs (closing keywords, maintenance, mergeability of other pulls).13 //! post-update work a push gets runs (closing keywords, maintenance, mergeability of other pulls).
13 14
14 use forge_core::protection::{Protection, effective};15 use forge_core::protection::{Protection, effective};
16+use forge_core::store::commit_status::StatusState;
15 use forge_core::{Action, IssueState, MergeStyle, PullRequest, ReviewState, Role, User, authorize};17 use forge_core::{Action, IssueState, MergeStyle, PullRequest, ReviewState, Role, User, authorize};
16 use forge_git::browse::{CommitInfo, default_branch_commit};18 use forge_git::browse::{CommitInfo, default_branch_commit};
17 use forge_git::pulls::{19 use forge_git::pulls::{
18- MergeCheck, Signature, check_merge, commit_tree, is_ancestor, range_log, update_ref_cas,20+ MergeCheck, RebaseResult, Signature, check_merge, commit_tree, is_ancestor, range_log,
21+ rebase_commits, update_ref_cas,
19 };22 };
20 use forge_git::repo::repo_path;23 use forge_git::repo::repo_path;
21 use http::HeaderValue;24 use http::HeaderValue;
@@ -61,7 +64,12 @@ pub const ERR_MESSAGE_INVALID: &str = "message_invalid";
61 pub const ERR_NEEDS_APPROVALS: &str = "needs_approvals";64 pub const ERR_NEEDS_APPROVALS: &str = "needs_approvals";
62 pub const ERR_CHANGES_REQUESTED: &str = "changes_requested";65 pub const ERR_CHANGES_REQUESTED: &str = "changes_requested";
63 pub const ERR_NOT_UP_TO_DATE: &str = "not_up_to_date";66 pub const ERR_NOT_UP_TO_DATE: &str = "not_up_to_date";
67+pub const ERR_DRAFT: &str = "draft";
68+pub const ERR_NEEDS_CHECKS: &str = "needs_checks";
69+pub const ERR_REBASE_CONFLICT: &str = "rebase_conflict";
70+pub const ERR_AUTO_MERGE_BLOCKED: &str = "auto_merge_blocked";
64 71
72+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.";
65 const CONFLICTS_MSG: &str = "This branch has conflicts that must be resolved";73 const CONFLICTS_MSG: &str = "This branch has conflicts that must be resolved";
66 const MOVED_MSG: &str = "The base branch moved; reload and try again.";74 const MOVED_MSG: &str = "The base branch moved; reload and try again.";
67 const UP_TO_DATE_MSG: &str = "Nothing to merge: the head is already contained in the base branch.";75 const UP_TO_DATE_MSG: &str = "Nothing to merge: the head is already contained in the base branch.";
@@ -77,7 +85,7 @@ const BASE_MISSING_MSG: &str = "The base branch does not exist.";
77 struct MergeForm {85 struct MergeForm {
78 #[serde(default)]86 #[serde(default)]
79 csrf: String,87 csrf: String,
80- /// `merge`, `squash` or `ff`. Empty means `merge`.88+ /// `merge`, `squash`, `rebase` or `ff`. Empty means `merge`.
81 #[serde(default)]89 #[serde(default)]
82 style: String,90 style: String,
83 /// Replaces the default commit message when not blank.91 /// Replaces the default commit message when not blank.
@@ -174,6 +182,7 @@ fn refusal_code(message: &str) -> Option<&'static str> {
174 CONFLICTS_MSG => ERR_CONFLICT,182 CONFLICTS_MSG => ERR_CONFLICT,
175 UP_TO_DATE_MSG => ERR_UP_TO_DATE,183 UP_TO_DATE_MSG => ERR_UP_TO_DATE,
176 FF_MSG => ERR_FF_IMPOSSIBLE,184 FF_MSG => ERR_FF_IMPOSSIBLE,
185+ REBASE_CONFLICT_MSG => ERR_REBASE_CONFLICT,
177 MOVED_MSG => ERR_BASE_MOVED,186 MOVED_MSG => ERR_BASE_MOVED,
178 ALREADY_MERGED_MSG => ERR_ALREADY_MERGED,187 ALREADY_MERGED_MSG => ERR_ALREADY_MERGED,
179 CLOSED_MSG => ERR_NOT_OPEN,188 CLOSED_MSG => ERR_NOT_OPEN,
@@ -225,7 +234,7 @@ pub fn counts_for_merge_rules(repo: &forge_core::Repo, user: &User, role: Option
225 }234 }
226 235
227 /// The base branch's merge rule for a pull request, with the facts that rule checks.236 /// The base branch's merge rule for a pull request, with the facts that rule checks.
228-#[derive(Debug, Clone, Copy, PartialEq, Eq)]237+#[derive(Debug, Clone, PartialEq, Eq)]
229 pub struct MergeGate {238 pub struct MergeGate {
230 pub rule: Protection,239 pub rule: Protection,
231 /// Distinct counting reviewers whose latest submitted review is an approval.240 /// Distinct counting reviewers whose latest submitted review is an approval.
@@ -234,21 +243,56 @@ pub struct MergeGate {
234 pub changes_requested: bool,243 pub changes_requested: bool,
235 /// The head contains the current base tip. Always true when the rule does not require it.244 /// The head contains the current base tip. Always true when the rule does not require it.
236 pub up_to_date: bool,245 pub up_to_date: bool,
246+ /// The pull request is a draft.
247+ pub draft: bool,
248+ /// Each required check context with its state on the head commit (`None`: not reported).
249+ pub required: Vec<RequiredCheck>,
250+}
251+
252+/// One required status check and where it stands on the pull request head.
253+#[derive(Debug, Clone, PartialEq, Eq)]
254+pub struct RequiredCheck {
255+ pub context: String,
256+ pub state: Option<StatusState>,
237 }257 }
238 258
239 impl MergeGate {259 impl MergeGate {
240- /// The refusal code for the first rule that blocks the merge, if any.260+ /// Every refusal code that currently blocks the merge, in the order they are reported.
241- pub fn blocked(&self) -> Option<&'static str> {261+ pub fn blockers(&self) -> Vec<&'static str> {
262+ let mut out = Vec::new();
263+ if self.draft {
264+ out.push(ERR_DRAFT);
265+ }
242 if self.approvals < self.rule.required_approvals {266 if self.approvals < self.rule.required_approvals {
243- return Some(ERR_NEEDS_APPROVALS);267+ out.push(ERR_NEEDS_APPROVALS);
244 }268 }
245 if self.rule.block_on_changes_requested && self.changes_requested {269 if self.rule.block_on_changes_requested && self.changes_requested {
246- return Some(ERR_CHANGES_REQUESTED);270+ out.push(ERR_CHANGES_REQUESTED);
271+ }
272+ if self
273+ .required
274+ .iter()
275+ .any(|check| check.state != Some(StatusState::Success))
276+ {
277+ out.push(ERR_NEEDS_CHECKS);
247 }278 }
248 if self.rule.require_up_to_date && !self.up_to_date {279 if self.rule.require_up_to_date && !self.up_to_date {
249- return Some(ERR_NOT_UP_TO_DATE);280+ out.push(ERR_NOT_UP_TO_DATE);
250 }281 }
251- None282+ out
283+ }
284+
285+ /// The refusal code for the first rule that blocks the merge, if any.
286+ pub fn blocked(&self) -> Option<&'static str> {
287+ self.blockers().first().copied()
288+ }
289+
290+ /// Whether waiting could clear every blocker: only missing approvals or checks that are not
291+ /// green yet. Auto-merge may be enabled only then (or when nothing blocks).
292+ pub fn waiting_only(&self) -> bool {
293+ self.blockers()
294+ .iter()
295+ .all(|code| matches!(*code, ERR_NEEDS_APPROVALS | ERR_NEEDS_CHECKS))
252 }296 }
253 }297 }
254 298
@@ -292,11 +336,28 @@ pub async fn merge_gate(
292 } else {336 } else {
293 true337 true
294 };338 };
339+ let required = if rule.required_checks.is_empty() {
340+ Vec::new()
341+ } else {
342+ let statuses = state.store.statuses_for(&repo.id, &pr.head_oid).await?;
343+ rule.required_checks
344+ .iter()
345+ .map(|context| RequiredCheck {
346+ context: context.clone(),
347+ state: statuses
348+ .iter()
349+ .find(|s| &s.context == context)
350+ .map(|s| s.state),
351+ })
352+ .collect()
353+ };
295 Ok(MergeGate {354 Ok(MergeGate {
296 rule,355 rule,
297 approvals,356 approvals,
298 changes_requested,357 changes_requested,
299 up_to_date,358 up_to_date,
359+ draft: pr.draft,
360+ required,
300 })361 })
301 }362 }
302 363
@@ -346,6 +407,17 @@ pub async fn perform_merge(
346 }407 }
347 head.to_owned()408 head.to_owned()
348 }409 }
410+ MergeStyle::Rebase => {
411+ match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? {
412+ RebaseResult::Clean { tip, count } if count > 0 => tip,
413+ RebaseResult::Clean { .. } => {
414+ return Ok(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG));
415+ }
416+ RebaseResult::Conflict { .. } => {
417+ return Ok(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG));
418+ }
419+ }
420+ }
349 MergeStyle::Merge => {421 MergeStyle::Merge => {
350 let text = match message {422 let text = match message {
351 Some(text) => text.to_owned(),423 Some(text) => text.to_owned(),
@@ -1228,4 +1300,319 @@ mod tests {
1228 assert!(clean_message(&"x".repeat(MAX_MESSAGE_BYTES + 1)).is_err());1300 assert!(clean_message(&"x".repeat(MAX_MESSAGE_BYTES + 1)).is_err());
1229 assert!(clean_message("a\0b").is_err());1301 assert!(clean_message("a\0b").is_err());
1230 }1302 }
1303+
1304+ #[tokio::test]
1305+ async fn rebase_replays_the_head_commits_with_their_author() {
1306+ let fx = fixture().await;
1307+ let number = fx
1308+ .open_feature("feature", "feature.txt", "f1", &fx.bob)
1309+ .await;
1310+ fx.advance_main("other.txt", "moved");
1311+ let before = fx.main_tip();
1312+
1313+ let reply = fx.merge(number, "rebase").await;
1314+ assert_eq!(reply.status, 303, "body: {}", reply.body);
1315+ assert_eq!(
1316+ reply.location.as_deref(),
1317+ Some(format!("/tahinli/proj/pulls/{number}").as_str())
1318+ );
1319+ let after = fx.main_tip();
1320+ assert_ne!(after, before);
1321+ // One new commit on top of the old base: no merge commit.
1322+ let parents = git(
1323+ &fx.bare,
1324+ &["rev-list", "--parents", "-n", "1", "refs/heads/main"],
1325+ );
1326+ assert_eq!(parents.split_whitespace().count(), 2, "{parents}");
1327+ assert!(parents.contains(&before));
1328+ assert_eq!(
1329+ git(&fx.bare, &["show", "refs/heads/main:feature.txt"]),
1330+ "f1"
1331+ );
1332+ assert_eq!(
1333+ git(&fx.bare, &["show", "refs/heads/main:other.txt"]),
1334+ "moved"
1335+ );
1336+ let merged = fx.pull(number).await;
1337+ assert_eq!(merged.merge_commit.as_deref(), Some(after.as_str()));
1338+ }
1339+
1340+ #[tokio::test]
1341+ async fn rebase_with_a_conflict_is_refused_and_base_unchanged() {
1342+ let fx = fixture().await;
1343+ let number = fx
1344+ .open_feature("feature", "same.txt", "feature side", &fx.bob)
1345+ .await;
1346+ fx.advance_main("same.txt", "main side");
1347+ let before = fx.main_tip();
1348+ let reply = fx.merge(number, "rebase").await;
1349+ assert_refused(&reply, number, ERR_CONFLICT);
1350+ assert_eq!(fx.main_tip(), before);
1351+ assert!(fx.pull(number).await.merged_at.is_none());
1352+ }
1353+
1354+ #[tokio::test]
1355+ async fn draft_pull_requests_cannot_merge_until_ready() {
1356+ let fx = fixture().await;
1357+ let number = fx
1358+ .open_feature("feature", "feature.txt", "f1", &fx.bob)
1359+ .await;
1360+ let pr = fx.pull(number).await;
1361+ let before = fx.main_tip();
1362+ assert!(
1363+ fx.state
1364+ .store
1365+ .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), true)
1366+ .await
1367+ .expect("draft")
1368+ );
1369+ assert_refused(&fx.merge(number, "merge").await, number, ERR_DRAFT);
1370+ assert_eq!(fx.main_tip(), before);
1371+
1372+ // The ready route is for the author or a writer, and sends the viewer back.
1373+ let reply = fx
1374+ .post(
1375+ &format!("/tahinli/proj/pulls/{number}/ready"),
1376+ Some(&fx.tahinli_cookie),
1377+ merge_form("merge", None),
1378+ )
1379+ .await;
1380+ assert_eq!(reply.status, 303, "body: {}", reply.body);
1381+ assert!(!fx.pull(number).await.draft);
1382+ let reply = fx.merge(number, "merge").await;
1383+ assert_eq!(reply.status, 303);
1384+ assert_ne!(fx.main_tip(), before);
1385+ }
1386+
1387+ #[tokio::test]
1388+ async fn required_checks_must_all_be_success_on_the_head() {
1389+ let fx = fixture().await;
1390+ let number = fx
1391+ .open_feature("feature", "feature.txt", "f1", &fx.bob)
1392+ .await;
1393+ let pr = fx.pull(number).await;
1394+ fx.state
1395+ .store
1396+ .upsert_branch_rule(
1397+ &fx.repo.id,
1398+ "main",
1399+ forge_core::protection::RuleFlags {
1400+ required_checks: vec!["ci/test".into(), "lint".into()],
1401+ ..Default::default()
1402+ },
1403+ )
1404+ .await
1405+ .expect("rule");
1406+ let before = fx.main_tip();
1407+ let report = |context: &'static str, state: StatusState| {
1408+ fx.state.store.set_status(
1409+ &fx.repo.id,
1410+ &pr.head_oid,
1411+ context,
1412+ state,
1413+ None,
1414+ None,
1415+ &fx.tahinli.id,
1416+ )
1417+ };
1418+
1419+ assert_refused(&fx.merge(number, "merge").await, number, ERR_NEEDS_CHECKS);
1420+ report("ci/test", StatusState::Success)
1421+ .await
1422+ .expect("status");
1423+ // One of two is not enough, and an unrelated context does not count.
1424+ report("other", StatusState::Success).await.expect("status");
1425+ assert_refused(&fx.merge(number, "merge").await, number, ERR_NEEDS_CHECKS);
1426+ report("lint", StatusState::Pending).await.expect("status");
1427+ assert_refused(&fx.merge(number, "merge").await, number, ERR_NEEDS_CHECKS);
1428+ report("lint", StatusState::Failure).await.expect("status");
1429+ assert_refused(&fx.merge(number, "merge").await, number, ERR_NEEDS_CHECKS);
1430+ assert_eq!(fx.main_tip(), before);
1431+
1432+ report("lint", StatusState::Success).await.expect("status");
1433+ let gate = merge_gate(&fx.state, &fx.repo, &fx.pull(number).await)
1434+ .await
1435+ .expect("gate");
1436+ assert!(gate.blocked().is_none(), "{gate:?}");
1437+ let reply = fx.merge(number, "merge").await;
1438+ assert_eq!(reply.status, 303, "body: {}", reply.body);
1439+ assert_ne!(fx.main_tip(), before);
1440+ }
1441+
1442+ fn gate_with(
1443+ approvals: u32,
1444+ need: u32,
1445+ draft: bool,
1446+ checks: &[Option<StatusState>],
1447+ ) -> MergeGate {
1448+ MergeGate {
1449+ rule: Protection {
1450+ required_approvals: need,
1451+ ..Protection::default()
1452+ },
1453+ approvals,
1454+ changes_requested: false,
1455+ up_to_date: true,
1456+ draft,
1457+ required: checks
1458+ .iter()
1459+ .enumerate()
1460+ .map(|(i, state)| RequiredCheck {
1461+ context: format!("c{i}"),
1462+ state: *state,
1463+ })
1464+ .collect(),
1465+ }
1466+ }
1467+
1468+ #[test]
1469+ fn gate_blockers_and_waiting_only() {
1470+ let open = gate_with(1, 1, false, &[Some(StatusState::Success)]);
1471+ assert!(open.blockers().is_empty() && open.waiting_only());
1472+
1473+ let waiting = gate_with(0, 1, false, &[Some(StatusState::Pending), None]);
1474+ assert_eq!(
1475+ waiting.blockers(),
1476+ vec![ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS]
1477+ );
1478+ assert!(waiting.waiting_only());
1479+
1480+ // A draft, a change request or a stale head is not something waiting fixes.
1481+ let draft = gate_with(1, 1, true, &[]);
1482+ assert_eq!(draft.blocked(), Some(ERR_DRAFT));
1483+ assert!(!draft.waiting_only());
1484+ let mut changes = gate_with(1, 1, false, &[]);
1485+ changes.rule.block_on_changes_requested = true;
1486+ changes.changes_requested = true;
1487+ assert!(!changes.waiting_only());
1488+ let mut stale = gate_with(1, 1, false, &[]);
1489+ stale.rule.require_up_to_date = true;
1490+ stale.up_to_date = false;
1491+ assert!(!stale.waiting_only());
1492+ }
1493+
1494+ #[tokio::test]
1495+ async fn auto_merge_waits_then_merges_when_a_status_arrives() {
1496+ let fx = fixture().await;
1497+ let number = fx
1498+ .open_feature("feature", "feature.txt", "f1", &fx.bob)
1499+ .await;
1500+ let pr = fx.pull(number).await;
1501+ fx.state
1502+ .store
1503+ .upsert_branch_rule(
1504+ &fx.repo.id,
1505+ "main",
1506+ forge_core::protection::RuleFlags {
1507+ required_checks: vec!["ci/test".into()],
1508+ ..Default::default()
1509+ },
1510+ )
1511+ .await
1512+ .expect("rule");
1513+ let before = fx.main_tip();
1514+
1515+ // Enable through the route: it is blocked only by a missing check, so it is accepted.
1516+ let mut form = form_urlencoded::Serializer::new(String::new());
1517+ form.append_pair("csrf", CSRF)
1518+ .append_pair("style", "squash");
1519+ let reply = fx
1520+ .post(
1521+ &format!("/tahinli/proj/pulls/{number}/auto-merge"),
1522+ Some(&fx.tahinli_cookie),
1523+ form.finish(),
1524+ )
1525+ .await;
1526+ assert_eq!(reply.status, 303, "body: {}", reply.body);
1527+ assert_eq!(
1528+ reply.location.as_deref(),
1529+ Some(format!("/tahinli/proj/pulls/{number}").as_str())
1530+ );
1531+ let waiting = fx.pull(number).await;
1532+ let auto = waiting.auto_merge.expect("auto-merge is on");
1533+ assert_eq!(auto.user_id, fx.tahinli.id);
1534+ assert_eq!(fx.main_tip(), before);
1535+
1536+ // A pending status changes nothing; the success status triggers the merge.
1537+ let report = |state: StatusState| {
1538+ fx.state.store.set_status(
1539+ &fx.repo.id,
1540+ &pr.head_oid,
1541+ "ci/test",
1542+ state,
1543+ None,
1544+ None,
1545+ &fx.tahinli.id,
1546+ )
1547+ };
1548+ report(StatusState::Pending).await.expect("pending");
1549+ crate::automerge::on_status(&fx.state, &fx.repo.id, &pr.head_oid).await;
1550+ assert_eq!(fx.main_tip(), before);
1551+ report(StatusState::Success).await.expect("success");
1552+ crate::automerge::on_status(&fx.state, &fx.repo.id, &pr.head_oid).await;
1553+
1554+ assert_ne!(fx.main_tip(), before);
1555+ let merged = fx.pull(number).await;
1556+ assert!(merged.merged_at.is_some());
1557+ assert_eq!(merged.merged_by.as_deref(), Some(fx.tahinli.id.as_str()));
1558+ assert!(merged.auto_merge.is_none());
1559+ // Squash: a single parent.
1560+ let parents = git(
1561+ &fx.bare,
1562+ &["rev-list", "--parents", "-n", "1", "refs/heads/main"],
1563+ );
1564+ assert_eq!(parents.split_whitespace().count(), 2);
1565+ }
1566+
1567+ #[tokio::test]
1568+ async fn auto_merge_is_refused_for_a_draft_and_disabled_by_a_push() {
1569+ let fx = fixture().await;
1570+ let number = fx
1571+ .open_feature("feature", "feature.txt", "f1", &fx.bob)
1572+ .await;
1573+ let pr = fx.pull(number).await;
1574+ fx.state
1575+ .store
1576+ .upsert_branch_rule(
1577+ &fx.repo.id,
1578+ "main",
1579+ forge_core::protection::RuleFlags {
1580+ required_approvals: 1,
1581+ ..Default::default()
1582+ },
1583+ )
1584+ .await
1585+ .expect("rule");
1586+ let mut form = form_urlencoded::Serializer::new(String::new());
1587+ form.append_pair("csrf", CSRF).append_pair("style", "merge");
1588+ let body = form.finish();
1589+ let path = format!("/tahinli/proj/pulls/{number}/auto-merge");
1590+
1591+ // A draft is not waiting on anything that arrives by itself.
1592+ fx.state
1593+ .store
1594+ .set_pull_draft(&pr.issue.id, None, true)
1595+ .await
1596+ .expect("draft");
1597+ let reply = fx.post(&path, Some(&fx.tahinli_cookie), body.clone()).await;
1598+ assert_refused(&reply, number, ERR_AUTO_MERGE_BLOCKED);
1599+ assert!(fx.pull(number).await.auto_merge.is_none());
1600+
1601+ fx.state
1602+ .store
1603+ .set_pull_draft(&pr.issue.id, None, false)
1604+ .await
1605+ .expect("ready");
1606+ let reply = fx.post(&path, Some(&fx.tahinli_cookie), body).await;
1607+ assert_eq!(reply.status, 303);
1608+ assert!(fx.pull(number).await.auto_merge.is_some());
1609+
1610+ // A new head commit switches it off.
1611+ fx.state
1612+ .store
1613+ .update_pull_head(&pr.issue.id, &"c".repeat(40))
1614+ .await
1615+ .expect("push");
1616+ assert!(fx.pull(number).await.auto_merge.is_none());
1617+ }
1231 }1618 }
crates/forge-web/src/pages/repo_settings.rsmodified+50 -2
@@ -8,7 +8,8 @@
8 use std::path::Path;8 use std::path::Path;
9 9
10 use forge_core::protection::{10 use forge_core::protection::{
11- BranchRule, RuleFlags, pattern_matches, validate_pattern, validate_required_approvals,11+ BranchRule, RuleFlags, normalize_required_checks, pattern_matches, validate_pattern,
12+ validate_required_approvals,
12 };13 };
13 use forge_core::store::MAX_DESCRIPTION_CHARS;14 use forge_core::store::MAX_DESCRIPTION_CHARS;
14 use forge_core::{AuditAction, Repo as RepoRow, Visibility};15 use forge_core::{AuditAction, Repo as RepoRow, Visibility};
@@ -126,6 +127,9 @@ struct BranchForm {
126 require_up_to_date: Option<String>,127 require_up_to_date: Option<String>,
127 #[serde(default)]128 #[serde(default)]
128 restrict_push: Option<String>,129 restrict_push: Option<String>,
130+ /// Required check contexts, separated by commas or new lines.
131+ #[serde(default)]
132+ required_checks: String,
129 }133 }
130 134
131 #[derive(Deserialize)]135 #[derive(Deserialize)]
@@ -422,6 +426,12 @@ fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFl
422 raw.parse::<u32>().map_err(|_| approvals_msg())?426 raw.parse::<u32>().map_err(|_| approvals_msg())?
423 };427 };
424 validate_required_approvals(required_approvals).map_err(|_| approvals_msg())?;428 validate_required_approvals(required_approvals).map_err(|_| approvals_msg())?;
429+ let listed: Vec<String> = form
430+ .required_checks
431+ .split([',', '\n', '\r'])
432+ .map(str::to_owned)
433+ .collect();
434+ let required_checks = normalize_required_checks(&listed).map_err(|e| e.to_string())?;
425 Ok(RuleFlags {435 Ok(RuleFlags {
426 allow_force_push: form.allow_force_push.is_some(),436 allow_force_push: form.allow_force_push.is_some(),
427 allow_deletion: form.allow_deletion.is_some(),437 allow_deletion: form.allow_deletion.is_some(),
@@ -429,6 +439,7 @@ fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFl
429 block_on_changes_requested: form.block_on_changes_requested.is_some(),439 block_on_changes_requested: form.block_on_changes_requested.is_some(),
430 require_up_to_date: form.require_up_to_date.is_some(),440 require_up_to_date: form.require_up_to_date.is_some(),
431 restrict_push: form.restrict_push.is_some(),441 restrict_push: form.restrict_push.is_some(),
442+ required_checks,
432 })443 })
433 }444 }
434 445
@@ -447,6 +458,9 @@ fn rule_summary(lang: Lang, rule: &BranchRule) -> String {
447 if rule.restrict_push {458 if rule.restrict_push {
448 parts.push(g::t(lang, K::RuleRestrictPush).to_owned());459 parts.push(g::t(lang, K::RuleRestrictPush).to_owned());
449 }460 }
461+ if !rule.required_checks.is_empty() {
462+ parts.push(g::checks_count(lang, rule.required_checks.len()));
463+ }
450 if parts.is_empty() {464 if parts.is_empty() {
451 g::t(lang, K::NoRule).to_owned()465 g::t(lang, K::NoRule).to_owned()
452 } else {466 } else {
@@ -516,6 +530,8 @@ async fn branch_rule_form(
516 block_on_changes_requested: bool,530 block_on_changes_requested: bool,
517 require_up_to_date: bool,531 require_up_to_date: bool,
518 restrict_push: bool,532 restrict_push: bool,
533+ required_checks: String,
534+ contexts: Vec<String>,
519 error: Option<String>,535 error: Option<String>,
520 ) -> Result<impl View> {536 ) -> Result<impl View> {
521 Ok(view! {537 Ok(view! {
@@ -554,6 +570,19 @@ async fn branch_rule_form(
554 <input type="checkbox" name="restrict_push" value="on" checked=(restrict_push)>570 <input type="checkbox" name="restrict_push" value="on" checked=(restrict_push)>
555 <span>(g::t(lang, K::RestrictPush))</span>571 <span>(g::t(lang, K::RestrictPush))</span>
556 </label>572 </label>
573+ <label>
574+ <span>(g::t(lang, K::RequiredChecks))</span>
575+ <input type="text" name="required_checks" value=(required_checks.as_str()) autocomplete="off" spellcheck="false" placeholder="ci/test, ci/lint">
576+ </label>
577+ <p class="muted small">(g::t(lang, K::RequiredChecksHelp))</p>
578+ if !contexts.is_empty() {
579+ <div class="context-picker">
580+ <span class="muted small">(g::t(lang, K::RecentContexts))</span>
581+ for context in contexts.iter() {
582+ <button type="button" class="context-chip" data-check-add=(context.as_str())>(context.as_str())</button>
583+ }
584+ </div>
585+ }
557 <div>586 <div>
558 <button type="submit">(g::t(lang, K::SaveRule))</button>587 <button type="submit">(g::t(lang, K::SaveRule))</button>
559 </div>588 </div>
@@ -570,6 +599,7 @@ struct RuleDraft {
570 block_on_changes_requested: bool,599 block_on_changes_requested: bool,
571 require_up_to_date: bool,600 require_up_to_date: bool,
572 restrict_push: bool,601 restrict_push: bool,
602+ required_checks: String,
573 error: Option<String>,603 error: Option<String>,
574 }604 }
575 605
@@ -584,6 +614,7 @@ impl RuleDraft {
584 block_on_changes_requested: false,614 block_on_changes_requested: false,
585 require_up_to_date: false,615 require_up_to_date: false,
586 restrict_push: false,616 restrict_push: false,
617+ required_checks: String::new(),
587 error: None,618 error: None,
588 }619 }
589 }620 }
@@ -596,6 +627,8 @@ struct SettingsView {
596 notice: Option<(K, bool)>,627 notice: Option<(K, bool)>,
597 draft: RuleDraft,628 draft: RuleDraft,
598 delete_error: Option<String>,629 delete_error: Option<String>,
630+ /// Recently reported status contexts, offered as required-check suggestions.
631+ contexts: Vec<String>,
599 }632 }
600 633
601 /// The settings body: the repo header tabs with Settings active, the sub-navigation, the General634 /// The settings body: the repo header tabs with Settings active, the sub-navigation, the General
@@ -623,6 +656,7 @@ async fn settings_body(
623 notice,656 notice,
624 draft,657 draft,
625 delete_error,658 delete_error,
659+ contexts,
626 } = page;660 } = page;
627 let (description, visibility) = (head.description.clone(), head.visibility);661 let (description, visibility) = (head.description.clone(), head.visibility);
628 let discussions_on = head.discussions;662 let discussions_on = head.discussions;
@@ -651,6 +685,7 @@ async fn settings_body(
651 required_approvals: draft.required_approvals,685 required_approvals: draft.required_approvals,
652 block_on_changes_requested: draft.block_on_changes_requested,686 block_on_changes_requested: draft.block_on_changes_requested,
653 require_up_to_date: draft.require_up_to_date, restrict_push: draft.restrict_push,687 require_up_to_date: draft.require_up_to_date, restrict_push: draft.restrict_push,
688+ required_checks: draft.required_checks, contexts: contexts,
654 error: draft.error)689 error: draft.error)
655 </section>690 </section>
656 discussions_card(lang: lang, action: format!("/{title}/settings/discussions"), csrf: csrf.clone(), enabled: discussions_on)691 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<impl View> {
705 notice: take_settings_notice(cx),740 notice: take_settings_notice(cx),
706 draft: RuleDraft::for_default_branch(&ctx.repo.default_branch),741 draft: RuleDraft::for_default_branch(&ctx.repo.default_branch),
707 delete_error: None,742 delete_error: None,
743+ contexts: app_context::<AppState>(cx)
744+ .store
745+ .recent_status_contexts(&ctx.repo.id, 20)
746+ .await?,
708 };747 };
709 let csrf = session.csrf_token.clone();748 let csrf = session.csrf_token.clone();
710 let frame = SettingsFrame::new(&ctx, app_context::<AppState>(cx), lang).await?;749 let frame = SettingsFrame::new(&ctx, app_context::<AppState>(cx), lang).await?;
@@ -1006,6 +1045,10 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
1006 notice: None,1045 notice: None,
1007 draft: RuleDraft::for_default_branch(&ctx.repo.default_branch),1046 draft: RuleDraft::for_default_branch(&ctx.repo.default_branch),
1008 delete_error: error,1047 delete_error: error,
1048+ contexts: app_context::<AppState>(cx)
1049+ .store
1050+ .recent_status_contexts(&ctx.repo.id, 20)
1051+ .await?,
1009 };1052 };
1010 let csrf = session.csrf_token.clone();1053 let csrf = session.csrf_token.clone();
1011 let frame = SettingsFrame::new(&ctx, app_context::<AppState>(cx), lang).await?;1054 let frame = SettingsFrame::new(&ctx, app_context::<AppState>(cx), lang).await?;
@@ -1054,9 +1097,14 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i
1054 block_on_changes_requested: form.block_on_changes_requested.is_some(),1097 block_on_changes_requested: form.block_on_changes_requested.is_some(),
1055 require_up_to_date: form.require_up_to_date.is_some(),1098 require_up_to_date: form.require_up_to_date.is_some(),
1056 restrict_push: form.restrict_push.is_some(),1099 restrict_push: form.restrict_push.is_some(),
1100+ required_checks: form.required_checks.clone(),
1057 error: Some(message),1101 error: Some(message),
1058 },1102 },
1059 delete_error: None,1103 delete_error: None,
1104+ contexts: app_context::<AppState>(cx)
1105+ .store
1106+ .recent_status_contexts(&ctx.repo.id, 20)
1107+ .await?,
1060 };1108 };
1061 let csrf = session.csrf_token.clone();1109 let csrf = session.csrf_token.clone();
1062 let frame = SettingsFrame::new(&ctx, app_context::<AppState>(cx), lang).await?;1110 let frame = SettingsFrame::new(&ctx, app_context::<AppState>(cx), lang).await?;
@@ -1073,7 +1121,7 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i
1073 let state = app_context::<AppState>(cx);1121 let state = app_context::<AppState>(cx);
1074 state1122 state
1075 .store1123 .store
1076- .upsert_branch_rule(&ctx.repo.id, &pattern, flags)1124+ .upsert_branch_rule(&ctx.repo.id, &pattern, flags.clone())
1077 .await?;1125 .await?;
1078 tracing::info!(1126 tracing::info!(
1079 actor_id = %user.id,1127 actor_id = %user.id,
crates/forge-web/src/pulls_sync.rsmodified+12 -0
@@ -103,6 +103,18 @@ async fn sync_head(
103 let head_path = forge_git::repo::repo_path(&state.git.data_dir, &head_repo.id)?;103 let head_path = forge_git::repo::repo_path(&state.git.data_dir, &head_repo.id)?;
104 fetch_into_pull_ref(&state.git, &base_path, &head_path, new, number).await?;104 fetch_into_pull_ref(&state.git, &base_path, &head_path, new, number).await?;
105 state.store.update_pull_head(issue_id, new).await?;105 state.store.update_pull_head(issue_id, new).await?;
106+ if pr.auto_merge.is_some() {
107+ // `update_pull_head` already cleared the setting; tell the timeline why.
108+ state
109+ .store
110+ .add_event(
111+ issue_id,
112+ actor,
113+ "auto_merge_disabled",
114+ json!({"reason": "push"}),
115+ )
116+ .await?;
117+ }
106 mark_outdated_threads(state, &base_path, issue_id, new).await;118 mark_outdated_threads(state, &base_path, issue_id, new).await;
107 state119 state
108 .store120 .store
crates/forge-web/src/webhooks/payload.rsmodified+3 -0
@@ -175,6 +175,7 @@ fn pull_object(base_url: &str, repo: &Repo, pr: &PullRequest) -> Value {
175 "body": pr.issue.body,175 "body": pr.issue.body,
176 "state": pr.issue.state.as_str(),176 "state": pr.issue.state.as_str(),
177 "merged": pr.merged_at.is_some(),177 "merged": pr.merged_at.is_some(),
178+ "draft": pr.draft,
178 "base": { "ref": pr.base_branch, "sha": pr.base_oid },179 "base": { "ref": pr.base_branch, "sha": pr.base_oid },
179 "head": { "ref": pr.head_branch, "sha": pr.head_oid },180 "head": { "ref": pr.head_branch, "sha": pr.head_oid },
180 "html_url": item_url(base_url, repo, "pulls", pr.issue.number),181 "html_url": item_url(base_url, repo, "pulls", pr.issue.number),
@@ -242,6 +243,8 @@ mod tests {
242 merged_at: None,243 merged_at: None,
243 merged_by: None,244 merged_by: None,
244 merge_commit: None,245 merge_commit: None,
246+ draft: false,
247+ auto_merge: None,
245 }248 }
246 }249 }
247 250
style/main.scssmodified+112 -0
@@ -6148,3 +6148,115 @@ button.ci-job-last {
6148 .srv-form .actions {6148 .srv-form .actions {
6149 margin-top: 16px;6149 margin-top: 16px;
6150 }6150 }
6151+
6152+// Draft pull requests: a neutral grey badge, distinct from open (green) and merged (purple).
6153+.issue-badge.issue-badge-draft {
6154+ background: var(--code-bg);
6155+ color: var(--muted);
6156+ border: 1px solid var(--border);
6157+}
6158+
6159+// Required checks and flow controls inside the merge box.
6160+.required-checks {
6161+ display: flex;
6162+ flex-direction: column;
6163+ gap: 0.35rem;
6164+
6165+ p {
6166+ margin: 0;
6167+ }
6168+}
6169+
6170+.required-check-list {
6171+ display: flex;
6172+ flex-direction: column;
6173+ gap: 0.25rem;
6174+ margin: 0;
6175+ padding: 0;
6176+ list-style: none;
6177+
6178+ li {
6179+ display: flex;
6180+ flex-wrap: wrap;
6181+ align-items: center;
6182+ justify-content: space-between;
6183+ gap: 0.5rem;
6184+ padding: 0.3rem 0.6rem;
6185+ border: 1px solid var(--border);
6186+ border-radius: var(--radius-md, var(--radius-lg));
6187+ background: var(--surface);
6188+ font-size: 0.9rem;
6189+ overflow-wrap: anywhere;
6190+ }
6191+
6192+ .check-ok span {
6193+ color: var(--add-text);
6194+ font-weight: 600;
6195+ }
6196+
6197+ .check-pending span {
6198+ color: var(--muted);
6199+ }
6200+
6201+ .check-bad span {
6202+ color: var(--danger);
6203+ font-weight: 600;
6204+ }
6205+}
6206+
6207+.merge-flow {
6208+ display: flex;
6209+ flex-wrap: wrap;
6210+ align-items: center;
6211+ gap: 0.5rem 0.75rem;
6212+ margin: 0;
6213+
6214+ p {
6215+ flex: 1 1 14rem;
6216+ margin: 0;
6217+ }
6218+}
6219+
6220+// Suggested required-check contexts under the branch rule form.
6221+.context-picker {
6222+ display: flex;
6223+ flex-wrap: wrap;
6224+ align-items: center;
6225+ gap: 0.4rem;
6226+}
6227+
6228+.context-chip {
6229+ padding: 2px 10px;
6230+ border: 1px solid var(--border);
6231+ border-radius: var(--radius-full);
6232+ background: var(--surface);
6233+ font-family: var(--mono);
6234+ font-size: 0.8rem;
6235+ cursor: pointer;
6236+}
6237+
6238+.form-actions {
6239+ display: flex;
6240+ flex-wrap: wrap;
6241+ gap: 0.5rem;
6242+}
6243+
6244+// Secondary actions in the merge box (auto-merge, draft toggle): quiet buttons, not full width.
6245+.merge-box .merge-flow button[type="submit"] {
6246+ width: auto;
6247+ padding: 0 14px;
6248+ border-color: var(--border);
6249+ background: var(--surface);
6250+ color: var(--text);
6251+ font-weight: 500;
6252+
6253+ &:hover {
6254+ border-color: var(--accent);
6255+ background: var(--surface);
6256+ }
6257+}
6258+
6259+.merge-box .merge-flow select {
6260+ width: auto;
6261+ min-width: 12rem;
6262+}