Question

I'd like to sort the output of git status --short --branch, so that:

  • Files in the index appear at the bottom
  • Files modified in the working tree but not in the index appear above that
  • Untracked changes at the top

If this requires piping to some other command to sort the lines in the output, it would be nice for it to retain output coloring configured by Git.

Is there some clever alias I can create that will do this for me? Note I'm using Git on Windows (if that matters).

Was it helpful?

Solution

You can tell git to generate colour codes, but to sort in a custom order you will have to script a bit. Here's a short python example that you can pipe from git -c color.ui=always status --short --branch:

#!/bin/env python

import sys, re

# custom sorting order defined here:
order = { 'A ' : 1, ' M' : 3, '??' : 2, '##' : 0 }

ansi_re = re.compile(r'\x1b[^m]*m')

print ''.join(sorted(
    sys.stdin.readlines(),
    cmp=lambda x,y: cmp(
        order.get(ansi_re.sub('', x)[0:2],0),
        order.get(ansi_re.sub('', y)[0:2],0))))

Or a one-liner abomination:

git -c color.ui=always status --short --branch | python -c 'import sys, re; \
  order = {"A ":1," M":3,"??":2,"##":0}; ansi_re = re.compile(r"\x1b[^m]*m");\
  print "".join(sorted(sys.stdin.readlines(),cmp=lambda x,y: \
  cmp(order.get(ansi_re.sub("", x)[0:2],0), order.get(ansi_re.sub("", y)[0:2],0))))'

Short explanation.

The python script reads the stdin, which is the coloured listing output of git status, and after stripping the ANSI colour codes, compares the first two status characters with respect to the custom priority for each status defined in a dictionary.

The ANSI colour code removals are based: on How can I remove the ANSI escape sequences from a string in python

And the full list of the different status codes can be found at the git status help page.

OTHER TIPS

tail -r can be used to reverse the output of git status, though it won't preserve color, and apparently on Linux there is no -r option, so you have to use tac instead:

git status --short --branch | tail -r

There are other reverse tricks in question I linked to, so it might be worth checking out other options too (to get the color output).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top