Add git-tree script

0ed2a70ef06c8b425bfbf00af80555354ce00c5c
Alexis Sellier committed ago 1 parent cc0ab8d9
bin/git-tree added +535 -0
1 +
#!/bin/sh
2 +
# Show local branch update times, ancestry, and commit differences.
3 +
4 +
set -eu
5 +
# Use a fixed locale for reference ordering and Git date text.
6 +
export LC_ALL=C
7 +
8 +
# UTF-8 symbols for commit counts, branch state, and containment paths.
9 +
upArrow=$(printf '\342\206\221')
10 +
downArrow=$(printf '\342\206\223')
11 +
currentSymbol=$(printf '\342\227\217')
12 +
equalSymbol=$(printf '\342\211\241')
13 +
lastConnector=$(printf '\342\224\224\342\224\200\342\224\200')
14 +
otherConnector=$(printf '\342\224\234\342\224\200\342\224\200')
15 +
pathSymbol=$(printf '\342\224\202')
16 +
17 +
# Read command-line options and select terminal color.
18 +
parseOptions() {
19 +
    mode=tree
20 +
    color=auto
21 +
    base=
22 +
    while [ "$#" -gt 0 ]; do
23 +
        case $1 in
24 +
            --list)
25 +
                mode=list
26 +
                ;;
27 +
            --color)
28 +
                color=always
29 +
                ;;
30 +
            --no-color)
31 +
                color=never
32 +
                ;;
33 +
            --base)
34 +
                if [ "$#" -lt 2 ] || [ -z "$2" ]; then
35 +
                    printf '%s\n' 'git-branches: --base needs a reference' >&2
36 +
                    exit 2
37 +
                fi
38 +
                base=$2
39 +
                shift
40 +
                ;;
41 +
            -h|--help)
42 +
                cat <<HELP
43 +
Usage: git branches [--list] [--base REF] [--color|--no-color]
44 +
45 +
Show local branches as a tree of full history containment.
46 +
Parents are immediate descendant tips and contain their children.
47 +
Shared history appears below each parent that contains it.
48 +
Equal tips are marked $equalSymbol. Prefer the current branch, then the default branch.
49 +
Update time is the latest local reflog entry, or the tip commit date.
50 +
Trees and siblings are ordered by their most recent update.
51 +
Use --list for all branches in strict update order.
52 +
Color is automatic in terminals. NO_COLOR or TERM=dumb disables auto color.
53 +
Use --color or --no-color to override automatic color selection.
54 +
55 +
$upArrow/$downArrow counts are commits ahead/behind the parent (tree) or base (list).
56 +
Roots compare with --base REF. The default is the local origin/HEAD branch,
57 +
then main, master, HEAD, or the most recently updated branch.
58 +
Upstream counts compare with the locally stored upstream reference.
59 +
$currentSymbol marks the checked-out branch.
60 +
61 +
Requires Git 2.41 or later, awk, sort, mktemp, and GNU wc with the C.UTF-8 locale.
62 +
No repository changes are made.
63 +
HELP
64 +
                exit 0
65 +
                ;;
66 +
            *)
67 +
                printf 'git-branches: unknown option: %s\n' "$1" >&2
68 +
                exit 2
69 +
                ;;
70 +
        esac
71 +
        shift
72 +
    done
73 +
74 +
    case $color in
75 +
        always)
76 +
            color=1
77 +
            ;;
78 +
        never)
79 +
            color=0
80 +
            ;;
81 +
        auto)
82 +
            color=0
83 +
            if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; then
84 +
                color=1
85 +
            fi
86 +
            ;;
87 +
    esac
