Skip to content

Instantly share code, notes, and snippets.

@kojinkai
Last active June 18, 2019 15:22
Show Gist options
  • Save kojinkai/5063df1187aa2f84711aa49e324579ba to your computer and use it in GitHub Desktop.
Save kojinkai/5063df1187aa2f84711aa49e324579ba to your computer and use it in GitHub Desktop.
A small shell script to run after closing a Pull Request

Branch Cleanup

Rationale

When working on topic branches, you often have a many old branches clogging up your local and remote repositories. This small command line tool can be run immediatley after closing a Pull Request to prune away the topic branch both locally and remotely and then bring your target branch up to date automatically before starting your new topic branch. This keeps your git repo free from clutter and ensures you always begin new branches at the point of integration - at the head of your project's target branch.

Installation

Create a branch-cleanup script in a folder. This folder should be in your path for it to be executable from the CLI.

touch ~/path/to/your/folder/new-branch

Change the mode of the file to make it executable

chmod +x /path/to/your/folder/new-branch

In a new shell check everything is working. Running which branch-cleanup should output the script location if the folder you created the script in is exported into your path.

→ which branch-cleanup
/path/to/your/folder/new-branch

Usage

The default target branch assumed by the script is develop.

Running:

branch-cleanup
  • Deletes the remote copy of the branch
  • Checks out to your local develop branch
  • Pulls the remote develop code using the fast forward method
  • Deletes the now obselete topic branch
  • Prunes the branches from origin

Passing a target-branch is optional as the script will default to develop but if your integration branch is named something else, such as release/2.0.0 then you can pass this as an argument like so

branch-cleanup release/2.0.0

And the script will execute the same routine as above but will replace develop with your target branch

#!/usr/bin/env bash
function cleanup {
local cleanupBranch=`git rev-parse --abbrev-ref HEAD`
echo "Deleting remote branch"
git push origin --delete $cleanupBranch
if [ -z "$1" ]
then
echo "Checking out develop"
targetBranch=develop;
else
echo "Checking out $targetBranch"
targetBranch=$1;
fi
git checkout $targetBranch -f
git pull --ff
echo "Deleting local $cleanupBranch"
git branch -D $cleanupBranch
git remote prune origin
return
}
# $1 is the first argument to the branch cleanup command
cleanup $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment