Let Git manage your indentation

Indentation in Ruby source code files is two spaces. It’s the rule.

I’m not much for two space indentation; it just feels cramped to me. That might change over time but for now that’s just the way it is. What that means for me is that it’s really hard to contribute to someone else’s Ruby project since my Vim config specifies four space indentation for everything. I could change my Vim config to use two spaces for .rb files but I figured I could have my cake and eat it too, aka let Git worry about it.

Git has the ability to use filters for various operations. Here’s an in depth guide, but I’m just going to cut to the chase and show how I made it work.

In your working tree, edit the file “.git/info/attributes” (create it if it doesn’t exist) to look like this:

These lines define the file extension(s) to which the filter applies, then specifies which filter to use. The filter name ‘two_four’ is just a descriptive filter name I picked.

Now we need to define the actions for our filter which should do nothing more than accept standard input, modify it as needed, and spit it back out on standard output. There are ‘git config’ commands you can use to enter the filter actions into your git configuration but in my case it’s easier to enter them directly into ~/.gitconfig than try to escape everything for the bash shell. Here’s the appropriate section:

That perl code-puke in there just looks for spaces at the beginning of the line and either doubles them or halves them depending on which direction we’re going. The “smudge” action says “Run this filter code just after checking the files out into my working tree”, whereas the “clean” action says “Run this filter code just before pushing the files to another repository”.

If you want to immediately see the difference in your working tree you can force all files to be checked out again by running:

git checkout HEAD -- **

Just make sure you commit all your work first!

**Disclaimer: I’ve only minimally tested this filter code. Use it at your own risk!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: