forked from elnic/branch-cleanup-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanup-pr-branch
executable file
·65 lines (52 loc) · 1.69 KB
/
cleanup-pr-branch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/bin/bash
set -e
set -o pipefail
MASTER_BRANCH="master"
if [[ ! -z "$TOKEN" ]]; then
GITHUB_TOKEN=$TOKEN
fi
if [[ ! -z "$BRANCH" ]]; then
MASTER_BRANCH=$BRANCH
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=$(jq --raw-output .action "$GITHUB_EVENT_PATH")
merged=$(jq --raw-output .pull_request.merged "$GITHUB_EVENT_PATH")
target_branch=$(jq --raw-output .pull_request.base.ref "$GITHUB_EVENT_PATH")
echo "DEBUG -> action: $action merged: $merged"
if [[ "$action" == "closed" ]] && [[ "$merged" == "true" ]] && [[ "$target_branch" == "$MASTER_BRANCH" ]]; then
# delete the branch.
ref=$(jq --raw-output .pull_request.head.ref "$GITHUB_EVENT_PATH")
owner=$(jq --raw-output .pull_request.head.repo.owner.login "$GITHUB_EVENT_PATH")
repo=$(jq --raw-output .pull_request.head.repo.name "$GITHUB_EVENT_PATH")
default_branch=$(
curl -XGET -sSL \
-H "${AUTH_HEADER}" \
-H "${API_HEADER}" \
"${URI}/repos/${owner}/${repo}" | jq .default_branch
)
if [[ "$ref" == "$default_branch" ]]; then
# Never delete the default branch.
echo "Will not delete default branch (${default_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}" \
"${URI}/repos/${owner}/${repo}/git/refs/heads/${ref}"
echo "Branch delete success!"
fi
}
main "$@"