From fb420ded80034727f091bf938a325cc491d64f39 Mon Sep 17 00:00:00 2001 From: Jess Frazelle Date: Thu, 27 Sep 2018 11:15:10 -0400 Subject: [PATCH] add delete ref script Signed-off-by: Jess Frazelle --- github-dev/cleanup-pr-branch | 52 ++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100755 github-dev/cleanup-pr-branch diff --git a/github-dev/cleanup-pr-branch b/github-dev/cleanup-pr-branch new file mode 100755 index 0000000..51b5980 --- /dev/null +++ b/github-dev/cleanup-pr-branch @@ -0,0 +1,52 @@ +#!/bin/bash +set -e +set -o pipefail + +if [[ ! -z "$TOKEN" ]]; then + GITHUB_TOKEN=$TOKEN +fi + +if [[ -z "$GITHUB_TOKEN" ]]; then + echo "Set the GITHUB_TOKEN env variable." + exit 1 +fi + +if [[ -z "$GITHUB_REPOSITORY" ]]; then + echo "Set the GITHUB_REPOSITORY env variable." + exit 1 +fi + +URI=https://api.github.com +API_VERSION=v3 +API_HEADER="Accept: application/vnd.github.${API_VERSION}+json" +AUTH_HEADER="Authorization: token ${GITHUB_TOKEN}" + +main(){ + action=$(cat "$GITHUB_EVENT_PATH" | jq --raw-output .action) + merged=$(cat "$GITHUB_EVENT_PATH" | jq --raw-output .pull_request.merged) + + echo "action: $action merged: $merged" + + if [[ "$action" == "closed" ]] && [[ "$merged" == "true" ]]; then + # delete the branch. + ref=$(cat "$GITHUB_EVENT_PATH" | jq --raw-output .pull_request.head.ref) + owner=$(cat "$GITHUB_EVENT_PATH" | jq --raw-output .pull_request.head.repo.owner.login) + repo=$(cat "$GITHUB_EVENT_PATH" | jq --raw-output .pull_request.head.repo.name) + + if [[ "$ref" == "master" ]]; then + # Never delete the master branch. + echo "Will not delete master branch for ${owner}/${repo}, exiting." + exit 0 + fi + + echo "Deleting branch ref $ref for owner ${owner}/${repo}..." + curl -XDELETE -sSL \ + -H "${AUTH_HEADER}" \ + -H "${API_HEADER}" \ + "/repos/${owner}/${repo}/git/refs/heads/${ref}" + + echo "Branch delete success!" + fi +} + +main "$@"