unixorn/git-extra-commands

View on GitHub
bin/git-rel

Summary

Maintainability
Test Coverage
#!/usr/bin/env bash
# Original source: http://github.com/rtomayko/dotfiles
# Usage: git-rel [<ref>]
# Shows the relationship between the current branch and <ref>. With no <ref>,
# the current branch's remote tracking branch is used.
#
# Examples:
#
#   $ git-rel
#     15 ahead
#     11 behind
#
#   $ git-rel v1.1
#     230 ahead

# shellcheck disable=SC2046,SC2086
strip_prefix () {
    # shellcheck disable=SC2001
    echo "$@" |
    sed 's@refs/heads/@@'
}

current_branch () {
    git symbolic-ref -q HEAD |
    sed 's@refs/heads/@@'
}

tracking_branch () {
    remote=$(git config --get branch.$(current_branch).remote)
    merge=$(git config --get branch.$(current_branch).merge)
    echo "$remote/$(strip_prefix $merge)"
}

ref="${1:-$(tracking_branch)}"

git rev-list --left-right --abbrev-commit --abbrev "$ref"...HEAD |
cut -c1         |
sort            |
uniq -c         |
tr '\n' ','     |
sed "
  s/>/ahead/
  s/</behind/
  s/,$//g
  s/,/, /g
"