:::: MENU ::::

Customise your .gitattributes to become a Git Ninja

One of the things I love about Git is that your .gitignore file travels with the repo, so ignore rules remain consistent no matter which machine you are working on.

In the same vein, adding a .gitattributes to your repo allows you to ensure consistent git settings across machine.  This enables the following subtle, but very useful features.

  1. Force line ending normalization inside your repo to LF
    Adding * text=auto causes Git to autodetect text files and normalise their line endings to LF when they are checked into your repository. This means that simple diff tools (I’m looking at you Github) that consider every line to have changed when someone’s editor changes the ending won’t get confused.
    Importantly, this doesn’t affect the line endings in your working copy. By default Git will convert these to your platform’s default when checking code out of your repo. You can override this using the core.eol setting.
  2. Language specific diffs
    When git shows you diff information it gives you some context as to where in the code the diff lives. Using the *.cs diff=csharp setting tells Git to be a little smarter about tailoring this for a specific language. Notice how in the example below Git is telling us the method name where the change occured for th .cs file, compared to the default first non comment line in the file.
  3. Normalize tabs vs spaces
    The filter= attribute instructs Git to run files through an external command when pulling them from / to the repo. One use of this functionality would be to normalise tabs to spaces (or visa versa).
  4. Encrypting sensitive information
    It is convenient to store config files in your git repo, but for public repo’s you don’t really want to expose things like your production db credentials. Using Git filters you could pass these config files through an encryption/decryption step when checking in/out of the repository. On machines that have the encryption keys your config files will be placed in plaintext in your working copy; everywhere else they will remain encrypted.
  5. Useful defaults
    If you use the GitHub Git clients, they add useful default settings. Further, the github/gitignore and Danimoth/gitattributes projects contain some useful defaults.

The more I use Git, the more I realise what a powerful tool it is. And I haven’t even touched on how you can use Git hooks for advanced Git Ninja moves…


One Comment

So, what do you think ?