Created
June 25, 2018 18:06
-
-
Save DanCech/45d1e5cacea19f5bc9398170ff40170d to your computer and use it in GitHub Desktop.
git-backport
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
# set -x | |
TOKEN=$(git config --get github.token) | |
if [ -z "$TOKEN" ]; then | |
echo 'Please create a personal github token and add it to your git config with git config --global github.token <token>' | |
echo 'https://github.com/settings/tokens' | |
exit 1 | |
fi | |
if [ -z "$1" -o -z "$2" ]; then | |
echo 'Usage: git backport <pr> <release> [remote]' | |
exit 1 | |
fi | |
PR="$1" | |
RELEASE="$2" | |
REMOTE="${3:-origin}" | |
NEWBRANCH="$RELEASE-backport-$PR" | |
CURR=$(git status | grep 'On branch' | sed -e 's/On branch //') | |
REPO=$(git remote -v | grep "^$REMOTE" | head -n1 | sed -r -e 's/.*[:\/](.*\/.*?)(.git?) .*/\1/') | |
if [ -z "$REPO" ]; then | |
echo "Couldn't get repo" | |
exit 1 | |
fi | |
PULL=$(curl -sS -H "Authorization: token $TOKEN" "https://api.github.com/repos/$REPO/pulls/$PR") | |
PATCH_URL=$(echo "$PULL" | jq -r .patch_url) | |
if [ "$PATCH_URL" = "null" ]; then | |
echo "Couldn't get PR info: $PULL" | |
exit 2 | |
fi | |
BODY=$(echo "$PULL" | jq .body) | |
BODY='"'"Backport #$PR to $RELEASE\r\n\r\n${BODY:1}" | |
if [ "$CURR" = "$NEWBRANCH" ]; then | |
echo "Continuing..." | |
CURR="master" | |
else | |
echo "Creating branch $NEWBRANCH to backport #$PR into $RELEASE" | |
git checkout -q -B "$NEWBRANCH" "$RELEASE" | |
PATCH=$(curl -sSL -H "Authorization: token $TOKEN" "$PATCH_URL") | |
trap "echo 'Patch could not be applied, fix issues then run git backport $PR $RELEASE'" ERR | |
echo "$PATCH" | git am -3 | |
trap ERR | |
fi | |
git push "$REMOTE" "$NEWBRANCH":"$NEWBRANCH" | |
NEWPULL=$(curl -sS -H "Authorization: token $TOKEN" "https://api.github.com/repos/$REPO/pulls" -d '{"title":"Backport #'"$PR to $RELEASE"'","head":"'"$NEWBRANCH"'","base":"'"$RELEASE"'","body":'"$BODY"',"maintainer_can_modify":true}') | |
NEWPR=$(echo "$NEWPULL" | jq -r .number) | |
if [ "$NEWPR" = "null" ]; then | |
echo "Couldn't create PR: $NEWPULL" | |
exit 3 | |
fi | |
echo "Opened backport PR #$NEWPR: https://github.com/$REPO/pull/$NEWPR" | |
git checkout -q "$CURR" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment