#!/bin/sh
# Show local branch update times, ancestry, and commit differences.

set -eu
# Use a fixed locale for reference ordering and Git date text.
export LC_ALL=C

# UTF-8 symbols for commit counts, branch state, and containment paths.
upArrow=$(printf '\342\206\221')
downArrow=$(printf '\342\206\223')
currentSymbol=$(printf '\342\227\217')
equalSymbol=$(printf '\342\211\241')
lastConnector=$(printf '\342\224\224\342\224\200\342\224\200')
otherConnector=$(printf '\342\224\234\342\224\200\342\224\200')
pathSymbol=$(printf '\342\224\202')

# Read command-line options and select terminal color.
parseOptions() {
    mode=tree
    color=auto
    base=
    while [ "$#" -gt 0 ]; do
        case $1 in
            --list)
                mode=list
                ;;
            --color)
                color=always
                ;;
            --no-color)
                color=never
                ;;
            --base)
                if [ "$#" -lt 2 ] || [ -z "$2" ]; then
                    printf '%s\n' 'git-branches: --base needs a reference' >&2
                    exit 2
                fi
                base=$2
                shift
                ;;
            -h|--help)
                cat <<HELP
Usage: git branches [--list] [--base REF] [--color|--no-color]

Show local branches as a tree of full history containment.
Parents are immediate descendant tips and contain their children.
Shared history appears below each parent that contains it.
Equal tips are marked $equalSymbol. Prefer the current branch, then the default branch.
Update time is the latest local reflog entry, or the tip commit date.
Trees and siblings are ordered by their most recent update.
Use --list for all branches in strict update order.
Color is automatic in terminals. NO_COLOR or TERM=dumb disables auto color.
Use --color or --no-color to override automatic color selection.

$upArrow/$downArrow counts are commits ahead/behind the parent (tree) or base (list).
Roots compare with --base REF. The default is the local origin/HEAD branch,
then main, master, HEAD, or the most recently updated branch.
Upstream counts compare with the locally stored upstream reference.
$currentSymbol marks the checked-out branch.

Requires Git 2.41 or later, awk, sort, mktemp, and GNU wc with the C.UTF-8 locale.
No repository changes are made.
HELP
                exit 0
                ;;
            *)
                printf 'git-branches: unknown option: %s\n' "$1" >&2
                exit 2
                ;;
        esac
        shift
    done

    case $color in
        always)
            color=1
            ;;
        never)
            color=0
            ;;
        auto)
            color=0
            if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; then
                color=1
            fi
            ;;
    esac
}

