Git Branch Name Completion in Zsh

| | Comments (0)

Speaking of git esoterica (and my Git Fundamentals talk), one of the questions during Part 1 was “what about the new switch and restore commands?”

The … uh … what now? So I did a quick search and, lo and behold, they were added late last year in version 2.23. The goal is help new users confused about the two most common uses of git checkout: switching branches and restoring files from the index, which admittedly have nothing to do with one-another, why are they managed by the same command?[*]

I see this as a definite positive development, and I wanted practice with them, so I could promote using them when I’m teaching folks, because I’m sure it will reduce confusion and improve velocity. I knew I had to go cold-turkey, so I deleted my git co alias and added a git sw alias to replace it.

It worked well enough, though I am still overcoming years of ossified motor-memory. But there was one glaring omission: my shell stopped tab-completing branch names. A minor annoyance, to be sure. But I didn’t realize how much I used it until it was gone. So I eventually went digging, and discovered this patch that added these commands (and a few other updates for 2.23) to zsh’s git completion.

I was not looking forward to trying to apply a patch across versions when I stumbled upon items in the base _git file that reminded me that zsh completion is handled via autoloaded functions. 💡 I might be able to extract them into files in my own autoload directory, and then I don’t have to muck with applying the patch at all!

Long story short(er), it works perfectly! You can drop these files into any directory in your zsh $fpath and if you open a new shell[**], git restore will tab complete command-line arguments and file names in the index / staging area, and git switch (or any aliased you’ve added to it) will complete its command-line arguments and branch names. Huzzah!


[*] Fun fact: in the very early days of git they were different commands, git checkout only switched branches, git checkout-index was how you restored files. But there was a clamor to make things “easier,” and the user experience never recovered. I see the new names as a huge step forward.

[**] Or run autoload -U _git-switch && autoload -U _git-restore in a shell you do not want to close.

Leave a comment

About this Entry

This page contains a single entry by Erik Ogan published on June 21, 2020 3:44 PM.

Introducing reinstate-revert-revert was the previous entry in this blog.

Find recent entries on the main index or look in the archives to find all entries.

June 2020

Sun Mon Tue Wed Thu Fri Sat
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30        
Powered by Movable Type 5.04