Skip to content

Instantly share code, notes, and snippets.

@DrPsychick
Last active April 19, 2021 20:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrPsychick/9b9d207c707830ca5e427558f1ee3b57 to your computer and use it in GitHub Desktop.
Save DrPsychick/9b9d207c707830ca5e427558f1ee3b57 to your computer and use it in GitHub Desktop.
Simple bash functions to automate GitHub branches and pull requests
#!/bin/bash
# Workflow: create branch -> create pull request
# git-create-branch-push "issue X"
# -> make changes, commit and push
# github-branch-pr "fix: issue solved" "closes #x"
# -> creates new PR with title and body
#
# Workflow: create branch for issue -> create pull request
# github-issue-branch-push 10
# -> creates branch with issue ID and title, make changes, commit and push
# github-branch-pr "fix: issue solved" "closes #x"
# -> creates new PR with title and body
#
# Workflow: create branch for an issue -> convert issue to pull request
# github-issue-branch-push 10
# -> creates branch with issue ID and title, make changes, commit and push
# github-issue-pr 10
# -> converts issue to PR
# normalize title for branch name
# thanks to https://github.com/Protolane/git-branch-name-normalizer
function git-normalize-branch-name() {
[ -z "$1" ] && {
echo "Usage: $0 <some issue title>"
return
}
echo "$1" | tr -d "'\`" \
| sed -E 's#[\. \"\*\#\!\$\?~\^:\\]#-#g' \
| sed -E 's#-+#-#g' \
| sed -E 's#^[-/]##' \
| sed -E 's#[-/](.lock)?$##'
}
# create a branch, check it out and push it to 'origin'
function git-create-branch-push() {
[ -z "$1" ] && return
git branch $name
git checkout $name
git push --set-upstream origin $name
}
# create a branch for the given issue ID
function github-issue-branch-push() {
[ -z "$1" ] && return
id="$1"
issue=$(hub issue show $id |head -n1)
if [ $? -ne 0 -o -z "$issue" ]; then
echo "Issue $id not found"
elif [ -n "$(echo "$issue" | grep "CLOSED")" ]; then
echo "Issue $id is closed"
else
name="$id-$(git-normalize-branch-name "$issue")"
git-create-branch-push "$name"
fi
}
# create a github pull request for the current brand with the given title and optional body
function github-branch-pr() {
[ -z "$1" ] && return
title="$1"
message=""
if [ -n "$2" ]; then
message="--message \"$2\""
fi
hub pull-request --message "$title" $message
}
# convert an issue to a pull request
function github-issue-pr() {
[ -z "$1" ] && return
id="$1"
issue=$(hub issue show $id |head -n1)
if [ $? -ne 0 ]; then
echo "Issue $id not found"
else
hub pull-request -i $id
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment