hardscrabble 🍫

Psst. Check out my RubyConf 2017 talk, There are no rules in Ruby.

git repl

30 Nov 2014

The other day I mentioned coming upon a neat set of git extensions called ‘git extras’ by TJ Holowaychuk. Since then I’ve become slightly obsessed with it. It’s so useful, including as a terrific learning tool. Take ‘git repl’ as an example.

First of all, what is it?

allow me to answer with a GIF:

vim auto indent gif

In short: if you’re gonna be doing a bunch of git operations in a row, why keep typing git over and over when you can go into a git repl and just let it assume that everything you’re doing is going to be a git command?

It plays well with vim, too – the commit message editor seamlessly pops into vim and then back into the git repl on quit.

So how does it work? I looked at it and assumed that it must be so much code and way beyond my understanding. But that’s totally wrong! It’s just 43 lines of bash and it’s fairly readable.

The really interesting part is read, which has a comment indicating that it’s powered by Readline, which is one of those words that I’ve seen fly around while existing in the world of software, but have never heard defined. Well, here’s the wikipedia page for it: GNU Readline. It was originally written by Brian Fox, who also created bash. Ruby’s various REPLs (eg rails console, irb, pry) are probably using it under the hood via Ruby’s standard Readline library, which makes writing a REPL super simple, while maintaining the behaviors you may be used to. For example, I compulsively press control+l to clear the screen; this works in a readline REPL but not in something like this:

loop do
  print "> "
  input = gets.chomp
  puts input
end

Filename tab completion works as well! Whoa!

Here’s my first readline program, inspired by the git repl code:

function extensions {
  read -e -r -p "find files with extension: " extension
  find . -name "*.$extension"
}

Try pasting that into your terminal then entering extensions to run it and to explore your projects. It should prompt you for a file extension (try entering rb in a Ruby project, for example) and then spit out the list of files with that extension in the current directory (and its subdirectories).

Not a particularly great program! I’m mostly just happy to see how simple and demonstrative the git extras code was.