# Select the local default branch from origin/HEAD, main, or master.
selectDefault() {
    defaultRef=
    remoteDefault=$(git symbolic-ref -q refs/remotes/origin/HEAD || :)
    case $remoteDefault in
        refs/remotes/origin/*)
            localDefault=refs/heads/${remoteDefault#refs/remotes/origin/}
            if git show-ref --verify --quiet "$localDefault"; then
                defaultRef=$localDefault
            fi
            ;;
    esac
    if [ -z "$defaultRef" ]; then
        if git show-ref --verify --quiet refs/heads/main; then
            defaultRef=refs/heads/main
        elif git show-ref --verify --quiet refs/heads/master; then
            defaultRef=refs/heads/master
        fi
    fi
    defaultName=${defaultRef#refs/heads/}
}

# Read branch metadata and upstream state from one reference snapshot.
readReferences() {
    refFormat='%(refname)%09%(objectname)%09%(objectname:short)'
    refFormat=$refFormat'%09%(committerdate:unix)%09%(committerdate:iso8601)'
    refFormat=$refFormat'%09%(committerdate:relative)%09%(upstream)'
    refFormat=$refFormat'%09%(upstream:track,nobracket)'
    git for-each-ref --format="$refFormat" refs/heads/ > "$scratch/refs"

    if [ ! -s "$scratch/refs" ]; then
        echo 'No local branches.'
        exit 0
    fi
}

# Sort branches by their latest reflog time or tip commit time.
# One reflog walk per date format reads the latest entry of all branches.
readUpdates() {
    current=$(git symbolic-ref -q HEAD || :)
    cut -f 1 "$scratch/refs" > "$scratch/names"
    for format in unix iso relative; do
        git -c log.showSignature=false log --walk-reflogs --stdin \
            --date="$format" --format=%gD < "$scratch/names" > "$scratch/reflog.$format"
    done
    # Each reflog walk shows the latest entry of a branch first.
    awk -F '\t' '
        FILENAME != ARGV[4] {
            slot = FILENAME == ARGV[1] ? 1 : FILENAME == ARGV[2] ? 2 : 3
            at = index($0, "@{")
            ref = substr($0, 1, at - 1)
            if ((ref, slot) in update) next
            update[ref, slot] = substr($0, at + 2, length($0) - at - 2)
            next
        }
        {
            if (($1, 1) in update) {
                printf "%s\t%s\t%s\t", update[$1, 1], update[$1, 2], update[$1, 3]
            } else {
                printf "%s\t%s\t%s\t", $4, $5, $6
            }
            printf "%s\t%s\t%s\t%s\t%s\n", $1, $2, $7, $3, $8
        }
    ' "$scratch/reflog.unix" "$scratch/reflog.iso" "$scratch/reflog.relative" \
        "$scratch/refs" > "$scratch/updates"
    sort -t "$tab" -k1,1nr -k4,4 "$scratch/updates" > "$scratch/sorted"
}

# Resolve the explicit or default comparison base to a commit ID.
selectBase() {
    if [ -z "$base" ]; then
        if [ -n "$defaultRef" ]; then
            base=$defaultRef
        elif git rev-parse --verify --quiet 'HEAD^{commit}' > /dev/null; then
            base=HEAD
        else
            IFS="$tab" read -r stamp date age base rest < "$scratch/sorted"
        fi
    fi
    baseOid=$(git rev-parse --verify --end-of-options "$base^{commit}")
}

# Count commits ahead of and behind the base for all branches.
readBaseCounts() {
    git for-each-ref --format="%(refname)%09%(ahead-behind:$baseOid)" refs/heads/ \
        > "$scratch/base"
}

# Measure display columns of branch names that contain non-ASCII bytes.
# Other names use their byte length.
readWidths() {
    awk -F '\t' '$4 ~ /[^ -~]/ { print substr($4, 12) }' "$scratch/sorted" |
        while IFS= read -r name; do
            columns=$(printf '%s\n' "$name" | LC_ALL=C.UTF-8 wc -L)
            printf '%s\t%s\n' "$name" "$columns"
        done > "$scratch/widths"
}

# Record ancestor distances between distinct branch tips.
# Each line holds a tip, a tip that it contains, and the commits between them.
# One reference walk computes the counts for a chunk of comparison tips.
readContainment() {
    cut -f 2 "$scratch/refs" | sort -u | awk '
        {
            format = format (count ? "%0a" : "") "%(objectname) " $0 " %(ahead-behind:" $0 ")"
            if (++count == 256) {
                print format
                format = ""
                count = 0
            }
        }
        END { if (count) print format }
    ' > "$scratch/formats"
    while IFS= read -r format; do
        git for-each-ref --format="$format" refs/heads/ > "$scratch/chunk"
        awk '$3 > 0 && $4 == 0 && !seen[$1, $2]++ { print $1 "\t" $2 "\t" $3 }' \
            "$scratch/chunk" >> "$scratch/containment"
    done < "$scratch/formats"
}

# Build the containment tree, measure the layout, and print all rows.
render() {
    awk -F '\t' \
        -v mode="$mode" -v color="$color" -v current="$current" -v defaultName="$defaultName" \
        -v upArrow="$upArrow" -v downArrow="$downArrow" -v currentSymbol="$currentSymbol" \
        -v equalSymbol="$equalSymbol" -v lastConnector="$lastConnector" \
        -v otherConnector="$otherConnector" -v pathSymbol="$pathSymbol" \
        -v widthFile="$scratch/widths" -v baseFile="$scratch/base" \
        -v sortedFile="$scratch/sorted" -v containmentFile="$scratch/containment" '
        # Prefer the current branch, default branch, and then update order.
        function preferred(left, right) {
            if (marker[left] != marker[right]) return marker[left] == 1
            if (name[left] == defaultName && name[right] != name[left]) return 1
            if (name[right] == defaultName && name[left] != name[right]) return 0
            return left < right
        }

        # Append a child and its commit distance to a parent node.
        function addChild(parent, node, delta) {
            childCount[parent]++
            child[parent, childCount[parent]] = node
            childDelta[parent, childCount[parent]] = delta
        }

        # Cache the newest branch index in each containment subtree.
        function freshness(node,    k, best, rank) {
            if (node in freshest) return freshest[node]
            best = node
            for (k = 1; k <= childCount[node]; k++) {
                rank = freshness(child[node, k])
                if (rank < best) best = rank
            }
            freshest[node] = best
            return best
        }

        # Record the greatest depth across all containment paths.
        # Nodes are visited in topological order from the roots.
        function measureDepths(    i, k, node, nextNode, head, tail, queue, incoming) {
            for (i = 1; i <= n; i++) {
                for (k = 1; k <= childCount[i]; k++) incoming[child[i, k]]++
            }
            head = 1
            tail = 0
            for (k = 1; k <= childCount[0]; k++) {
                queue[++tail] = child[0, k]
                depth[child[0, k]] = 1
            }
            while (head <= tail) {
                node = queue[head++]
                for (k = 1; k <= childCount[node]; k++) {
                    nextNode = child[node, k]
                    if (depth[node] + 1 > depth[nextNode]) depth[nextNode] = depth[node] + 1
                    if (--incoming[nextNode] == 0) queue[++tail] = nextNode
                }
            }
        }

        # Select siblings by subtree freshness and equal-tip preference.
        function orderSiblings(node,    k, c, tipKey, best, bestTip, bestRank, bestDelta, candidateTip, candidateRank, selected) {
            for (k = 1; k <= childCount[node]; k++) {
                c = child[node, k]
                tipKey = node SUBSEP tip[c]
                if (!(tipKey in groupRank) || freshest[c] < groupRank[tipKey]) {
                    groupRank[tipKey] = freshest[c]
                }
            }
            for (;;) {
                best = 0
                for (k = 1; k <= childCount[node]; k++) {
                    c = child[node, k]
                    if (c in selected) continue
                    candidateTip = tip[c]
                    candidateRank = groupRank[node, candidateTip]
                    if (best != 0) {
                        if (candidateRank > bestRank) continue
                        if (candidateRank == bestRank) {
                            if (candidateTip == bestTip) {
                                if (!preferred(c, best)) continue
                            } else if (c > best) {
                                continue
                            }
                        }
                    }
                    best = c
                    bestTip = candidateTip
                    bestRank = candidateRank
                    bestDelta = childDelta[node, k]
                }
                if (best == 0) break
                selected[best] = 1
                orderedCount[node]++
                ordered[node, orderedCount[node]] = best
                orderedDelta[node, orderedCount[node]] = bestDelta
            }
        }

        # Attach equal tips and immediate ancestors to their containing branches.
        function buildTree(    i, k, m, t, other, middle, immediate, node, tipCount, tips, canonical, contained, containedCount) {
            for (i = 1; i <= n; i++) {
                t = tip[i]
                if (t in canonical) {
                    if (preferred(i, canonical[t])) canonical[t] = i
                } else {
                    canonical[t] = i
                    tips[++tipCount] = t
                }
            }
            for (i = 1; i <= n; i++) {
                t = tip[i]
                if (i != canonical[t]) {
                    addChild(canonical[t], i, 0)
                    equal[i] = 1
                    hasParent[i] = 1
                    continue
                }
                containedCount = 0
                for (k = 1; k <= tipCount; k++) {
                    if ((t, tips[k]) in distance) contained[++containedCount] = tips[k]
                }
                for (k = 1; k <= containedCount; k++) {
                    other = contained[k]
                    immediate = 1
                    for (m = 1; m <= containedCount; m++) {
                        if ((contained[m], other) in distance) {
                            immediate = 0
                            break
                        }
                    }
                    if (immediate) {
                        node = canonical[other]
                        addChild(i, node, distance[t, other])
                        hasParent[node] = 1
                    }
                }
            }
            for (i = 1; i <= n; i++) {
                if (!(i in hasParent)) {
                    addChild(0, i, 0)
                    freshness(i)
                }
            }
            measureDepths()
            for (i = 0; i <= n; i++) orderSiblings(i)
        }

        # Measure uncolored text and display columns before printing any rows.
        function measureLayout(    i, k, width) {
            countWidth = 3
            dateWidth = 25
            ageWidth = 12
            hashWidth = 0
            branchWidth = 0
            for (i = 1; i <= n; i++) {
                if (length(date[i]) > dateWidth) dateWidth = length(date[i])
                if (length(age[i]) > ageWidth) ageWidth = length(age[i])
                if (length(hash[i]) > hashWidth) hashWidth = length(hash[i])
                if (length(ahead[i]) > countWidth) countWidth = length(ahead[i])
                if (length(behind[i]) > countWidth) countWidth = length(behind[i])
                width = columns[i]
                if (mode == "tree") {
                    width += 4 * depth[i]
                    if (i in equal) width += 2
                }
                if (width > branchWidth) branchWidth = width
            }
            if (mode == "tree") {
                for (i = 0; i <= n; i++) {
                    for (k = 1; k <= childCount[i]; k++) {
                        if (length(childDelta[i, k]) > countWidth) countWidth = length(childDelta[i, k])
                    }
                }
            }
        }

        # Return a run of spaces with the given length.
        function spaces(count,    text) {
            text = ""
            while (count-- > 0) text = text " "
            return text
        }

        # Apply terminal color to text.
        function paint(style, text) {
            if (color) return "\033[" style "m" text "\033[0m"
            return text
        }

        # Format a commit count with a gray arrow and a colored nonzero value.
        function formatCount(value, arrow, style) {
            if (value == 0) style = 90
            return spaces(countWidth - length(value)) paint("2;90", arrow) paint(style, value)
        }

        # Print update time, counts, hash, branch label, and upstream state.
        function printRow(i, prefix, labelDepth, plus, minus,    line, labelWidth, symbol, style) {
            labelWidth = columns[i]
            symbol = " "
            style = "1;36"
            if (marker[i] == 1) {
                symbol = currentSymbol
                style = "1;32"
            }
            line = paint("1;32", symbol) " "
            line = line paint(90, date[i] spaces(dateWidth - length(date[i]))) "  "
            line = line paint(90, age[i] spaces(ageWidth - length(age[i]))) " "
            line = line formatCount(plus, upArrow, 32) " "
            line = line formatCount(minus, downArrow, 31) "  "
            line = line paint("2;33", hash[i] spaces(hashWidth - length(hash[i]))) "  "
            if (labelDepth > 0) {
                line = line paint(90, prefix)
                labelWidth += 4 * labelDepth
            }
            line = line paint(style, name[i])
            if (mode == "tree" && (i in equal)) {
                line = line paint(33, " " equalSymbol)
                labelWidth += 2
            }
            if (tracking[i] != "-") {
                line = line spaces(branchWidth - labelWidth + 2) paint(90, tracking[i])
            }
            print line
        }

        # Print every immediate containment path in cached sibling order.
        function printTree(node, prefix, depth_,    k, c, connector, nextPrefix) {
            for (k = 1; k <= orderedCount[node]; k++) {
                c = ordered[node, k]
                if (k == orderedCount[node]) {
                    connector = lastConnector " "
                    nextPrefix = prefix "    "
                } else {
                    connector = otherConnector " "
                    nextPrefix = prefix pathSymbol "   "
                }
                if (node == 0) {
                    printRow(c, prefix connector, depth_, ahead[c], behind[c])
                } else {
                    printRow(c, prefix connector, depth_, 0, orderedDelta[node, k])
                }
                printTree(c, nextPrefix, depth_ + 1)
            }
        }

        # Format upstream state from the reference name and tracking counts.
        function formatTracking(upstream, track,    text, parts, k, plus, minus) {
            if (upstream == "") return "-"
            if (track == "gone") {
                text = upstream
                sub(/^refs\/remotes\//, "", text)
                return text " (gone)"
            }
            plus = 0
            minus = 0
            split(track, parts, ", ")
            for (k in parts) {
                if (parts[k] ~ /^ahead /) plus = substr(parts[k], 7)
                if (parts[k] ~ /^behind /) minus = substr(parts[k], 8)
            }
            text = upstream
            sub(/^refs\/heads\//, "", text)
            text = text " " upArrow plus " " downArrow minus
            sub(/^refs\/remotes\//, "", text)
            return text
        }

        FILENAME == widthFile {
            width[$1] = $2
            next
        }
        FILENAME == baseFile {
            split($2, counts, " ")
            baseAhead[$1] = counts[1]
            baseBehind[$1] = counts[2]
            next
        }
        FILENAME == sortedFile {
            n++
            name[n] = substr($4, 12)
            tip[n] = $5
            date[n] = $2
            age[n] = $3
            marker[n] = $4 == current
            ahead[n] = baseAhead[$4]
            behind[n] = baseBehind[$4]
            tracking[n] = formatTracking($6, $8)
            hash[n] = $7
            columns[n] = (name[n] in width) ? width[name[n]] : length(name[n])
            next
        }
        FILENAME == containmentFile {
            distance[$1, $2] = $3
        }
        END {
            if (mode == "list") {
                measureLayout()
                for (i = 1; i <= n; i++) printRow(i, "", 0, ahead[i], behind[i])
            } else {
                buildTree()
                measureLayout()
                printTree(0, "", 1)
            }
        }
    ' "$scratch/widths" "$scratch/base" "$scratch/sorted" "$scratch/containment"
}

parseOptions "$@"
git rev-parse --git-dir > /dev/null
scratch=$(mktemp -d "${TMPDIR:-/tmp}/git-branches.XXXXXXXX")
trap 'rm -rf "$scratch"' 0
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
tab=$(printf '\t')

readReferences
selectDefault
readUpdates
selectBase
readBaseCounts
readWidths
: > "$scratch/containment"
if [ "$mode" = tree ]; then
    readContainment
fi
render
