gitrecipes: the Git cookbook

Line endings

When Windows/Linux/OS X developers work together, things can get a bit tricky, because Windows uses a different encoding for line endings (CRLF) than Unix-flavoured systems do (LF). So, depending on the editor(s) you use, you will usually start to aggregate a weird mix of different line endings and troublesome merges whenever someone changes them around. This is clearly not an awesome thing to have to deal with.

The traditional solution

Before git 1.7.2, you could use the core.autocrlf setting (and a few related ones) to fix files, but with a chance of some files getting broken (because git has to apply heuristics in order to tell text files from binary files)... so I'm not going to talk about that solution.

The current best solution

git 1.7.2 introduced the core.eol setting and automatic conversion of files that are marked as text files in .gitattributes. Msysgit, the recommended Windows port of git, automatically has core.eol set to the right value for standard Windows tool. So, typically all that's left is creating a proper .gitattributes file (which you can then add to the repository so that everything works correctly for everyone by default). Here's an example:

*.c text
/foo/bar/hello text

That's all there is to it. From now on, files will automatically be checked out with your system's native encoding for line endings, and new commits will contain a normalized version (LF encoding).

Loose ends: old, broken files

If you already have files with CRLF encoding in your repository, you'll find that sooner or later someone will commit changes to it and then all line endings will be converted to LF in the repository.

If you had files with incorrect line endings in your working tree before you created a proper .gitattributes files, you can either throw away all uncommitted changes using git reset --hard or use a separate tool (perhaps your editor) to convert the line endings to your system's native format. Some editors do this automatically.

A word about Cygwin

Cygwin pretends to be a Unix environment, so its version of git will use LF line encodings. Don't use Windowsy editors together with Cygwin and line ending normalization... or, if you do, be sure to set core.eol to crlf.

This article was written by Jan Krüger. See history of changes.