88 +
}
89 +
90 +
# Select the local default branch from origin/HEAD, main, or master.
91 +
selectDefault() {
92 +
    defaultRef=
93 +
    remoteDefault=$(git symbolic-ref -q refs/remotes/origin/HEAD || :)
94 +
    case $remoteDefault in
95 +
        refs/remotes/origin/*)
96 +
            localDefault=refs/heads/${remoteDefault#refs/remotes/origin/}
97 +
            if git show-ref --verify --quiet "$localDefault"; then
98 +
                defaultRef=$localDefault
99 +
            fi
100 +
            ;;
101 +
    esac
102 +
    if [ -z "$defaultRef" ]; then
103 +
        if git show-ref --verify --quiet refs/heads/main; then
104 +
            defaultRef=refs/heads/main
105 +
        elif git show-ref --verify --quiet refs/heads/master; then
106 +
            defaultRef=refs/heads/master
107 +
        fi
108 +
    fi
109 +
    defaultName=${defaultRef#refs/heads/}
110 +
}
111 +
112 +
# Read branch metadata and upstream state from one reference snapshot.
113 +
readReferences() {
114 +
    refFormat='%(refname)%09%(objectname)%09%(objectname:short)'
115 +
    refFormat=$refFormat'%09%(committerdate:unix)%09%(committerdate:iso8601)'
116 +
    refFormat=$refFormat'%09%(committerdate:relative)%09%(upstream)'
117 +
    refFormat=$refFormat'%09%(upstream:track,nobracket)'
118 +
    git for-each-ref --format="$refFormat" refs/heads/ > "$scratch/refs"
119 +
120 +
    if [ ! -s "$scratch/refs" ]; then
121 +
        echo 'No local branches.'
122 +
        exit 0
123 +
    fi
124 +
}
125 +
126 +
# Sort branches by their latest reflog time or tip commit time.
127 +
# One reflog walk per date format reads the latest entry of all branches.
128 +
readUpdates() {
129 +
    current=$(git symbolic-ref -q HEAD || :)
130 +
    cut -f 1 "$scratch/refs" > "$scratch/names"
131 +
    for format in unix iso relative; do
132 +
        git -c log.showSignature=false log --walk-reflogs --stdin \
133 +
            --date="$format" --format=%gD < "$scratch/names" > "$scratch/reflog.$format"
134 +
    done
135 +
    # Each reflog walk shows the latest entry of a branch first.
136 +
    awk -F '\t' '
137 +
        FILENAME != ARGV[4] {
138 +
            slot = FILENAME == ARGV[1] ? 1 : FILENAME == ARGV[2] ? 2 : 3
139 +
            at = index($0, "@{")
140 +
            ref = substr($0, 1, at - 1)
141 +
            if ((ref, slot) in update) next
142 +
            update[ref, slot] = substr($0, at + 2, length($0) - at - 2)
143 +
            next
144 +
        }
145 +
        {
146 +
            if (($1, 1) in update) {
147 +
                printf "%s\t%s\t%s\t", update[$1, 1], update[$1, 2], update[$1, 3]
148 +
            } else {
149 +
                printf "%s\t%s\t%s\t", $4, $5, $6
150 +
            }
151 +
            printf "%s\t%s\t%s\t%s\t%s\n", $1, $2, $7, $3, $8
152 +
        }
153 +
    ' "$scratch/reflog.unix" "$scratch/reflog.iso" "$scratch/reflog.relative" \
154 +
        "$scratch/refs" > "$scratch/updates"
155 +
    sort -t "$tab" -k1,1nr -k4,4 "$scratch/updates" > "$scratch/sorted"
156 +
}
157 +
158 +
# Resolve the explicit or default comparison base to a commit ID.
159 +
selectBase() {
160 +
    if [ -z "$base" ]; then
161 +
        if [ -n "$defaultRef" ]; then
162 +
            base=$defaultRef
163 +
        elif git rev-parse --verify --quiet 'HEAD^{commit}' > /dev/null; then
164 +
            base=HEAD
165 +
        else
166 +
            IFS="$tab" read -r stamp date age base rest < "$scratch/sorted"
167 +
        fi
168 +
    fi
169 +
    baseOid=$(git rev-parse --verify --end-of-options "$base^{commit}")
170 +
}
171 +
172 +
# Count commits ahead of and behind the base for all branches.
173 +
readBaseCounts() {
174 +
    git for-each-ref --format="%(refname)%09%(ahead-behind:$baseOid)" refs/heads/ \
175 +
        > "$scratch/base"
176 +
}
177 +
178 +
# Measure display columns of branch names that contain non-ASCII bytes.
179 +
# Other names use their byte length.
180 +
readWidths() {
181 +
    awk -F '\t' '$4 ~ /[^ -~]/ { print substr($4, 12) }' "$scratch/sorted" |
182 +
        while IFS= read -r name; do
183 +
            columns=$(printf '%s\n' "$name" | LC_ALL=C.UTF-8 wc -L)
184 +
            printf '%s\t%s\n' "$name" "$columns"
185 +
        done > "$scratch/widths"
186 +
}
187 +
188 +
# Record ancestor distances between distinct branch tips.
189 +
# Each line holds a tip, a tip that it contains, and the commits between them.
190 +
# One reference walk computes the counts for a chunk of comparison tips.
191 +
readContainment() {
192 +
    cut -f 2 "$scratch/refs" | sort -u | awk '
193 +
        {
194 +
            format = format (count ? "%0a" : "") "%(objectname) " $0 " %(ahead-behind:" $0 ")"
195 +
            if (++count == 256) {
196 +
                print format
197 +
                format = ""
198 +
                count = 0
199 +
            }
200 +
        }
201 +
        END { if (count) print format }
202 +
    ' > "$scratch/formats"
203 +
    while IFS= read -r format; do
204 +
        git for-each-ref --format="$format" refs/heads/ > "$scratch/chunk"
205 +
        awk '$3 > 0 && $4 == 0 && !seen[$1, $2]++ { print $1 "\t" $2 "\t" $3 }' \
206 +
            "$scratch/chunk" >> "$scratch/containment"
207 +
    done < "$scratch/formats"
208 +
}
209 +
210 +
# Build the containment tree, measure the layout, and print all rows.
211 +
render() {
212 +
    awk -F '\t' \
213 +
        -v mode="$mode" -v color="$color" -v current="$current" -v defaultName="$defaultName" \
214 +
        -v upArrow="$upArrow" -v downArrow="$downArrow" -v currentSymbol="$currentSymbol" \
215 +
        -v equalSymbol="$equalSymbol" -v lastConnector="$lastConnector" \
216 +
        -v otherConnector="$otherConnector" -v pathSymbol="$pathSymbol" \
217 +
        -v widthFile="$scratch/widths" -v baseFile="$scratch/base" \
218 +
        -v sortedFile="$scratch/sorted" -v containmentFile="$scratch/containment" '
219 +
        # Prefer the current branch, default branch, and then update order.
220 +
        function preferred(left, right) {
221 +
            if (marker[left] != marker[right]) return marker[left] == 1
222 +
            if (name[left] == defaultName && name[right] != name[left]) return 1
223 +
            if (name[right] == defaultName && name[left] != name[right]) return 0
224 +
            return left < right
225 +
        }
226 +
227 +
        # Append a child and its commit distance to a parent node.
228 +
        function addChild(parent, node, delta) {
229 +
            childCount[parent]++
230 +
            child[parent, childCount[parent]] = node
231 +
            childDelta[parent, childCount[parent]] = delta
232 +
        }
233 +
234 +
        # Cache the newest branch index in each containment subtree.
235 +
        function freshness(node,    k, best, rank) {
236 +
            if (node in freshest) return freshest[node]
237 +
            best = node
238 +
            for (k = 1; k <= childCount[node]; k++) {
239 +
                rank = freshness(child[node, k])
240 +
                if (rank < best) best = rank
241 +
            }
242 +
            freshest[node] = best
243 +
            return best
244 +
        }
245 +
246 +
        # Record the greatest depth across all containment paths.
247 +
        # Nodes are visited in topological order from the roots.
248 +
        function measureDepths(    i, k, node, nextNode, head, tail, queue, incoming) {
249 +
            for (i = 1; i <= n; i++) {
250 +
                for (k = 1; k <= childCount[i]; k++) incoming[child[i, k]]++
251 +
            }
252 +
            head = 1
253 +
            tail = 0
254 +
            for (k = 1; k <= childCount[0]; k++) {
255 +
                queue[++tail] = child[0, k]
256 +
                depth[child[0, k]] = 1
257 +
            }
258 +
            while (head <= tail) {
259 +
                node = queue[head++]
260 +
                for (k = 1; k <= childCount[node]; k++) {
261 +
                    nextNode = child[node, k]
262 +
                    if (depth[node] + 1 > depth[nextNode]) depth[nextNode] = depth[node] + 1
263 +
                    if (--incoming[nextNode] == 0) queue[++tail] = nextNode
264 +
                }
265 +
            }
266 +
        }
267 +
268 +
        # Select siblings by subtree freshness and equal-tip preference.
269 +
        function orderSiblings(node,    k, c, tipKey, best, bestTip, bestRank, bestDelta, candidateTip, candidateRank, selected) {
270 +
            for (k = 1; k <= childCount[node]; k++) {
271 +
                c = child[node, k]
272 +
                tipKey = node SUBSEP tip[c]
273 +
                if (!(tipKey in groupRank) || freshest[c] < groupRank[tipKey]) {
274 +
                    groupRank[tipKey] = freshest[c]
275 +
                }
276 +
            }
277 +
            for (;;) {
278 +
                best = 0
279 +
                for (k = 1; k <= childCount[node]; k++) {
280 +
                    c = child[node, k]
281 +
                    if (c in selected) continue
282 +
                    candidateTip = tip[c]
283 +
                    candidateRank = groupRank[node, candidateTip]
284 +
                    if (best != 0) {
285 +
                        if (candidateRank > bestRank) continue
286 +
                        if (candidateRank == bestRank) {
287 +
                            if (candidateTip == bestTip) {
288 +
                                if (!preferred(c, best)) continue
289 +
                            } else if (c > best) {
290 +
                                continue
291 +
                            }
292 +
                        }
293 +
                    }
294 +
                    best = c
295 +
                    bestTip = candidateTip
296 +
                    bestRank = candidateRank
297 +
                    bestDelta = childDelta[node, k]
298 +
                }
299 +
                if (best == 0) break
300 +
                selected[best] = 1
301 +
                orderedCount[node]++
302 +
                ordered[node, orderedCount[node]] = best
303 +
                orderedDelta[node, orderedCount[node]] = bestDelta
304 +
            }
305 +
        }
306 +
307 +
        # Attach equal tips and immediate ancestors to their containing branches.
308 +
        function buildTree(    i, k, m, t, other, middle, immediate, node, tipCount, tips, canonical, contained, containedCount) {
309 +
            for (i = 1; i <= n; i++) {
310 +
                t = tip[i]
311 +
                if (t in canonical) {
312 +
                    if (preferred(i, canonical[t])) canonical[t] = i
313 +
                } else {
314 +
                    canonical[t] = i
315 +
                    tips[++tipCount] = t
316 +
                }
317 +
            }
318 +
            for (i = 1; i <= n; i++) {
319 +
                t = tip[i]
320 +
                if (i != canonical[t]) {
321 +
                    addChild(canonical[t], i, 0)
322 +
                    equal[i] = 1
323 +
                    hasParent[i] = 1
324 +
                    continue
325 +
                }
326 +
                containedCount = 0
327 +
                for (k = 1; k <= tipCount; k++) {
328 +
                    if ((t, tips[k]) in distance) contained[++containedCount] = tips[k]
329 +
                }
330 +
                for (k = 1; k <= containedCount; k++) {
331 +
                    other = contained[k]
332 +
                    immediate = 1
333 +
                    for (m = 1; m <= containedCount; m++) {
334 +
                        if ((contained[m], other) in distance) {
335 +
                            immediate = 0
336 +
                            break
337 +
                        }
338 +
                    }
339 +
                    if (immediate) {
340 +
                        node = canonical[other]
341 +
                        addChild(i, node, distance[t, other])
342 +
                        hasParent[node] = 1
343 +
                    }
344 +
                }
345 +
            }
346 +
            for (i = 1; i <= n; i++) {
347 +
                if (!(i in hasParent)) {
348 +
                    addChild(0, i, 0)
349 +
                    freshness(i)
350 +
                }
351 +
            }
352 +
            measureDepths()
353 +
            for (i = 0; i <= n; i++) orderSiblings(i)
354 +
        }
355 +
356 +
        # Measure uncolored text and display columns before printing any rows.
357 +
        function measureLayout(    i, k, width) {
358 +
            countWidth = 3
359 +
            dateWidth = 25
360 +
            ageWidth = 12
361 +
            hashWidth = 0
362 +
            branchWidth = 0
363 +
            for (i = 1; i <= n; i++) {
364 +
                if (length(date[i]) > dateWidth) dateWidth = length(date[i])
365 +
                if (length(age[i]) > ageWidth) ageWidth = length(age[i])
366 +
                if (length(hash[i]) > hashWidth) hashWidth = length(hash[i])
367 +
                if (length(ahead[i]) > countWidth) countWidth = length(ahead[i])
368 +
                if (length(behind[i]) > countWidth) countWidth = length(behind[i])
369 +
                width = columns[i]
370 +
                if (mode == "tree") {
371 +
                    width += 4 * depth[i]
372 +
                    if (i in equal) width += 2
373 +
                }
374 +
                if (width > branchWidth) branchWidth = width
375 +
            }
376 +
            if (mode == "tree") {
377 +
                for (i = 0; i <= n; i++) {
378 +
                    for (k = 1; k <= childCount[i]; k++) {
379 +
                        if (length(childDelta[i, k]) > countWidth) countWidth = length(childDelta[i, k])
380 +
                    }
381 +
                }
382 +
            }
383 +
        }
384 +
385 +
        # Return a run of spaces with the given length.
386 +
        function spaces(count,    text) {
387 +
            text = ""
388 +
            while (count-- > 0) text = text " "
389 +
            return text
390 +
        }
391 +
392 +
        # Apply terminal color to text.
393 +
        function paint(style, text) {
394 +
            if (color) return "\033[" style "m" text "\033[0m"
395 +
            return text
396 +
        }
397 +
398 +
        # Format a commit count with a gray arrow and a colored nonzero value.
399 +
        function formatCount(value, arrow, style) {
400 +
            if (value == 0) style = 90
401 +
            return spaces(countWidth - length(value)) paint("2;90", arrow) paint(style, value)
402 +
        }
403 +
404 +
        # Print update time, counts, hash, branch label, and upstream state.
405 +
        function printRow(i, prefix, labelDepth, plus, minus,    line, labelWidth, symbol, style) {
406 +
            labelWidth = columns[i]
407 +
            symbol = " "
408 +
            style = "1;36"
409 +
            if (marker[i] == 1) {
410 +
                symbol = currentSymbol
411 +
                style = "1;32"
412 +
            }
413 +
            line = paint("1;32", symbol) " "
414 +
            line = line paint(90, date[i] spaces(dateWidth - length(date[i]))) "  "
415 +
            line = line paint(90, age[i] spaces(ageWidth - length(age[i]))) " "
416 +
            line = line formatCount(plus, upArrow, 32) " "
417 +
            line = line formatCount(minus, downArrow, 31) "  "
418 +
            line = line paint("2;33", hash[i] spaces(hashWidth - length(hash[i]))) "  "
419 +
            if (labelDepth > 0) {
420 +
                line = line paint(90, prefix)
421 +
                labelWidth += 4 * labelDepth
422 +
            }
423 +
            line = line paint(style, name[i])
424 +
            if (mode == "tree" && (i in equal)) {
425 +
                line = line paint(33, " " equalSymbol)
426 +
                labelWidth += 2
427 +
            }
428 +
            if (tracking[i] != "-") {
429 +
                line = line spaces(branchWidth - labelWidth + 2) paint(90, tracking[i])
430 +
            }
431 +
            print line
432 +
        }
433 +
434 +
        # Print every immediate containment path in cached sibling order.
435 +
        function printTree(node, prefix, depth_,    k, c, connector, nextPrefix) {
436 +
            for (k = 1; k <= orderedCount[node]; k++) {
437 +
                c = ordered[node, k]
438 +
                if (k == orderedCount[node]) {
439 +
                    connector = lastConnector " "
440 +
                    nextPrefix = prefix "    "
441 +
                } else {
442 +
                    connector = otherConnector " "
443 +
                    nextPrefix = prefix pathSymbol "   "
444 +
                }
445 +
                if (node == 0) {
446 +
                    printRow(c, prefix connector, depth_, ahead[c], behind[c])
447 +
                } else {
448 +
                    printRow(c, prefix connector, depth_, 0, orderedDelta[node, k])
449 +
                }
450 +
                printTree(c, nextPrefix, depth_ + 1)
451 +
            }
452 +
        }
453 +
454 +
        # Format upstream state from the reference name and tracking counts.
455 +
        function formatTracking(upstream, track,    text, parts, k, plus, minus) {
456 +
            if (upstream == "") return "-"
457 +
            if (track == "gone") {
458 +
                text = upstream
459 +
                sub(/^refs\/remotes\//, "", text)
460 +
                return text " (gone)"
461 +
            }
462 +
            plus = 0
463 +
            minus = 0
464 +
            split(track, parts, ", ")
465 +
            for (k in parts) {
466 +
                if (parts[k] ~ /^ahead /) plus = substr(parts[k], 7)
467 +
                if (parts[k] ~ /^behind /) minus = substr(parts[k], 8)
468 +
            }
469 +
            text = upstream
470 +
            sub(/^refs\/heads\//, "", text)
471 +
            text = text " " upArrow plus " " downArrow minus
472 +
            sub(/^refs\/remotes\//, "", text)
473 +
            return text
474 +
        }
475 +
476 +
        FILENAME == widthFile {
477 +
            width[$1] = $2
478 +
            next
479 +
        }
480 +
        FILENAME == baseFile {
481 +
            split($2, counts, " ")
482 +
            baseAhead[$1] = counts[1]
483 +
            baseBehind[$1] = counts[2]
484 +
            next
485 +
        }
486 +
        FILENAME == sortedFile {
487 +
            n++
488 +
            name[n] = substr($4, 12)
489 +
            tip[n] = $5
490 +
            date[n] = $2
491 +
            age[n] = $3
492 +
            marker[n] = $4 == current
493 +
            ahead[n] = baseAhead[$4]
494 +
            behind[n] = baseBehind[$4]
495 +
            tracking[n] = formatTracking($6, $8)
496 +
            hash[n] = $7
497 +
            columns[n] = (name[n] in width) ? width[name[n]] : length(name[n])
498 +
            next
499 +
        }
500 +
        FILENAME == containmentFile {
501 +
            distance[$1, $2] = $3
502 +
        }
503 +
        END {
504 +
            if (mode == "list") {
505 +
                measureLayout()
506 +
                for (i = 1; i <= n; i++) printRow(i, "", 0, ahead[i], behind[i])
507 +
            } else {
508 +
                buildTree()
509 +
                measureLayout()
510 +
                printTree(0, "", 1)
511 +
            }
512 +
        }
513 +
    ' "$scratch/widths" "$scratch/base" "$scratch/sorted" "$scratch/containment"
514 +
}
515 +
516 +
parseOptions "$@"
517 +
git rev-parse --git-dir > /dev/null
518 +
scratch=$(mktemp -d "${TMPDIR:-/tmp}/git-branches.XXXXXXXX")
519 +
trap 'rm -rf "$scratch"' 0
520 +
trap 'exit 129' HUP
521 +
trap 'exit 130' INT
522 +
trap 'exit 143' TERM
523 +
tab=$(printf '\t')
524 +
525 +
readReferences
526 +
selectDefault
527 +
readUpdates
528 +
selectBase
529 +
readBaseCounts
530 +
readWidths
531 +
: > "$scratch/containment"
532 +
if [ "$mode" = tree ]; then
533 +
    readContainment
534 +
fi
535 +
render