From cd5c4ab776004b841ddbf0106ad0c104ef3280b4 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:40:51 -0800 Subject: [PATCH 1/3] feat: pin required checks to an app, manage org Actions workflow settings A required check may be written as {context: , app_id: }; plain names keep working and mean no pin. sync sends the pin as integration_id, diff and the no-op check compare it, and sync-from-org writes it back. A top-level actions block holds the org's default_workflow_permissions and can_approve_pull_request_reviews (PUT /orgs/{org}/actions/permissions/workflow). Without the block they are left alone and not compared. --- README.md | 19 ++++- docs/changelog.md | 2 + docs/usage.md | 7 +- src/config.rs | 138 ++++++++++++++++++++++++++++++-- src/github.rs | 195 ++++++++++++++++++++++++++++++++++++++-------- 5 files changed, 319 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index efc44f4..cccaf00 100644 --- a/README.md +++ b/README.md @@ -247,14 +247,17 @@ repos: ```yaml repos: - name: service - required_checks: [Format, Unit Tests, "Clippy & Docs"] + required_checks: + - Format + - "Clippy & Docs" + - {context: Unit Tests, app_id: 15368} # only GitHub Actions may post it required_checks_bypass: # optional: who may merge past the checks, and how - team: core-team mode: pull_request # only by merging a PR; `always` also allows direct pushes ``` - `sync` keeps them in the repo's own ruleset named `Require CI`: active, on the default branch (`~DEFAULT_BRANCH`), not strict (a PR needn't be up to date with the branch), one `required_status_checks` rule. It creates the ruleset if the repo has none by that name and rewrites it when its checks (in any order) or any of those properties differ. An existing `Require CI` ruleset is adopted by name. -- A check the ruleset already pins to an app (`integration_id`, e.g. GitHub Actions) keeps that pin when `sync` rewrites the ruleset; a new check gets none. The pin isn't part of the config or the drift check. +- A check is its name, which any app may post, or `{context: , app_id: }`, which only that GitHub App may post (the ruleset's `integration_id`; GitHub Actions is `15368`). The pin is part of the check: a ruleset whose check has no pin, or another app's, is rewritten by `sync` and shown by `diff`, and a plain name drops a pin the ruleset has. `sync-from-org` writes each pin back. A pin stops another app or a commit status (which has no app) from satisfying the check; it doesn't stop a workflow in the PR itself from posting a check run with the same name. - `allow_auto_merge` is written after the repo's `Require CI` ruleset, so if the ruleset write fails, auto-merge isn't left on without the checks it waits for. - A name listed twice is refused when the config is loaded. A `Require CI` ruleset that requires one check twice (from different apps) is refused like one with another rule: a config can't say which pin to keep. - gh-config owns every rule in `Require CI`: if it holds any other rule, `sync` stops with an error naming the repo and the rule instead of dropping it. Keep other rules in other rulesets. @@ -263,6 +266,18 @@ repos: - A repo with no `required_checks` is left alone: `sync` doesn't read or delete its rulesets. To stop requiring checks, delete the ruleset on GitHub and the key. - `sync-from-org` records the checks of each repo's `Require CI` ruleset, in the file's order when the file names the same ones; `diff` compares them as a set. It costs one rulesets request per repo, plus one when `Require CI` exists. A ruleset that can't be read keeps what the file has, and `diff` names the repo and exits 1. It records the bypass list too, reading team ids as slugs (one teams request in all). GitHub shows a ruleset's bypass list only to a token that can administer the repo; when it doesn't, or the list holds anything other than the org's teams, the file's list is kept and `diff` names the repo and exits 1. A ruleset that requires no checks is recorded without them and without a bypass list (a config can't hold a bypass list alone), and `sync-from-org` never writes a config that wouldn't load: it stops and leaves the file as it is. Properties other than the checks and the bypass list aren't recorded, so `diff` shows no change when only those differ; `sync` still corrects them. +### Org Actions settings + +```yaml +actions: + default_workflow_permissions: read # read or write: what a workflow's GITHUB_TOKEN gets by default + can_approve_pull_request_reviews: false # whether Actions may create and approve PRs +``` + +- The org's Actions workflow settings (GitHub's `/orgs/{org}/actions/permissions/workflow`). Both keys are required; leave the whole block out and `sync` leaves them alone and `diff` doesn't compare them. +- `sync` reads them and writes both, with one PUT, only when they differ; `--dry-run` prints the change. It writes them after checking the config's bypass lists and before teams and repos. +- `sync-from-org` records them. If they can't be read (the token needs org administration access), a file that has the block keeps it and `diff` names the org and exits 1; a file without it stays without it. + ### Webhooks A repo gets a webhook only if the config says so: its own `webhook`, or `use_default_webhook: true` for the org's `default_webhook`. Being listed connects nothing, and `sync` never deletes a webhook. diff --git a/docs/changelog.md b/docs/changelog.md index 5b732bc..083bcfc 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -8,6 +8,8 @@ All notable changes to this project will be documented in this file. - `sync-from-org` and `diff` record `allow_auto_merge` and private repos' Actions `access_level`, so the drift check keeps them; `sync` reads `access_level` before writing it. - New repo field `required_checks`, kept in the repo ruleset `Require CI`. - New repo field `required_checks_bypass`: the teams, and only those, that may bypass `Require CI` (`pull_request` or `always`). `sync` writes it, `sync-from-org` and `diff` read it back. +- A required check can be pinned to the app that must post it: `{context: , app_id: }`. The pin is part of the check for `sync`, `diff` and `sync-from-org`; a plain name now means no pin, so `sync` drops a pin the config doesn't name instead of keeping it. +- New top-level `actions` block: the org's `default_workflow_permissions` and `can_approve_pull_request_reviews`. `sync` writes them, `sync-from-org` and `diff` read them back; without the block they're left alone. ## [v1.3.2] - 2026-11-09 diff --git a/docs/usage.md b/docs/usage.md index 4b34ef9..f578719 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -41,6 +41,10 @@ The configuration file is written in YAML and describes your organization, repos ```yaml org: gitkb # (string) Name of the GitHub organization +actions: # (object, optional) Org Actions workflow settings; absent: left alone + default_workflow_permissions: read # (string) read or write: a workflow's default GITHUB_TOKEN permissions + can_approve_pull_request_reviews: false # (bool) Whether Actions may create and approve PRs + repos: # (list) Repository configurations - name: my-repo # (string) Repository name settings: # (map) GitHub repo settings from the API mapping (see below) @@ -52,7 +56,8 @@ repos: # (list) Repository configurations access_level: organization # (string, private repos only) Who may call this repo's workflows: none, user, organization visibility: private # (string, optional) "public" or "private"; required for sync to create a missing repo required_checks: # (list, optional) Checks a PR to the default branch must pass (ruleset `Require CI`) - - Unit Tests + - Unit Tests # A name: any app may post it + - {context: "gate / CI gate", app_id: 15368} # Pinned: only this GitHub App (15368 is GitHub Actions) required_checks_bypass: # (list, optional) The only teams that may merge past required_checks - team: core-team # (string) Team slug mode: pull_request # (string) pull_request (by merging a PR) or always (also direct pushes) diff --git a/src/config.rs b/src/config.rs index 073b148..1814582 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,7 +3,7 @@ //! This module defines the data structures used for representing repository, team, user, and webhook //! configuration. All structs are serializable/deserializable for use with YAML and JSON configuration files. -use serde::{Deserialize, Serialize}; +use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use serde_yaml::Value; use std::collections::BTreeMap; @@ -84,16 +84,70 @@ pub struct Repo { pub webhook: Option, #[serde(default)] pub branch_protections: Vec, - /// Status checks that must pass before a PR merges to the default branch, held in the repo's - /// `Require CI` ruleset. Empty: `sync` leaves the repo's rulesets alone. + /// Status checks that must pass before a PR merges to the default branch, each pinned to the app that must + /// post it or to none, held in the repo's `Require CI` ruleset. Empty: `sync` leaves the repo's rulesets alone. #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub required_checks: Vec, + pub required_checks: Vec, /// The teams that may merge past `required_checks`, and how. Nobody else can: `sync` makes the ruleset's /// bypass list exactly this, so leaving it out removes every bypass. Needs `required_checks`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub required_checks_bypass: Vec, } +/// A required status check: its name, and the GitHub App that must post it, if pinned (GitHub's `integration_id`). +/// Written as the name alone (any app may post it) or as `{context: , app_id: }`. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct RequiredCheck { + pub context: String, + pub app_id: Option, +} + +/// The pinned form of a `RequiredCheck`. +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct PinnedCheck { + context: String, + app_id: u64, +} + +impl Serialize for RequiredCheck { + fn serialize(&self, serializer: S) -> Result { + match self.app_id { + None => serializer.serialize_str(&self.context), + Some(app_id) => PinnedCheck { context: self.context.clone(), app_id }.serialize(serializer), + } + } +} + +impl<'de> Deserialize<'de> for RequiredCheck { + fn deserialize>(deserializer: D) -> Result { + struct Check; + impl<'de> de::Visitor<'de> for Check { + type Value = RequiredCheck; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a check name, or `{context: , app_id: }`") + } + fn visit_str(self, name: &str) -> Result { + Ok(RequiredCheck { context: name.to_string(), app_id: None }) + } + fn visit_map>(self, map: A) -> Result { + let pinned = PinnedCheck::deserialize(de::value::MapAccessDeserializer::new(map))?; + Ok(RequiredCheck { context: pinned.context, app_id: Some(pinned.app_id) }) + } + } + deserializer.deserialize_any(Check) + } +} + +impl std::fmt::Display for RequiredCheck { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self.app_id { + None => f.write_str(&self.context), + Some(app_id) => write!(f, "{} (app {app_id})", self.context), + } + } +} + #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord)] #[serde(deny_unknown_fields)] /// A team that may bypass a repo's `required_checks`. @@ -122,6 +176,35 @@ impl BypassMode { } } +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] +#[serde(deny_unknown_fields)] +/// The org's Actions workflow settings (GitHub's `/orgs/{org}/actions/permissions/workflow`). +pub struct OrgActions { + /// What the `GITHUB_TOKEN` of a workflow run may do by default. + pub default_workflow_permissions: WorkflowPermissions, + /// Whether Actions may create and approve pull requests. + pub can_approve_pull_request_reviews: bool, +} + +#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +/// GitHub's `default_workflow_permissions`. +pub enum WorkflowPermissions { + /// Read the repo's contents and packages. + Read, + /// Read and write every permission. + Write, +} + +impl WorkflowPermissions { + pub fn as_str(self) -> &'static str { + match self { + WorkflowPermissions::Read => "read", + WorkflowPermissions::Write => "write", + } + } +} + #[derive(Debug, Serialize, Deserialize, Clone)] // Added Clone #[serde(deny_unknown_fields)] /// @@ -177,6 +260,9 @@ pub struct Assignment { pub struct Config { /// The name of the GitHub organization. pub org: String, + /// The org's Actions workflow settings. Absent: `sync` leaves them alone. + #[serde(default)] + pub actions: Option, /// List of repository configurations. #[serde(default)] pub repos: Vec, @@ -226,7 +312,7 @@ impl Config { let all = crate::github_api_mapping_generated::get_github_api_mapping(); for (i, repo) in config.repos.iter().enumerate() { let checks = &repo.required_checks; - if let Some(dup) = checks.iter().enumerate().find_map(|(j, c)| checks.iter().take(j).any(|x| x == c).then_some(c)) { + if let Some(dup) = checks.iter().enumerate().find_map(|(j, c)| checks.iter().take(j).any(|x| x.context == c.context).then_some(&c.context)) { return Err(crate::error::AppError::Config(format!( "{main_path}: repos[{i}].required_checks (repo {}): `{dup}` is listed twice.", repo.name @@ -429,6 +515,48 @@ allow_force_pushes: false assert!(err.contains("required_checks") && err.contains("`A` is listed twice"), "{err}"); } + #[test] + fn a_check_is_a_name_or_a_name_pinned_to_an_app() { + let load = |checks: &str| { + let mut file = tempfile::NamedTempFile::new().unwrap(); + std::io::Write::write_all(&mut file, format!("org: o\nrepos:\n- name: r\n required_checks: {checks}\n").as_bytes()).unwrap(); + Config::from_file_with_defaults(file.path().to_str().unwrap(), None).map_err(|e| e.to_string()) + }; + let ok = load(r#"[A, {context: "gate / CI gate", app_id: 15368}]"#).unwrap(); + assert_eq!( + ok.repos[0].required_checks, + [RequiredCheck { context: "A".into(), app_id: None }, RequiredCheck { context: "gate / CI gate".into(), app_id: Some(15368) }] + ); + for (checks, expected) in [ + ("[{context: A, appid: 1}]", "unknown field `appid`"), + ("[{context: A}]", "missing field `app_id`"), + ("[{context: A, app_id: actions}]", "required_checks[0].app_id"), + ("[A, {context: A, app_id: 1}]", "`A` is listed twice"), + ] { + let err = load(checks).unwrap_err(); + assert!(err.contains("required_checks") && err.contains(expected), "{checks}: {err}"); + } + } + + #[test] + fn org_actions_take_both_settings_and_nothing_else() { + let load = |actions: &str| { + let mut file = tempfile::NamedTempFile::new().unwrap(); + std::io::Write::write_all(&mut file, format!("org: o\nactions: {actions}\n").as_bytes()).unwrap(); + Config::from_file_with_defaults(file.path().to_str().unwrap(), None).map_err(|e| e.to_string()) + }; + let ok = load("{default_workflow_permissions: read, can_approve_pull_request_reviews: false}").unwrap(); + assert_eq!(ok.actions, Some(OrgActions { default_workflow_permissions: WorkflowPermissions::Read, can_approve_pull_request_reviews: false })); + for (actions, expected) in [ + ("{default_workflow_permissions: admin, can_approve_pull_request_reviews: false}", "unknown variant `admin`"), + ("{default_workflow_permissions: read, can_approve_pull_request_reviews: false, can_approve: true}", "unknown field `can_approve`"), + ("{default_workflow_permissions: read}", "missing field `can_approve_pull_request_reviews`"), + ] { + let err = load(actions).unwrap_err(); + assert!(err.contains("actions") && err.contains(expected), "{actions}: {err}"); + } + } + #[test] fn a_bypass_list_names_known_teams_once_with_a_known_mode_and_needs_checks() { let load = |text: &str| { diff --git a/src/github.rs b/src/github.rs index 64b6042..b525058 100644 --- a/src/github.rs +++ b/src/github.rs @@ -9,7 +9,7 @@ Public APIs are documented for maintainability. Internal response structs are used for deserialization. */ -use crate::config::{Assignment, BypassMode, CheckBypass, Repo, RepoSettings, Team, User, WebhookConfig, Config}; +use crate::config::{Assignment, BypassMode, CheckBypass, Config, OrgActions, Repo, RepoSettings, RequiredCheck, Team, User, WebhookConfig}; use crate::error::{AppError, AppResult}; use colored::*; use log::{debug, info, error}; @@ -43,13 +43,6 @@ fn omitted_defaults() -> [(&'static str, serde_yaml::Value); 3] { ] } -/// One required status check. `integration_id`, when GitHub has one, pins the check to the app that must post it. -#[derive(Debug, Clone, PartialEq)] -struct RequiredCheck { - context: String, - integration_id: Option, -} - /// One entry of a ruleset's bypass list, as GitHub holds it: a team, an app, a role, the org's admins... #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] struct BypassActor { @@ -127,12 +120,6 @@ struct RequireCi { standard: bool, } -impl RequireCi { - fn contexts(&self) -> Vec { - self.checks.iter().map(|c| c.context.clone()).collect() - } -} - /// The `Require CI` ruleset `sync` writes for `checks`, which only `bypass` may merge past. fn require_ci_body(checks: &[RequiredCheck], bypass: &[BypassActor]) -> serde_json::Value { let bypass: Vec<_> = bypass @@ -144,7 +131,7 @@ fn require_ci_body(checks: &[RequiredCheck], bypass: &[BypassActor]) -> serde_js .collect(); let checks: Vec<_> = checks .iter() - .map(|c| match c.integration_id { + .map(|c| match c.app_id { Some(id) => json!({ "context": c.context, "integration_id": id }), None => json!({ "context": c.context }), }) @@ -183,7 +170,7 @@ fn parse_require_ci(repo: &str, ruleset: &serde_json::Value) -> AppResult AppResult bool { +/// Whether two check lists hold the same checks, each pinned to the same app, in any order. +fn same_checks(a: &[RequiredCheck], b: &[RequiredCheck]) -> bool { let mut a = a.to_vec(); let mut b = b.to_vec(); a.sort(); @@ -521,6 +508,38 @@ impl GitHubClient { .collect() } + /// The org's Actions workflow settings. + async fn read_org_actions(&self) -> AppResult { + let url = format!("{}/orgs/{}/actions/permissions/workflow", self.api_url, self.org); + let held: serde_json::Value = serde_json::from_str(&self.get(&url).await?.text().await?) + .map_err(|e| AppError::GitHubApi(format!("Failed to parse response from {}: {}", url, e)))?; + // Only the fields a config holds: GitHub may add others. + let fields = json!({ + "default_workflow_permissions": held["default_workflow_permissions"], + "can_approve_pull_request_reviews": held["can_approve_pull_request_reviews"], + }); + serde_json::from_value(fields).map_err(|e| AppError::GitHubApi(format!("Unexpected response from {}: {}", url, e))) + } + + /// Makes the org's Actions workflow settings `actions`, writing only when they differ. + async fn sync_org_actions(&self, actions: &OrgActions, dry_run: bool) -> AppResult<()> { + let held = self.read_org_actions().await?; + if held == *actions { + return Ok(()); + } + let describe = |a: &OrgActions| { + format!("default_workflow_permissions: {}, can_approve_pull_request_reviews: {}", a.default_workflow_permissions.as_str(), a.can_approve_pull_request_reviews) + }; + if dry_run { + println!("[Dry Run] Would set the Actions workflow settings of {} to {} (now {})", self.org, describe(actions), describe(&held)); + return Ok(()); + } + let url = format!("{}/orgs/{}/actions/permissions/workflow", self.api_url, self.org); + self.send_put(&url, Some(serde_json::to_value(actions)?)).await?; + info!("Actions workflow settings of {} now: {}", self.org, describe(actions)); + Ok(()) + } + /// Makes the repo's `Require CI` ruleset require exactly `repo.required_checks`, with exactly /// `repo.required_checks_bypass` allowed past them. A repo with no checks is left alone. async fn sync_required_checks(&self, repo: &Repo, teams: &TeamIds, dry_run: bool) -> AppResult<()> { @@ -531,27 +550,24 @@ impl GitHubClient { let bypass = bypass_actors(&self.org, repo, teams)?; let current = self.read_require_ci(&repo.name).await?; let held = current.as_ref().map(|c| c.checks.clone()).unwrap_or_default(); - // A check kept from the ruleset keeps the app it's pinned to; a new one has none. - let desired: Vec = checks - .iter() - .map(|name| held.iter().find(|c| &c.context == name).cloned().unwrap_or(RequiredCheck { context: name.clone(), integration_id: None })) - .collect(); let held_bypass = current.as_ref().and_then(|c| c.bypass.clone()); let (method, url) = match current { - Some(current) if current.standard && same_checks(¤t.contexts(), checks) && current.bypass.as_ref() == Some(&bypass) => return Ok(()), + Some(current) if current.standard && same_checks(¤t.checks, checks) && current.bypass.as_ref() == Some(&bypass) => return Ok(()), Some(current) => (Method::PUT, format!("{}/repos/{}/{}/rulesets/{}", self.api_url, self.org, repo.name, current.id)), None => (Method::POST, format!("{}/repos/{}/{}/rulesets", self.api_url, self.org, repo.name)), }; let verb = if method == Method::POST { "create" } else { "update" }; + let named = |checks: &[&RequiredCheck]| checks.iter().map(|c| c.to_string()).collect::>().join(", "); + let requiring = named(&checks.iter().collect::>()); if dry_run { - let removed: Vec<_> = held.iter().map(|c| c.context.as_str()).filter(|c| !checks.iter().any(|n| n == c)).collect(); - let removed = if removed.is_empty() { String::new() } else { format!("; no longer requiring: {}", removed.join(", ")) }; + let removed: Vec<_> = held.iter().filter(|c| !checks.contains(c)).collect(); + let removed = if removed.is_empty() { String::new() } else { format!("; no longer requiring: {}", named(&removed)) }; let bypass = bypass_change(&bypass, held_bypass.as_deref(), method == Method::PUT, teams); - println!("[Dry Run] Would {verb} ruleset `{REQUIRE_CI}` on {}/{} requiring: {}{removed}; {bypass}", self.org, repo.name, checks.join(", ")); + println!("[Dry Run] Would {verb} ruleset `{REQUIRE_CI}` on {}/{} requiring: {requiring}{removed}; {bypass}", self.org, repo.name); return Ok(()); } - self.client.request(method, &url, "application/vnd.github+json", Some(require_ci_body(&desired, &bypass))).await?; - info!("Ruleset `{REQUIRE_CI}` on {}/{} now requires: {}; bypass: {}", self.org, repo.name, checks.join(", "), bypass.len()); + self.client.request(method, &url, "application/vnd.github+json", Some(require_ci_body(checks, &bypass))).await?; + info!("Ruleset `{REQUIRE_CI}` on {}/{} now requires: {requiring}; bypass: {}", self.org, repo.name, bypass.len()); Ok(()) } @@ -1015,6 +1031,11 @@ impl GitHubClient { let mut yaml_content = String::new(); yaml_content.push_str(&format!("org: {}\n\n", config.org)); + if let Some(actions) = &config.actions { + yaml_content.push_str("actions:\n"); + yaml_content.push_str(&format!(" default_workflow_permissions: {}\n", actions.default_workflow_permissions.as_str())); + yaml_content.push_str(&format!(" can_approve_pull_request_reviews: {}\n\n", actions.can_approve_pull_request_reviews)); + } // Add assignments (sorted) let mut assignments = config.assignments; @@ -1092,7 +1113,11 @@ impl GitHubClient { if !repo.required_checks.is_empty() { yaml_content.push_str(" required_checks:\n"); for check in &repo.required_checks { - yaml_content.push_str(&format!(" - {}\n", serde_yaml::to_string(check)?.trim())); + let context = serde_yaml::to_string(&check.context)?; + match check.app_id { + None => yaml_content.push_str(&format!(" - {}\n", context.trim())), + Some(app_id) => yaml_content.push_str(&format!(" - context: {}\n app_id: {app_id}\n", context.trim())), + } } } if !repo.required_checks_bypass.is_empty() { @@ -1163,6 +1188,20 @@ impl GitHubClient { // This is essentially the original logic of generate_config_from_org let mut repos = Vec::new(); let mut unread = Vec::new(); + let actions = match self.read_org_actions().await { + Ok(actions) => Some(actions), + Err(e) => { + // Only a file that manages them loses anything: the others leave them alone. + let kept = file.and_then(|file| file.actions.clone()); + if kept.is_some() { + error!("Failed to read the Actions workflow settings of {}: {}. They stay as the file has them.", self.org, e); + unread.push(format!("{} (Actions workflow settings)", self.org)); + } else { + info!("Not recording the Actions workflow settings of {}: {}", self.org, e); + } + kept + } + }; let team_ids = self.team_ids().await?; let repo_url = format!("{}/orgs/{}/repos?per_page=100", self.api_url, self.org); let repo_json: Vec = self.get_all(&repo_url).await?; @@ -1239,7 +1278,7 @@ impl GitHubClient { let (required_checks, required_checks_bypass) = match self.read_require_ci(&name).await { Ok(found) => { // The file's order when it names the same checks, so regenerating doesn't reorder them. - let checks = match found.as_ref().map(RequireCi::contexts).unwrap_or_default() { + let checks = match found.as_ref().map(|r| r.checks.clone()).unwrap_or_default() { checks if same_checks(&checks, &file_checks) => file_checks, checks => checks, }; @@ -1323,6 +1362,7 @@ impl GitHubClient { let config = Config { org: self.org.clone(), + actions, repos, teams, users, @@ -1360,6 +1400,9 @@ impl GitHubClient { for repo in &config.repos { bypass_actors(&self.org, repo, &teams)?; } + if let Some(actions) = &config.actions { + self.sync_org_actions(actions, dry_run).await?; + } for team in &config.teams { info!("Processing team: {}", team.name); self.create_team(team, dry_run).await?; @@ -1474,6 +1517,10 @@ impl GitHubClient { } } } + // A config without `actions` leaves them alone, so there is nothing to compare. + if diff_local_config.actions.is_none() { + diff_github_config.actions = None; + } // Required checks and their bypass list are sets: their order means nothing. for repo in diff_local_config.repos.iter_mut().chain(diff_github_config.repos.iter_mut()) { repo.required_checks.sort(); @@ -1679,6 +1726,12 @@ mod tests { let team_list: Vec<_> = teams.iter().map(|(slug, id)| json!({"slug": slug, "name": slug, "id": id})).collect(); let mut mocks = vec![ server.mock("GET", "/orgs/o/teams?per_page=100").with_body(json!(team_list).to_string()).create_async().await, + // GitHub's defaults for a new org, plus a field a config doesn't hold. + server + .mock("GET", "/orgs/o/actions/permissions/workflow") + .with_body(r#"{"default_workflow_permissions": "write", "can_approve_pull_request_reviews": true, "other": 1}"#) + .create_async() + .await, server.mock("GET", "/orgs/o/members?per_page=100").with_body("[]").create_async().await, ]; for (slug, _) in teams { @@ -1728,7 +1781,7 @@ mod tests { /// `checks` pinned to no app. fn unpinned(checks: &[&str]) -> Vec { - checks.iter().map(|c| RequiredCheck { context: c.to_string(), integration_id: None }).collect() + checks.iter().map(|c| RequiredCheck { context: c.to_string(), app_id: None }).collect() } /// A `Require CI` ruleset with id `id` requiring `checks`, as `sync` writes it. @@ -2418,7 +2471,7 @@ assignments: } #[tokio::test] - async fn rewriting_require_ci_keeps_the_app_each_kept_check_is_pinned_to() { + async fn rewriting_require_ci_pins_each_check_to_the_configured_app() { let mut server = mockito::Server::new_async().await; let _mocks = mock_org_full(&mut server, &[("r", json!({}))], |_| json!([]), |_| None).await; // As GitHub returns it, written out by hand. @@ -2436,7 +2489,7 @@ assignments: let _detail = server.mock("GET", "/repos/o/r/rulesets/42").with_body(held).create_async().await; let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); let _put = record(&mut server, &writes, "PUT", "/repos/o/r/rulesets/42").await; - let config = write_file("org: o\nrepos:\n- name: r\n required_checks: [Unit Tests, Lint]\n"); + let config = write_file("org: o\nrepos:\n- name: r\n required_checks: [{context: Unit Tests, app_id: 15368}, Lint]\n"); client(&server).sync(config.path().to_str().expect("utf-8 path"), false).await.expect("sync"); let writes = writes.lock().expect("lock"); let [put] = writes.as_slice() else { panic!("{writes:?}") }; @@ -2451,6 +2504,80 @@ assignments: assert_eq!(sent, expected); } + #[tokio::test] + async fn a_missing_or_wrong_pin_is_drift_that_sync_rewrites_and_sync_from_org_writes_back() { + let mut server = mockito::Server::new_async().await; + let gate = |app_id| RequiredCheck { context: "gate / CI gate".into(), app_id }; + let ruleset = |id: u64, app_id| { + let mut ruleset = require_ci_body(&[gate(app_id)], &[]); + ruleset["id"] = json!(id); + ruleset + }; + let repos = ["unpinned", "wrong", "right"].map(|n| (n, json!({}))); + let _mocks = mock_org_full(&mut server, &repos, |_| json!([]), |name| match name { + "unpinned" => Some(vec![ruleset(1, None)]), + "wrong" => Some(vec![ruleset(2, Some(1))]), + _ => Some(vec![ruleset(3, Some(15368))]), + }).await; + let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let _puts = [ + record(&mut server, &writes, "PUT", "/repos/o/unpinned/rulesets/1").await, + record(&mut server, &writes, "PUT", "/repos/o/wrong/rulesets/2").await, + ]; + let pinned = " required_checks: [{context: gate / CI gate, app_id: 15368}]\n"; + let config = write_file(&format!("org: o\nrepos:\n- name: unpinned\n{pinned}- name: wrong\n{pinned}- name: right\n{pinned}")); + let path = config.path().to_str().expect("utf-8 path"); + assert!(client(&server).diff(path).await.expect("diff"), "a missing or wrong pin was called a match"); + client(&server).sync(path, false).await.expect("sync"); + let body = require_ci_body(&[gate(Some(15368))], &[]); + assert_eq!(*writes.lock().expect("lock"), [format!("PUT /repos/o/unpinned/rulesets/1 {body}"), format!("PUT /repos/o/wrong/rulesets/2 {body}")]); + + let export = write_file("org: o\n"); + let path = export.path().to_str().expect("utf-8 path"); + client(&server).generate_config_and_write(path, false).await.expect("sync-from-org"); + let yaml = std::fs::read_to_string(path).expect("read export"); + assert!(repo_block(&yaml, "unpinned").contains(" required_checks:\n - gate / CI gate\n"), "{yaml}"); + assert!(repo_block(&yaml, "wrong").contains(" required_checks:\n - context: gate / CI gate\n app_id: 1\n"), "{yaml}"); + assert!(repo_block(&yaml, "right").contains(" required_checks:\n - context: gate / CI gate\n app_id: 15368\n"), "{yaml}"); + assert!(!client(&server).diff(path).await.expect("diff"), "sync-from-org output differs from the org it came from:\n{yaml}"); + } + + #[tokio::test] + async fn org_actions_are_written_only_when_they_differ_and_round_trip() { + let mut server = mockito::Server::new_async().await; + let _mocks = mock_org_full(&mut server, &[("r", json!({}))], |_| json!([]), |_| Some(vec![])).await; + let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let _put = record(&mut server, &writes, "PUT", "/orgs/o/actions/permissions/workflow").await; + let config = |actions: &str| write_file(&format!("org: o\nactions: {actions}\nrepos:\n- name: r\n")); + let locked = config("{default_workflow_permissions: read, can_approve_pull_request_reviews: false}"); + let locked = locked.path().to_str().expect("utf-8 path"); + client(&server).sync(locked, true).await.expect("dry run"); + assert!(writes.lock().expect("lock").is_empty(), "a dry run wrote to GitHub"); + client(&server).sync(locked, false).await.expect("sync"); + let sent: Vec = writes.lock().expect("lock").iter() + .map(|w| serde_json::from_str(w.trim_start_matches("PUT /orgs/o/actions/permissions/workflow ")).expect("json body")) + .collect(); + assert_eq!(sent, [json!({"default_workflow_permissions": "read", "can_approve_pull_request_reviews": false})]); + assert!(client(&server).diff(locked).await.expect("diff"), "changed Actions settings were called a match"); + + writes.lock().expect("lock").clear(); + let same = config("{default_workflow_permissions: write, can_approve_pull_request_reviews: true}"); + client(&server).sync(same.path().to_str().expect("utf-8 path"), false).await.expect("sync"); + assert!(writes.lock().expect("lock").is_empty(), "matching Actions settings were rewritten"); + + let export = write_file("org: o\n"); + let path = export.path().to_str().expect("utf-8 path"); + client(&server).generate_config_and_write(path, false).await.expect("sync-from-org"); + let yaml = std::fs::read_to_string(path).expect("read export"); + assert!(yaml.contains("actions:\n default_workflow_permissions: write\n can_approve_pull_request_reviews: true\n"), "{yaml}"); + assert!(!client(&server).diff(path).await.expect("diff"), "sync-from-org output differs from the org it came from:\n{yaml}"); + // Without the block they are unmanaged: nothing to compare. + let start = yaml.find("actions:").expect("actions block"); + let end = start + yaml[start..].find("\n\n").expect("block end"); + std::fs::write(path, format!("{}{}", &yaml[..start], &yaml[end + 2..])).expect("write config"); + assert!(!client(&server).diff(path).await.expect("diff"), "a config without `actions` differs"); + } + /// A `Require CI` ruleset requiring `A`, with `bypass_actors` as given (`None`: GitHub didn't show it). fn require_a_with(id: u64, bypass: Option) -> serde_json::Value { let mut ruleset = require_ci(id, &["A"]); From 0209c46bea7c4a7da568e78b11c7babb5b1a93ab Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:51:32 -0800 Subject: [PATCH 2/3] test: a repo block of the export ends before its last newline --- src/github.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/github.rs b/src/github.rs index b525058..22ec61a 100644 --- a/src/github.rs +++ b/src/github.rs @@ -2536,9 +2536,9 @@ assignments: let path = export.path().to_str().expect("utf-8 path"); client(&server).generate_config_and_write(path, false).await.expect("sync-from-org"); let yaml = std::fs::read_to_string(path).expect("read export"); - assert!(repo_block(&yaml, "unpinned").contains(" required_checks:\n - gate / CI gate\n"), "{yaml}"); + assert!(repo_block(&yaml, "unpinned").contains(" required_checks:\n - gate / CI gate"), "{yaml}"); assert!(repo_block(&yaml, "wrong").contains(" required_checks:\n - context: gate / CI gate\n app_id: 1\n"), "{yaml}"); - assert!(repo_block(&yaml, "right").contains(" required_checks:\n - context: gate / CI gate\n app_id: 15368\n"), "{yaml}"); + assert!(repo_block(&yaml, "right").contains(" required_checks:\n - context: gate / CI gate\n app_id: 15368"), "{yaml}"); assert!(!client(&server).diff(path).await.expect("diff"), "sync-from-org output differs from the org it came from:\n{yaml}"); } From c3cdf75bc005afdb5782dcb723588e3c593dcc40 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:03:26 -0800 Subject: [PATCH 3/3] fix: keep live pins, branches and strictness; name unread Actions settings A plain check name keeps the pin its ruleset has: only an app_id sets or changes one, so sync never removes a pin. Rewriting Require CI keeps the ruleset's branch conditions and strict policy instead of resetting them to the default branch and not strict; a ruleset gh-config can't keep that for is refused. sync-from-org logs Actions settings it couldn't read at the default level and names them in its last line instead of reporting success. README: the Actions block needs org Administration read/write. --- README.md | 7 ++- docs/changelog.md | 3 +- src/github.rs | 138 ++++++++++++++++++++++++++++++++-------------- 3 files changed, 103 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index cccaf00..89d400a 100644 --- a/README.md +++ b/README.md @@ -256,8 +256,8 @@ repos: mode: pull_request # only by merging a PR; `always` also allows direct pushes ``` -- `sync` keeps them in the repo's own ruleset named `Require CI`: active, on the default branch (`~DEFAULT_BRANCH`), not strict (a PR needn't be up to date with the branch), one `required_status_checks` rule. It creates the ruleset if the repo has none by that name and rewrites it when its checks (in any order) or any of those properties differ. An existing `Require CI` ruleset is adopted by name. -- A check is its name, which any app may post, or `{context: , app_id: }`, which only that GitHub App may post (the ruleset's `integration_id`; GitHub Actions is `15368`). The pin is part of the check: a ruleset whose check has no pin, or another app's, is rewritten by `sync` and shown by `diff`, and a plain name drops a pin the ruleset has. `sync-from-org` writes each pin back. A pin stops another app or a commit status (which has no app) from satisfying the check; it doesn't stop a workflow in the PR itself from posting a check run with the same name. +- `sync` keeps them in the repo's own ruleset named `Require CI`: active, enforced on branch creation too, one `required_status_checks` rule. A ruleset it creates covers the default branch (`~DEFAULT_BRANCH`) and isn't strict (a PR needn't be up to date with the branch). It rewrites the ruleset when its checks (in any order), the bypass list, or those properties differ, and keeps the branches it covers and its strictness, so a rewrite never covers fewer branches or stops requiring PRs to be up to date. An existing `Require CI` ruleset is adopted by name; one that targets tags or pushes, or has no branch conditions, is refused. +- A check is its name, which any app may post, or `{context: , app_id: }`, which only that GitHub App may post (the ruleset's `integration_id`; GitHub Actions is `15368`). A pin is set or changed only by an `app_id` in the config: a ruleset whose check has no pin, or another app's, is rewritten by `sync` and shown by `diff`. A plain name keeps the pin the ruleset has, so `sync` never removes one; to remove a pin, change the ruleset on GitHub. `sync-from-org` writes each pin back, so `diff` shows a pin the file doesn't name until the file records it. A pin stops another app or a commit status (which has no app) from satisfying the check; it doesn't stop a workflow in the PR itself from posting a check run with the same name. - `allow_auto_merge` is written after the repo's `Require CI` ruleset, so if the ruleset write fails, auto-merge isn't left on without the checks it waits for. - A name listed twice is refused when the config is loaded. A `Require CI` ruleset that requires one check twice (from different apps) is refused like one with another rule: a config can't say which pin to keep. - gh-config owns every rule in `Require CI`: if it holds any other rule, `sync` stops with an error naming the repo and the rule instead of dropping it. Keep other rules in other rulesets. @@ -276,7 +276,8 @@ actions: - The org's Actions workflow settings (GitHub's `/orgs/{org}/actions/permissions/workflow`). Both keys are required; leave the whole block out and `sync` leaves them alone and `diff` doesn't compare them. - `sync` reads them and writes both, with one PUT, only when they differ; `--dry-run` prints the change. It writes them after checking the config's bypass lists and before teams and repos. -- `sync-from-org` records them. If they can't be read (the token needs org administration access), a file that has the block keeps it and `diff` names the org and exits 1; a file without it stays without it. +- The token needs the org's administration permission: a GitHub App needs **Organization permissions → Administration: Read** for `sync-from-org` and `diff` (GET) and **Read and write** for `sync` (PUT); a classic PAT needs `admin:org`. Grant it before adding the block. +- `sync-from-org` records them. If they can't be read (no permission, an error, a response it doesn't understand), it logs the error and names them in its last line instead of reporting success. A file that has the block keeps it, and `diff` names the org and exits 1; a file without it stays without it, and `diff` doesn't compare them. ### Webhooks diff --git a/docs/changelog.md b/docs/changelog.md index 083bcfc..1fda8e3 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -8,7 +8,8 @@ All notable changes to this project will be documented in this file. - `sync-from-org` and `diff` record `allow_auto_merge` and private repos' Actions `access_level`, so the drift check keeps them; `sync` reads `access_level` before writing it. - New repo field `required_checks`, kept in the repo ruleset `Require CI`. - New repo field `required_checks_bypass`: the teams, and only those, that may bypass `Require CI` (`pull_request` or `always`). `sync` writes it, `sync-from-org` and `diff` read it back. -- A required check can be pinned to the app that must post it: `{context: , app_id: }`. The pin is part of the check for `sync`, `diff` and `sync-from-org`; a plain name now means no pin, so `sync` drops a pin the config doesn't name instead of keeping it. +- A required check can be pinned to the app that must post it: `{context: , app_id: }`. Only an `app_id` sets or changes a pin; a plain name keeps the ruleset's. `sync`, `diff` and `sync-from-org` compare and record pins. +- `sync` keeps a `Require CI` ruleset's branch conditions and strictness when it rewrites it, instead of resetting them to the default branch and not strict. - New top-level `actions` block: the org's `default_workflow_permissions` and `can_approve_pull_request_reviews`. `sync` writes them, `sync-from-org` and `diff` read them back; without the block they're left alone. ## [v1.3.2] - 2026-11-09 diff --git a/src/github.rs b/src/github.rs index 22ec61a..ba5eb10 100644 --- a/src/github.rs +++ b/src/github.rs @@ -116,12 +116,19 @@ struct RequireCi { checks: Vec, /// Sorted. `None` when GitHub didn't say: it shows a ruleset's bypass list only to tokens that can administer the repo. bypass: Option>, - /// Whether everything but the checks is what `sync` writes: active, on the default branch, not strict. + /// The branches it covers (`conditions`) and whether a PR must be up to date first. `sync` keeps both. + conditions: serde_json::Value, + strict: bool, + /// Whether everything else is what `sync` writes: active, enforced on branch creation too. standard: bool, } -/// The `Require CI` ruleset `sync` writes for `checks`, which only `bypass` may merge past. -fn require_ci_body(checks: &[RequiredCheck], bypass: &[BypassActor]) -> serde_json::Value { +/// The `Require CI` ruleset `sync` writes for `checks`, which only `bypass` may merge past. A new one covers the +/// default branch and isn't strict; rewriting `held` keeps its branches and strictness, so it never covers less. +fn require_ci_body(checks: &[RequiredCheck], bypass: &[BypassActor], held: Option<&RequireCi>) -> serde_json::Value { + let default_conditions = json!({ "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } }); + let conditions = held.map_or(&default_conditions, |h| &h.conditions); + let strict = held.is_some_and(|h| h.strict); let bypass: Vec<_> = bypass .iter() .map(|a| match a.actor_id { @@ -141,12 +148,12 @@ fn require_ci_body(checks: &[RequiredCheck], bypass: &[BypassActor]) -> serde_js "target": "branch", "enforcement": "active", "bypass_actors": bypass, - "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } }, + "conditions": conditions, "rules": [{ "type": REQUIRED_STATUS_CHECKS, "parameters": { "required_status_checks": checks, - "strict_required_status_checks_policy": false, + "strict_required_status_checks_policy": strict, "do_not_enforce_on_create": false, }, }], @@ -181,13 +188,15 @@ fn parse_require_ci(repo: &str, ruleset: &serde_json::Value) -> AppResult = actors .iter() @@ -200,7 +209,7 @@ fn parse_require_ci(repo: &str, ruleset: &serde_json::Value) -> AppResult = checks + .iter() + .map(|c| match c.app_id { + Some(_) => c.clone(), + None => held.iter().find(|h| h.context == c.context).cloned().unwrap_or_else(|| c.clone()), + }) + .collect(); let held_bypass = current.as_ref().and_then(|c| c.bypass.clone()); - let (method, url) = match current { - Some(current) if current.standard && same_checks(¤t.checks, checks) && current.bypass.as_ref() == Some(&bypass) => return Ok(()), + let (method, url) = match ¤t { + Some(current) if current.standard && same_checks(¤t.checks, &desired) && current.bypass.as_ref() == Some(&bypass) => return Ok(()), Some(current) => (Method::PUT, format!("{}/repos/{}/{}/rulesets/{}", self.api_url, self.org, repo.name, current.id)), None => (Method::POST, format!("{}/repos/{}/{}/rulesets", self.api_url, self.org, repo.name)), }; let verb = if method == Method::POST { "create" } else { "update" }; let named = |checks: &[&RequiredCheck]| checks.iter().map(|c| c.to_string()).collect::>().join(", "); - let requiring = named(&checks.iter().collect::>()); + let requiring = named(&desired.iter().collect::>()); if dry_run { - let removed: Vec<_> = held.iter().filter(|c| !checks.contains(c)).collect(); + let removed: Vec<_> = held.iter().filter(|c| !desired.contains(c)).collect(); let removed = if removed.is_empty() { String::new() } else { format!("; no longer requiring: {}", named(&removed)) }; let bypass = bypass_change(&bypass, held_bypass.as_deref(), method == Method::PUT, teams); println!("[Dry Run] Would {verb} ruleset `{REQUIRE_CI}` on {}/{} requiring: {requiring}{removed}; {bypass}", self.org, repo.name); return Ok(()); } - self.client.request(method, &url, "application/vnd.github+json", Some(require_ci_body(checks, &bypass))).await?; + self.client.request(method, &url, "application/vnd.github+json", Some(require_ci_body(&desired, &bypass, current.as_ref()))).await?; info!("Ruleset `{REQUIRE_CI}` on {}/{} now requires: {requiring}; bypass: {}", self.org, repo.name, bypass.len()); Ok(()) } @@ -1021,10 +1038,13 @@ impl GitHubClient { Err(AppError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => None, Err(e) => return Err(e), }; - let (config, unread) = self.generate_unfiltered_config_from_org(file.as_ref()).await?; // Make sure to call an unfiltered version + let (config, unread, unrecorded) = self.generate_unfiltered_config_from_org(file.as_ref()).await?; // Make sure to call an unfiltered version if !unread.is_empty() { println!("Not read, so these keep what the file has for them: {}", unread.join(", ")); } + if !unrecorded.is_empty() { + println!("Not read, so the config doesn't record them: {}", unrecorded.join(", ")); + } // ... rest of the YAML writing logic ... // (Ensure this part uses the full, unfiltered config) @@ -1173,21 +1193,27 @@ impl GitHubClient { println!("Writing generated config to {}", config_path); let mut file = File::create(config_path).map_err(AppError::Io)?; file.write_all(yaml_content.as_bytes()).map_err(AppError::Io)?; - println!("Config generation completed successfully."); + if unrecorded.is_empty() { + println!("Config generation completed successfully."); + } else { + println!("Config generation completed without: {}", unrecorded.join(", ")); + } } Ok(()) } /// The org as a config, reading `file` for what GitHub can't say: which default to keep and, as a config holds /// one webhook per repo, which of a repo's webhooks to record. Without a default, the first webhook found is it. - /// Also returns the repos whose webhooks couldn't be read: their webhook is the file's, not GitHub's. - async fn generate_unfiltered_config_from_org(&self, file: Option<&Config>) -> AppResult<(Config, Vec)> { + /// Also returns what couldn't be read and so is the file's, not GitHub's (a repo's webhook, ...), and what + /// couldn't be read and isn't in the file, so the config doesn't record it. + async fn generate_unfiltered_config_from_org(&self, file: Option<&Config>) -> AppResult<(Config, Vec, Vec)> { let mut default_webhook = file .and_then(|file| file.default_webhook.clone()) .map(|wh| WebhookConfig { events: sorted(&wh.events), ..wh }); // This is essentially the original logic of generate_config_from_org let mut repos = Vec::new(); let mut unread = Vec::new(); + let mut unrecorded = Vec::new(); let actions = match self.read_org_actions().await { Ok(actions) => Some(actions), Err(e) => { @@ -1197,7 +1223,9 @@ impl GitHubClient { error!("Failed to read the Actions workflow settings of {}: {}. They stay as the file has them.", self.org, e); unread.push(format!("{} (Actions workflow settings)", self.org)); } else { - info!("Not recording the Actions workflow settings of {}: {}", self.org, e); + // Shown at the default log level, and named again when the file is written. + error!("Failed to read the Actions workflow settings of {}: {}. The config won't record them.", self.org, e); + unrecorded.push(format!("{} (Actions workflow settings)", self.org)); } kept } @@ -1370,7 +1398,7 @@ impl GitHubClient { default_webhook, default_branch_protections: vec![], // Add logic if needed }; - Ok((config, unread)) + Ok((config, unread, unrecorded)) } pub async fn sync(&mut self, config_path: &str, dry_run: bool) -> AppResult<()> { @@ -1501,7 +1529,8 @@ impl GitHubClient { check_archived(&local_config)?; // --- Step 2: Fetch FULL GitHub org state (unfiltered, as sync-from-github would write) --- - let (github_config, unread) = self.generate_unfiltered_config_from_org(Some(&local_config)).await?; + // What isn't in the file and couldn't be read isn't compared: the file doesn't manage it. + let (github_config, unread, _) = self.generate_unfiltered_config_from_org(Some(&local_config)).await?; // --- Step 3: Prepare final versions for diffing --- let mut diff_local_config = local_config.clone(); // Clone original local config @@ -1726,7 +1755,7 @@ mod tests { let team_list: Vec<_> = teams.iter().map(|(slug, id)| json!({"slug": slug, "name": slug, "id": id})).collect(); let mut mocks = vec![ server.mock("GET", "/orgs/o/teams?per_page=100").with_body(json!(team_list).to_string()).create_async().await, - // GitHub's defaults for a new org, plus a field a config doesn't hold. + // GitHub's defaults for a new org, plus a field a config doesn't hold. Second: a test removes it by index. server .mock("GET", "/orgs/o/actions/permissions/workflow") .with_body(r#"{"default_workflow_permissions": "write", "can_approve_pull_request_reviews": true, "other": 1}"#) @@ -1786,7 +1815,7 @@ mod tests { /// A `Require CI` ruleset with id `id` requiring `checks`, as `sync` writes it. fn require_ci(id: u64, checks: &[&str]) -> serde_json::Value { - let mut ruleset = require_ci_body(&unpinned(checks), &[]); + let mut ruleset = require_ci_body(&unpinned(checks), &[], None); ruleset["id"] = json!(id); ruleset } @@ -2317,6 +2346,7 @@ assignments: async fn sync_keeps_require_ci_to_the_configured_checks() { let mut server = mockito::Server::new_async().await; let mut adopted = require_ci(7, &["A", "B"]); + adopted["enforcement"] = json!("evaluate"); adopted["conditions"]["ref_name"]["include"] = json!(["refs/heads/main"]); let mut mixed = require_ci(9, &["A"]); mixed["rules"].as_array_mut().expect("rules").push(json!({"type": "pull_request", "parameters": {}})); @@ -2339,10 +2369,10 @@ assignments: client(&server).sync(path, true).await.expect("dry run"); assert!(writes.lock().expect("lock").is_empty(), "a dry run wrote to GitHub"); client(&server).sync(path, false).await.expect("sync"); - let body = |checks: &[&str]| require_ci_body(&unpinned(checks), &[]).to_string(); + let body = |checks: &[&str]| require_ci_body(&unpinned(checks), &[], None).to_string(); assert_eq!( *writes.lock().expect("lock"), - [format!("POST /repos/o/fresh/rulesets {}", body(&["A", "Clippy & Docs"])), format!("PUT /repos/o/adopt/rulesets/7 {}", body(&["A", "B"]))] + [format!("POST /repos/o/fresh/rulesets {}", body(&["A", "Clippy & Docs"])), format!("PUT /repos/o/adopt/rulesets/7 {}", body(&["A", "B"]).replace("~DEFAULT_BRANCH", "refs/heads/main"))] ); let config = write_file("org: o\nrepos:\n- name: mixed\n required_checks: [A]\n"); @@ -2471,16 +2501,16 @@ assignments: } #[tokio::test] - async fn rewriting_require_ci_pins_each_check_to_the_configured_app() { + async fn rewriting_require_ci_keeps_live_pins_branches_and_strictness_and_sets_the_configs_pins() { let mut server = mockito::Server::new_async().await; let _mocks = mock_org_full(&mut server, &[("r", json!({}))], |_| json!([]), |_| None).await; // As GitHub returns it, written out by hand. let held = r#"{ "id": 42, "name": "Require CI", "target": "branch", "source_type": "Repository", "source": "o/r", "enforcement": "active", "bypass_actors": [], - "conditions": {"ref_name": {"include": ["refs/heads/main"], "exclude": []}}, + "conditions": {"ref_name": {"include": ["refs/heads/main", "refs/heads/release/*"], "exclude": []}}, "rules": [{"type": "required_status_checks", "parameters": { - "strict_required_status_checks_policy": false, "do_not_enforce_on_create": false, + "strict_required_status_checks_policy": true, "do_not_enforce_on_create": false, "required_status_checks": [{"context": "Unit Tests", "integration_id": 15368}, {"context": "Old"}]}}], "node_id": "RRS_x", "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z" }"#; @@ -2489,17 +2519,18 @@ assignments: let _detail = server.mock("GET", "/repos/o/r/rulesets/42").with_body(held).create_async().await; let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); let _put = record(&mut server, &writes, "PUT", "/repos/o/r/rulesets/42").await; - let config = write_file("org: o\nrepos:\n- name: r\n required_checks: [{context: Unit Tests, app_id: 15368}, Lint]\n"); + // `Unit Tests` keeps its pin though the config names no app; `Lint` gets the config's. + let config = write_file("org: o\nrepos:\n- name: r\n required_checks: [Unit Tests, {context: Lint, app_id: 15368}]\n"); client(&server).sync(config.path().to_str().expect("utf-8 path"), false).await.expect("sync"); let writes = writes.lock().expect("lock"); let [put] = writes.as_slice() else { panic!("{writes:?}") }; let sent: serde_json::Value = serde_json::from_str(put.trim_start_matches("PUT /repos/o/r/rulesets/42 ")).expect("json body"); let expected: serde_json::Value = serde_json::from_str(r#"{ "name": "Require CI", "target": "branch", "enforcement": "active", "bypass_actors": [], - "conditions": {"ref_name": {"include": ["~DEFAULT_BRANCH"], "exclude": []}}, + "conditions": {"ref_name": {"include": ["refs/heads/main", "refs/heads/release/*"], "exclude": []}}, "rules": [{"type": "required_status_checks", "parameters": { - "strict_required_status_checks_policy": false, "do_not_enforce_on_create": false, - "required_status_checks": [{"context": "Unit Tests", "integration_id": 15368}, {"context": "Lint"}]}}] + "strict_required_status_checks_policy": true, "do_not_enforce_on_create": false, + "required_status_checks": [{"context": "Unit Tests", "integration_id": 15368}, {"context": "Lint", "integration_id": 15368}]}}] }"#).expect("expected json"); assert_eq!(sent, expected); } @@ -2509,14 +2540,15 @@ assignments: let mut server = mockito::Server::new_async().await; let gate = |app_id| RequiredCheck { context: "gate / CI gate".into(), app_id }; let ruleset = |id: u64, app_id| { - let mut ruleset = require_ci_body(&[gate(app_id)], &[]); + let mut ruleset = require_ci_body(&[gate(app_id)], &[], None); ruleset["id"] = json!(id); ruleset }; - let repos = ["unpinned", "wrong", "right"].map(|n| (n, json!({}))); + let repos = ["unpinned", "wrong", "right", "kept"].map(|n| (n, json!({}))); let _mocks = mock_org_full(&mut server, &repos, |_| json!([]), |name| match name { "unpinned" => Some(vec![ruleset(1, None)]), "wrong" => Some(vec![ruleset(2, Some(1))]), + "kept" => Some(vec![ruleset(4, Some(15368))]), _ => Some(vec![ruleset(3, Some(15368))]), }).await; let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); @@ -2525,11 +2557,12 @@ assignments: record(&mut server, &writes, "PUT", "/repos/o/wrong/rulesets/2").await, ]; let pinned = " required_checks: [{context: gate / CI gate, app_id: 15368}]\n"; - let config = write_file(&format!("org: o\nrepos:\n- name: unpinned\n{pinned}- name: wrong\n{pinned}- name: right\n{pinned}")); + // `kept` names the check without an app: its live pin stays, so no PUT is mocked for it. + let config = write_file(&format!("org: o\nrepos:\n- name: unpinned\n{pinned}- name: wrong\n{pinned}- name: right\n{pinned}- name: kept\n required_checks: [gate / CI gate]\n")); let path = config.path().to_str().expect("utf-8 path"); assert!(client(&server).diff(path).await.expect("diff"), "a missing or wrong pin was called a match"); client(&server).sync(path, false).await.expect("sync"); - let body = require_ci_body(&[gate(Some(15368))], &[]); + let body = require_ci_body(&[gate(Some(15368))], &[], None); assert_eq!(*writes.lock().expect("lock"), [format!("PUT /repos/o/unpinned/rulesets/1 {body}"), format!("PUT /repos/o/wrong/rulesets/2 {body}")]); let export = write_file("org: o\n"); @@ -2538,7 +2571,9 @@ assignments: let yaml = std::fs::read_to_string(path).expect("read export"); assert!(repo_block(&yaml, "unpinned").contains(" required_checks:\n - gate / CI gate"), "{yaml}"); assert!(repo_block(&yaml, "wrong").contains(" required_checks:\n - context: gate / CI gate\n app_id: 1\n"), "{yaml}"); - assert!(repo_block(&yaml, "right").contains(" required_checks:\n - context: gate / CI gate\n app_id: 15368"), "{yaml}"); + for repo in ["right", "kept"] { + assert!(repo_block(&yaml, repo).contains(" required_checks:\n - context: gate / CI gate\n app_id: 15368"), "{yaml}"); + } assert!(!client(&server).diff(path).await.expect("diff"), "sync-from-org output differs from the org it came from:\n{yaml}"); } @@ -2578,6 +2613,27 @@ assignments: assert!(!client(&server).diff(path).await.expect("diff"), "a config without `actions` differs"); } + #[tokio::test] + async fn org_actions_that_cant_be_read_are_named_and_kept_from_a_file_that_has_them() { + let mut server = mockito::Server::new_async().await; + let mocks = mock_org_full(&mut server, &[("r", json!({}))], |_| json!([]), |_| Some(vec![])).await; + // The Actions settings, mocked second by `mock_org_with_teams`, give way to the 403 below. + mocks[1].remove_async().await; + let _refused = server.mock("GET", "/orgs/o/actions/permissions/workflow").with_status(403).with_body(r#"{"message": "Resource not accessible by integration"}"#).create_async().await; + let file = write_file("org: o\nrepos:\n- name: r\n"); + let path = file.path().to_str().expect("utf-8 path"); + client(&server).generate_config_and_write(path, false).await.expect("sync-from-org"); + let yaml = std::fs::read_to_string(path).expect("read export"); + assert!(!yaml.contains("actions:"), "{yaml}"); + assert!(!client(&server).diff(path).await.expect("diff"), "unmanaged Actions settings were compared"); + + let managed = "actions:\n default_workflow_permissions: read\n can_approve_pull_request_reviews: false\n"; + std::fs::write(path, format!("{managed}{yaml}")).expect("write config"); + client(&server).generate_config_and_write(path, false).await.expect("sync-from-org"); + assert!(std::fs::read_to_string(path).expect("read export").contains(managed), "the file's Actions settings were dropped"); + assert!(client(&server).diff(path).await.expect("diff"), "Actions settings that couldn't be read were called a match"); + } + /// A `Require CI` ruleset requiring `A`, with `bypass_actors` as given (`None`: GitHub didn't show it). fn require_a_with(id: u64, bypass: Option) -> serde_json::Value { let mut ruleset = require_ci(id, &["A"]);