set -euo pipefail
_git_repo() {
git remote get-url origin 2>/dev/null \
| sed -E 's|.*github\.com[:/]||' | sed 's|\.git$||'
}
REPO="${REPO:-$(_git_repo)}"
if [[ -z "$REPO" ]]; then
echo "error: could not infer repo from git remote. Set REPO=owner/name explicitly." >&2
exit 1
fi
BRANCH="${BRANCH:-master}"
STRICT="${STRICT:-true}"
ENFORCE_ADMINS="${ENFORCE_ADMINS:-false}"
CONTEXTS=(
"validate / Run Tests"
"validate / Validate PR Title (Future Squash Commit)"
)
echo "Configuring branch protection for ${REPO}@${BRANCH}"
echo " strict (up to date): ${STRICT}"
echo " enforce on admins: ${ENFORCE_ADMINS}"
echo " required checks:"
for c in "${CONTEXTS[@]}"; do echo " - ${c}"; done
echo
contexts_json=$(printf '%s\n' "${CONTEXTS[@]}" | \
awk 'BEGIN{printf "["} {printf "%s\"%s\"", (NR>1?",":""), $0} END{printf "]"}')
gh api -X PUT "repos/${REPO}/branches/${BRANCH}/protection" --input - <<JSON
{
"required_status_checks": {
"strict": ${STRICT},
"contexts": ${contexts_json}
},
"enforce_admins": ${ENFORCE_ADMINS},
"required_pull_request_reviews": null,
"restrictions": null
}
JSON
echo
echo "Done. Branch protection applied to ${REPO}@${BRANCH}."