Hina-Mode

とある呑んだくれエンジニアの気が向いた時に書く戯言

【Git】masterにmergeしたbranch群を一括で削除するshellScript

仕事でbranchを管理するのが面倒だったので、「リリースするときに古いブランチ消せば解決じゃね?」って思ったのが始まり。
指定したタグより前のブランチを全て削るようにしています。

判定的には指定したタグにブランチのコミットが全部入っていれば削除、
何かコミットが残っていれば残し、という感じ。

かなり適当に作ってあるので改善したい方はご自由にどうぞ持って行ってください。
Gist?なにそれ美味しいの?

■前提

  • ファイル名はcheck_branch.sh
  • 初期gitディレクトリパスは~/git/src/php (オプションで変更可能)
  • gitコマンドにパスが通っている
  • パスワード入力なしでgit pushが可能(ssh-keygenとかして。)
#!/bin/sh
#-------------------------------------------------
# check old branch and delete script
#-------------------------------------------------
result=""
dirpath="~/git/src/php"
tag=""
execDel=""

while getopts t:g:s OPT
do
    case $OPT in
        "t" ) tag="$OPTARG";;
        "g" ) dirpath="$OPTARG";;
        "s" ) execDel="n";;
        * ) echo "option list:"
            echo "  -t ... tag name (required)"
            echo "  -g ... git repository directory"
            echo "  -s ... only show branch (dont delete)"
            exit
    esac
done

if [ "$tag" == "" ]; then
    echo "command failed."
    echo "   --usage"
    echo "   check_branch.sh [options]"
    exit
fi

cd $dirpath
# update all branches
git fetch --prune
conf=`git tag --list | grep -E "${tag}"`
if [ "$conf" != "$tag" ]; then
    echo "tag not exists."
    exit
fi

echo "Display deletable tag list."
for i in `git branch --remotes | grep -v HEAD | grep -v master | grep -v devel | grep -v release`
do
    tmp=`git log --pretty=format:"|%h|%an|%s|" --no-merges remotes/origin/devel..remotes/$i | wc -w`
    tmp2=`git log --pretty=format:"|%h|%an|%s|" --no-merges remotes/origin/master..remotes/$i | wc -w`
    tmp3=`git log --pretty=format:"|%h|%an|%s|" --no-merges $tag..remotes/$i | wc -w`
    if [ `expr $tmp + $tmp2 + $tmp3` == 0 ]; then
        line=`echo $i | sed -e "s/^origin\///g"`
        result="$result $line"
        echo $i

    fi
done

if [ "$result" == "" ]; then
    echo "there are no deletable branch. script done."
    exit
fi

if [ "$execDel" != "n" ]; then
    echo ""
    echo "do you want delete them? [y/n]"
    read YN
    if [ "$YN" == "y" ]; then
        for j in $result
        do
            git branch -D $j
            git push origin :$j
        done
    fi
fi