Remove Stale Git Branches

Another issue I commonly have to deal with in the multitudes of repositories I oversee and manage: stale git branches. Gitlab has a pretty good interface for pointing these out. The trouble here, is that it’s still a manual process to remove each of these branches. If you’ve got a team of any size working on numerous code bases, this can become a very time consuming process.

So, I wrote some code to solve my problem. This is the crux of it:

  _maxage=$((60*60*24*90))
  _time="$(date '+%s')"
  _starting_branch="$(git rev-parse --abbrev-ref HEAD)"

  # First, update everything
  git fetch --all \
    && git gc --aggressive \
    && git fsck --full

  for _branch in $(git branch -r -vv \
      | awk '{print $1}' \
      | grep -v '\*' \
      | grep -E -v 'master|develop'); do
    echo "${_branch/origin\//}"
    git stash || true 
    git reset HEAD
    git clean -f
    git checkout -f -q "${_branch/origin\//}"
    git pull -q origin "${_branch/origin\//}"

    _timestamp="$(git log "${_branch/origin\//}" \
        -1 --date=unix \
        --pretty='%at')"
    _diff=$((_time - _timestamp))

    if [ ${_diff} -gt ${_maxage} ]; then
        echo "[${_branch/origin\//}] got one"
        git status
        git checkout develop
        git branch -D "${_branch/origin\//}"
        git push origin :"${_branch/origin\//}"
    fi
  done

  git checkout "${_starting_branch}"

As always, I welcome comments and feedback.

Leave a Reply