Skip to content

Instantly share code, notes, and snippets.

@ian-h-chamberlain
Last active February 27, 2025 05:16
Show Gist options
  • Save ian-h-chamberlain/05bbd39fc35b856307ac168febcfa92a to your computer and use it in GitHub Desktop.
Save ian-h-chamberlain/05bbd39fc35b856307ac168febcfa92a to your computer and use it in GitHub Desktop.
custom sorting git branches
[alias]
# this is gnarly but it's based on the hardcoded upstream default:
# https://github.com/git/git/blob/08bdfd453584e489d5a551aecbdcb77584e1b958/builtin/branch.c#L386
# The idea is to add a field for commit date and another for a "known prefix", which sort -k can use
# I wodner if this is worth breaking out into its own helper script (git-br) instead
br = "git branch --color --format '%(committerdate:unix)'\t'%(if:equals=refs/heads/test)%(refname:rstrip=-3)%(then)1%(else)0%(end)'\t'%(HEAD) %(if)%(HEAD)%(then)%(color:green)%(else)%(color:normal)%(end)%(refname:short)' | sort -r -n -k 2 -k 1 | cut -d \t -f3"
#!/usr/bin/env bash
MY_PREFIX="test"
MINE="%(if:equals=refs/heads/${MY_PREFIX})%(refname:rstrip=-3)%(then)1%(else)0%(end)"
TAB=$'\t'
DATE='%(committerdate:unix)'
# Based on https://github.com/git/git/blob/08bdfd453584e489d5a551aecbdcb77584e1b958/builtin/branch.c#L386
HEAD_PREFIX='*%(color:green)'
WORKTREE_PREFIX='+%(color:cyan)'
# Unclear why %(color:normal) doesn't behave the same as the RGB color here, or why
# this is set to some white color at all (since normal is green in my iTerm settings)
WORKTREE="%(if)%(worktreepath)%(then)${WORKTREE_PREFIX}%(else) %(color:#F8F8F2)%(end)"
PREFIX="%(if)%(HEAD)%(then)${HEAD_PREFIX}%(else)${WORKTREE}%(end)"
FORMAT='%(refname:lstrip=2)%(color:reset)%(if)%(symref)%(then) -> %(symref:short)%(end)'
git branch --color --format "${DATE}${TAB}${MINE}${TAB}${PREFIX} ${FORMAT}" | sort -r -n -k2 -k1 | cut -d"$TAB" -f3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment