Skip to content

Instantly share code, notes, and snippets.

@ErinCall
Last active Jun 7, 2018
Embed
What would you like to do?
Script for removing stale branches
#!/usr/bin/env bash
set -e
candidates=''
stale=''
dry_run=''
review_issues=''
case $1 in
'--dry-run')
dry_run='yeppers'
;;
'--review-issues')
review_issues='yepperooni'
;;
*)
;;
esac
function gather_candidates {
# gather branches that exist on origin
candidates=$(git branch -a | grep remotes/origin)
# Exclude branches with version numbers
candidates=$(printf '%s\n' $candidates | grep -v '\d\.')
# Splitting the branches on newlines turns
# "remotes/origin/HEAD -> origin/development" into
# "remotes/origin/HEAD\n->\ndevelopment", so strip the ->
candidates=$(printf '%s\n' $candidates | grep -v -- '->')
# Exclude primary branches
candidates=$(printf '%s\n' $candidates | grep -Ev 'development|master|HEAD')
# Strip off the "remotes" prefix
candidates=$(printf '%s\n' $candidates | sed -E 's| *remotes/origin/||')
}
function gather_stale {
for branch in $candidates; do
# look for commits that are on $branch but not on development
changes=$(git log --oneline "development..origin/$branch")
if [ -z "$changes" ]; then
stale="$stale $branch"
fi
done
stale=$(echo $stale | sort)
}
function prune {
if [ -z $dry_run ]; then
for branch in $stale; do
# remove the branch on origin
git push origin ":$branch" || true
done
else
echo "Would have deleted:"
for branch in $stale; do
latest=$(git log -1 --format='%cd' --date=short "origin/$branch")
echo "$branch (last commit $latest)"
done
fi
}
gather_candidates
gather_stale
if [ -z $review_issues ]; then
prune
else
issues="$(printf '%s\n' $stale | grep -Eo '^[A-Z]+-\d+')"
for issue in $issues; do
open "https://jira.gslabs.us/browse/$issue"
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment