Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- `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: <name>, app_id: <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.
Expand All @@ -263,6 +266,19 @@ 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.
- 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

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.
Expand Down
3 changes: 3 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ 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: <name>, app_id: <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

Expand Down
7 changes: 6 additions & 1 deletion docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
138 changes: 133 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -84,16 +84,70 @@ pub struct Repo {
pub webhook: Option<WebhookConfig>,
#[serde(default)]
pub branch_protections: Vec<BranchProtectionRule>,
/// 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<String>,
pub required_checks: Vec<RequiredCheck>,
/// 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<CheckBypass>,
}

/// 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: <name>, app_id: <id>}`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct RequiredCheck {
pub context: String,
pub app_id: Option<u64>,
}

/// 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<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
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<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
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: <name>, app_id: <id>}`")
}
fn visit_str<E: de::Error>(self, name: &str) -> Result<RequiredCheck, E> {
Ok(RequiredCheck { context: name.to_string(), app_id: None })
}
fn visit_map<A: de::MapAccess<'de>>(self, map: A) -> Result<RequiredCheck, A::Error> {
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`.
Expand Down Expand Up @@ -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)]
///
Expand Down Expand Up @@ -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<OrgActions>,
/// List of repository configurations.
#[serde(default)]
pub repos: Vec<Repo>,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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| {
Expand Down
Loading
Loading