#!/bin/sh

#   This script nicely displays the remote Git branches not merged into
# the given branch, together with the list of commits they would introduce.

# Usage:
#   For the current branch:
#     branches_unmerged
#   For the specified branch:
#     branches_unmerged origin/master


# Copyright (c) 2011, Amir Yalon <unmerged@please.nospammail.net>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

if [ "x$1" = "x--color" ]; then
    use_color='true'
    shift
fi

commit=${1:-HEAD}

# Check if we output to a terminal or forced to use colours
if [ -t 1 -o -n "$use_color" ]; then
    branch_color="%C(magenta)"
    an_color="%C(white bold)"
    s_color="%C(yellow)"
    reset_color="%Creset"
fi

IFS=','

{
    # Extract unmerged branch names
    git branch -r --no-merged $commit | grep -ve '->' | cut -d ' ' -f 3
} | while read i; do
    # Prepend fork time to branch names
    base=$(git merge-base $commit $i)
    git log --no-walk --format="%ai,$i,$branch_color,$reset_color%n" $base
done | {
    # Sort by descending fork time
    sort -r
} | while read time i color reset; do
    # For each unmerged branch, print fork time, branch name, commit count
    # and list of commits.
    commits="$(git log --no-merges --format="  $an_color%an:$reset_color $s_color%s$reset_color" $commit..$i)"
    echo "$time $color$i$reset ($(echo "$commits" | wc -l | tr -cd '[[:digit:]]'))"
    echo "$commits"
done | less -SFRX
