-
Notifications
You must be signed in to change notification settings - Fork 7
/
github-applypr
executable file
·96 lines (79 loc) · 2.37 KB
/
github-applypr
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/bin/bash
usage() {
echo "
Usage: $(basename $0) [OPTIONS] <branch> <PR> [message]
Apply a pull-request from github
OPTIONS
-r <remote> Use <remote> instead of origin to fetch the pr
" 1>&$1;
exit $(($1 - 1));
}
ask_confirmation() {
read -p "Continue (y/N)? " choice
case "$choice" in
y|Y) return 0;;
n|N) return 1;;
*) return 1;;
esac
}
OPT_REMOTE="origin"
args=0
while getopts "r:h" o; do
case "${o}" in
r) OPT_REMOTE=${OPTARG}; args=$[$args + 2] ;;
h) usage 1;;
\?) usage 2;;
esac
done
shift $args
if [ $# -lt 2 ]; then
usage 2
fi
BRANCH=$1
PR=$2
MSG="${3:-Applied, thanks!}"
REMOTE=$(git config remote.$OPT_REMOTE.url)
REMOTE=${REMOTE/.git}
REMOTE=${REMOTE/*github.com:}
NEED_REBASE=0
TMP_BRANCH=apply-pr
RBRANCH=$(basename $(git config branch.$BRANCH.merge))
if [ "$(git rev-parse $BRANCH)" != "$(git rev-parse $OPT_REMOTE/$RBRANCH)" ]; then
if git merge-base --is-ancestor $BRANCH $OPT_REMOTE/$RBRANCH; then
echo "Local branch $BRANCH and remote $OPT_REMOTE/$RBRANCH do not point to the "
echo "same commit, but it is a fastforward."
echo "I need to take the following commits from upstream:"
GITPAGER=cat git log --reverse --pretty=oneline --abbrev-commit $BRANCH..$OPT_REMOTE/$RBRANCH
if ! ask_confirmation; then
exit 0
fi
NEED_REBASE=1
else
echo "Local branch $BRANCH and remote $OPT_REMOTE/$RBRANCH do not point to the "
echo "same commit, and it is NOT a fastforward. Can't continue."
exit 1
fi
fi
git fetch -f $OPT_REMOTE refs/pull/$PR/head:$TMP_BRANCH
echo "Applying PR #$PR on $RBRANCH of $OPT_REMOTE ($REMOTE) with following commits:"
GITPAGER=cat git log --reverse --pretty=oneline --abbrev-commit $OPT_REMOTE/$RBRANCH..$TMP_BRANCH
if ! ask_confirmation; then
exit 0;
fi
set -ex
if [ -z "$GITHUB_TOKEN" ]; then
read -p "user:" user
AUTH=(-u $user)
else
AUTH=(-H "Authorization: token $GITHUB_TOKEN")
fi
git checkout $BRANCH
if [ $NEED_REBASE == 1 ]; then
git rebase $OPT_REMOTE/$RBRANCH
fi
git cherry-pick HEAD..$TMP_BRANCH
git push $OPT_REMOTE $BRANCH
curl "${AUTH[@]}" --data "{\"body\": \"$MSG\"}" \
https://api.github.com/repos/$REMOTE/issues/$PR/comments
curl "${AUTH[@]}" --request PATCH --data '{"state": "closed"}' \
https://api.github.com/repos/$REMOTE/issues/$PR