Skip to content

Instantly share code, notes, and snippets.

@rossille
Last active August 29, 2015 14:06
Show Gist options
  • Save rossille/6757bb1128e7f83cf60c to your computer and use it in GitHub Desktop.
Save rossille/6757bb1128e7f83cf60c to your computer and use it in GitHub Desktop.
Creates a PR from staged content
#!/usr/bin/env bash
# Adds the "git pr" command. Create a PR from the staged changes.
# Use:
# git pr "Small change"
# Install / Update:
# sudo wget -O /usr/bin/git-pr http://tinyurl.com/qg5ek45 && sudo chmod +x /usr/bin/git-pr
if [ -z "$1" ]
then
echo "Use: git pr \"Sample commit message\""
exit
fi
function fail {
echo "=========================== FAILED ==========================="
echo >&2 $1
exit 1
}
#http://stackoverflow.com/questions/296536/urlencode-from-a-bash-script
urlencode() {
local string="${1}"
local strlen=${#string}
local encoded=""
for (( pos=0 ; pos<strlen ; pos++ )); do
c=${string:$pos:1}
case "$c" in
[-_.~a-zA-Z0-9] ) o="${c}" ;;
* ) printf -v o '%%%02x' "'$c"
esac
encoded+="${o}"
done
echo "${encoded}" # You can either set a return variable (FASTER)
REPLY="${encoded}" #+or echo the result (EASIER)... or both... :p
}
patch=`mktemp`
git diff --cached > $patch
repo_url=`git config --get remote.origin.url`
dir=`mktemp -d` && cd $dir
git clone $repo_url || fail "Could not clone repo. Exiting..."
cd *
# Create slug (https://gist.github.com/saml/4674977)
message=$1
max_length="${2:-48}"
slug="$({
tr '[A-Z]' '[a-z]' | tr -cs '[[:alnum:]]' '-'
} <<< "$message")"
slug="${slug##-}"
slug="${slug%%-}"
slug="${slug:0:$max_length}"
branch=feature/$slug
git checkout -b $branch
git apply $patch || fail "Could not apply patch. Exiting..."
git add --all .
git commit -m "$message"
git push -u origin $branch || fail "Could not push branch. Exiting..."
pr_url=${repo_url/git@github.com:/https://github.com/}
pr_url=${pr_url/.git//compare/$branch?expand=1&title=$(urlencode "$message")&$(urlencode pull_request[body])=$(urlencode "Created with [git pr](https://gist.github.com/rossille/6757bb1128e7f83cf60c/). Merge this pr with:")%0D%0A$(urlencode "\`\`dir=\`mktemp -d\` && cd \$dir && git clone $repo_url && cd * && git checkout -b $branch origin/$branch && git rebase develop && git push -f && git flow feature finish && git push\`\`")}
dir=\`mktemp -d\` && cd $dir && git clone $repo_url && cd * && git checkout -b $branch origin/$branch && git rebase develop && git push -f && git flow feature finish && git push
echo "=========================== SUCCESS ==========================="
echo "All done, ready to create PR here: $pr_url"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment