Skip to content

Instantly share code, notes, and snippets.

@edudobay
Last active June 27, 2023 13:02
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save edudobay/decc7d772c8a11db130aef9340d392bf to your computer and use it in GitHub Desktop.
Save edudobay/decc7d772c8a11db130aef9340d392bf to your computer and use it in GitHub Desktop.
Command-line script for protecting/unprotecting branches in a GitHub repository

(To be improved)

Requirements

  • httpie (which provides the http command) — pip install httpie

Setup

  • Save the git-branch-protection.sh as git-branch-protection somewhere in your path (something like ~/bin or ~/.local/bin if you already use it)
  • Generate a GitHub token and save it as ~/.config/github_token.

Running

$ git branch-protection protect
#!/bin/zsh
set -o errexit
PROGNAME=$0
print_usage() {
cat <<EOF
$PROGNAME <command> <repository name> [<branch>]
Available commands are:
show Display current branch protection settings for the selected
branch
protect Protect the selected branch
unprotect Unprotect the selected branch
Repository names must be given in 'OWNER/repo' form. The branch defaults to
'master' if not given.
EOF
}
action=$1
REPO=$2
BRANCH=${3-master}
if [[ -z $REPO && -d .git ]]; then
repo_url=$(git remote get-url origin)
REPO=$(echo $repo_url | sed -e 's/^git@github.com:\(.*\)$/\1/; s/\.git$//')
fi
if [[ $REPO != */* ]]; then
echo 'Invalid repository name'
exit 1
fi
case $action in
protect|unprotect|show|show_all) ;;
*)
print_usage
exit 1
esac
TOKEN_FILE=$HOME/.config/github_token
echo $action $REPO $BRANCH
_read_token() {
head -1 $TOKEN_FILE
}
GITHUB_API_TOKEN=$(_read_token)
show() {
http get https://api.github.com/repos/$REPO/branches/$BRANCH/protection Authorization:token\ $GITHUB_API_TOKEN Accept:application/vnd.github.luke-cage-preview+json
}
protect() {
http put https://api.github.com/repos/$REPO/branches/$BRANCH/protection Authorization:token\ $GITHUB_API_TOKEN Accept:application/vnd.github.luke-cage-preview+json \
required_status_checks:='{
"strict": true,
"contexts": []
}' \
required_pull_request_reviews:='{
"dismissal_restrictions": {},
"dismiss_stale_reviews": false,
"require_code_owner_reviews": false,
"required_approving_review_count": 1
}' \
enforce_admins:=true \
restrictions:=null
}
unprotect() {
http delete https://api.github.com/repos/$REPO/branches/$BRANCH/protection/required_pull_request_reviews Authorization:token\ $GITHUB_API_TOKEN
}
$action
@bxw85a3
Copy link

bxw85a3 commented Jan 17, 2020

Why require httpie when you could do this with CURL?

@vijay-yadav-3
Copy link

vijay-yadav-3 commented Feb 17, 2021

Can i simply use it by

sh git-branch-protection.sh action repo_name branch

I am getting the following error while doing this

Traceback (most recent call last):
  File "/usr/bin/http", line 11, in <module>
    sys.exit(main())
  File "/usr/lib/python2.7/dist-packages/httpie/__main__.py", line 10, in main
    from .core import main
  File "/usr/lib/python2.7/dist-packages/httpie/core.py", line 21
    args: List[Union[str, bytes]] = sys.argv,
        ^
SyntaxError: invalid syntax

Update: The issue resolved by updating python and pip version

@nperez0111
Copy link

Couple of commands that do the same thing with GitHub's CLI Tool.

# Show branch protection of master branch
gh api repos/:owner/:repo/branches/master/protection  

# Deletes branch protection of master branch
gh api -X DELETE repos/:owner/:repo/branches/master/protection

# Configuation for the branch protection to enable https://docs.github.com/en/rest/reference/repos#update-branch-protection
echo '{
  "required_status_checks": {
    "strict": true,
    "contexts": ["contexts"]
  },
  "enforce_admins": true,
  "required_pull_request_reviews": {
    "dismissal_restrictions": {
      "users": ["users"],
      "teams": ["teams"]
    },
    "dismiss_stale_reviews": false,
    "require_code_owner_reviews": false,
    "required_approving_review_count": 1
  },
  "restrictions": {
    "users": ["users"],
    "teams": ["teams"],
    "apps": ["apps"]
  }
}' >/tmp/config-branch-rules

# Applies the branch protection specified above to master branch
gh api --method PUT --preview luke-cage repos/:owner/:repo/branches/master/protection --input /tmp/config-branch-rules >/dev/null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment