unixorn/git-extra-commands

View on GitHub
bin/git-recently-checkedout-branches

Summary

Maintainability
Test Coverage
#!/usr/bin/env bash
# Usage: git recently-checkedout-branches
#
# Shows timestamp and name of recently checked-out branches in reverse
# chronological order. This is powered by git-reflog, but excludes branches
# that have since been deleted.
# Author: Mislav Marohnić

set -e

[ "$1" = "-h" ] && exec sed -ne '/^#/!q;s/.\{1,2\}//;1d;p' < "$0"

seen=":"
git_dir="$(git rev-parse --git-dir)"

# shellcheck disable=SC2162
git reflog -n100 --pretty='%cr|%gs' --grep-reflog='checkout: moving' HEAD | \
  while read line; do
    date="${line%%|*}"
    branch="${line##* }"
    if ! [[ $seen == *:"${branch}":* ]]; then
      seen="${seen}${branch}:"
      if [ -f "${git_dir}/refs/heads/${branch}" ]; then
        printf "%s\t%s\n" "$date" "$branch"
      fi
    fi
  done