Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
git-list-merged-branches - A script that can find already merged branches and provide git command to remove them
#!/bin/bash
getopt --test > /dev/null
if [[ $? -ne 4 ]]; then
echo "I’m sorry, `getopt --test` failed in this environment."
exit 1
fi
SHORT=d:b:e:h
LONG=date:,branches:,excluded:,help
# -temporarily store output to be able to check for errors
# -activate advanced mode getopt quoting e.g. via "--options"
# -pass arguments only via -- "$@" to separate them correctly
PARSED=$(getopt --options $SHORT --longoptions $LONG --name "$0" -- "$@")
if [[ $? -ne 0 ]]; then
# e.g. $? == 1
# then getopt has complained about wrong arguments to stdout
exit 2
fi
set -e
# use eval with "$PARSED" to properly handle the quoting
eval set -- "$PARSED"
past=$(date --date='1 months ago' --rfc-3339=seconds)
branches='develop'
excluded='master|develop'
showhelp=n
# now enjoy the options in order and nicely split until we see --
while true; do
case "$1" in
-d|--date)
past="$2"
shift 2
;;
-b|--branches)
branches=$(echo $2 | tr ',' "\n")
shift 2
;;
-e|--excluded)
excluded=$(echo $2 | tr ',' '|')
shift 2
;;
-h|--help)
showhelp=y
shift
;;
--)
shift
break
;;
*)
echo "Programming error"
exit 3
;;
esac
done
# handle non-option arguments
if [[ $# -ne 0 ]]; then
echo "$0: No more options are expected."
exit 4
fi
if [[ $showhelp = "y" ]]; then
echo "
Usage: $0 [options]
Options:
-d, --date A boundry date tor which already merged branches
will be searched for. By default: one month ago
-b, --branches A comma seperated list of branches to searched already
merged branches against to. Default to: develop
-e, --excluded A comma seperated list of regex expressions to filter
out found branches. By default: master,develop
-h, --help Prints this help message.
"
exit 5
fi
echo "# Past date: ${past}"
echo "# Branches to check:"
for branch in $branches; do
echo "# - ${branch}"
done
echo "# Branches to be excluded:"
for branch in $(echo "${excluded}" | tr '|' "\n"); do
echo "# - ${branch}"
done
echo ""
for merged in $branches; do
echo "# Listing branches merged to ${merged} older then ${past}..." 1>&2
for branch in $(git branch -a --merged "${merged}" | sed 's/^\s*remotes\///' | grep -vE "(${excluded})"); do
if [[ $(git log ${branch} --since "${past}" | wc -l) -eq 0 ]]; then
if [[ "$branch" =~ "origin/" ]]; then
local_branch_name=$(echo "$branch" | sed 's/^origin\///')
echo "git push origin :$local_branch_name"
else
echo "git branch -D $branch"
fi
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.