Skip to content

Instantly share code, notes, and snippets.

@joeywang
Created March 18, 2026 21:36
Show Gist options
  • Select an option

  • Save joeywang/e713a25a9095e0c635f343b29dbc3b6f to your computer and use it in GitHub Desktop.

Select an option

Save joeywang/e713a25a9095e0c635f343b29dbc3b6f to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -euo pipefail
REPO="${1:-}"
BRANCH="${2:-}"
if [[ -z "$REPO" ]]; then
echo "Usage: $0 <owner/repo> [branch]"
exit 1
fi
api() {
gh api \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
"$@"
}
branch_exists() {
local repo="$1"
local branch="$2"
api "repos/$repo/branches/$branch" >/dev/null 2>&1
}
protect_branch() {
local repo="$1"
local branch="$2"
echo "Protecting $repo:$branch"
gh api \
-X PUT \
"repos/$repo/branches/$branch/protection" \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
--input - <<'JSON'
{
"required_status_checks": null,
"enforce_admins": true,
"required_pull_request_reviews": null,
"restrictions": null,
"required_linear_history": false,
"allow_force_pushes": false,
"allow_deletions": false,
"block_creations": false,
"required_conversation_resolution": false,
"lock_branch": false,
"allow_fork_syncing": false
}
JSON
echo "Done: $branch"
}
if [[ -z "$BRANCH" ]]; then
BRANCH="$(api "repos/$REPO" --jq '.default_branch')"
fi
if [[ -z "$BRANCH" || "$BRANCH" == "null" ]]; then
echo "Could not determine branch"
exit 1
fi
if ! branch_exists "$REPO" "$BRANCH"; then
echo "Branch does not exist: $REPO:$BRANCH"
exit 1
fi
protect_branch "$REPO" "$BRANCH"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment