GitLab Protected Branches API的GitHub等效API及分支权限管理问询
I get it—you're used to GitLab's Protected Branches API where setting a permission level of 0 locks down a branch completely, and you want to replicate that on GitHub for a temporary workflow: lock master first, do your work, then unlock it. Here's exactly how to do it using the GitHub REST API:
Step 1: Lock the master Branch (Block All Pushes/Merges)
GitHub doesn't have a direct "permission level 0" parameter, but we can achieve the same effect by creating a branch protection rule that restricts all users/teams from pushing, and enforces the rule even for repository admins.
Use the Update branch protection endpoint (it works for creating rules too, even if none exist yet):
curl -L \ -X PUT \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer YOUR_GITHUB_TOKEN" \ -H "X-GitHub-Api-Version: 2022-11-28" \ https://api.github.com/repos/OWNER/REPO/branches/master/protection \ -d '{ "enforce_admins": true, "restrictions": { "users": [], "teams": [] }, "allow_force_pushes": false, "allow_deletions": false, "required_pull_request_reviews": null, "required_status_checks": null }'
What each parameter does:
enforce_admins: true: Ensures even repository admins can't bypass the lock (critical for a full restriction)restrictions: { "users": [], "teams": [] }: Blocks all users and teams from pushing or merging tomaster—since no entities are whitelisted, nobody gets accessallow_force_pushes: false: Prevents force pushes that could bypass the ruleallow_deletions: false: Stops the branch from being deleted accidentallyrequired_pull_request_reviews/required_status_checks: Set tonullbecause we don't want any workarounds via PR reviews or status checks—just a hard lock
Step 2: Unlock the master Branch After Your Operation
Once you're done with your task, simply delete the branch protection rule entirely:
curl -L \ -X DELETE \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer YOUR_GITHUB_TOKEN" \ -H "X-GitHub-Api-Version: 2022-11-28" \ https://api.github.com/repos/OWNER/REPO/branches/master/protection
This removes all restrictions, restoring normal push/merge access to the branch.
Key Notes
- Permissions: You'll need a GitHub token with the
reposcope (oradmin:repo_hookfor organization repos) to modify branch protection. - Idempotency: The PUT endpoint works whether a protection rule exists or not—no need to check first before creating/updating.
- Alternative for Organizations: If you're working with an org repo, you can also restrict to empty teams instead of empty users, but the effect is identical.
内容的提问来源于stack exchange,提问作者hisener

