Skip to content

BranchProtection

Source: src/GitHub/BranchProtection.ts

A GitHub branch protection rule.

BranchProtection manages the classic branch protection settings on a single branch: required status checks, required pull request reviews, push restrictions, admin enforcement, signed commits, linear history, and the force-push / deletion / lock toggles. Pair it with GitHub.Repository to protect the default branch of a repository provisioned in the same stack.

Branch protection is available on public repositories on every plan; private repositories require GitHub Pro, Team, or Enterprise. Push restrictions and dismissal restrictions are only available on organization-owned repositories.

Authentication is resolved via the GitHubCredentials service supplied by GitHub.providers() (env, stored PAT, gh CLI, or OAuth). The token needs repo scope and admin access to the repository.

Require Pull Request Reviews

yield* GitHub.BranchProtection("main", {
owner: "my-org",
repository: "my-repo",
branch: "main",
requiredPullRequestReviews: {
requiredApprovingReviewCount: 1,
dismissStaleReviews: true,
},
});

Require Status Checks and a Linear History

yield* GitHub.BranchProtection("main", {
owner: "my-org",
repository: "my-repo",
branch: "main",
requiredStatusChecks: {
strict: true,
checks: [{ context: "ci" }],
},
requiredLinearHistory: true,
requiredConversationResolution: true,
enforceAdmins: true,
});

Protecting a Repository’s Default Branch

Section titled “Protecting a Repository’s Default Branch”
import * as Output from "alchemy/Output";
const repo = yield* GitHub.Repository("repo", {
owner: "my-org",
name: "my-repo",
autoInit: true,
});
yield* GitHub.BranchProtection("main", {
owner: "my-org",
repository: Output.map(repo.fullName, (fullName) => fullName.split("/")[1]!),
branch: repo.defaultBranch,
requiredPullRequestReviews: { requiredApprovingReviewCount: 1 },
allowForcePushes: false,
allowDeletions: false,
});
yield* GitHub.BranchProtection("release", {
owner: "my-org",
repository: "my-repo",
branch: "release",
restrictions: { teams: ["release-managers"] },
blockCreations: true,
requiredSignatures: true,
});