May 29, 2014

Git, line endings, and the .gitattributes file

While trying to solve a problem with block literals in YAML files, I discovered that Git may convert line endings when text files are committed into the repo or when they are checked out into the working directory.

Specifically, on my Windows system, by default Git converts the Windows CR-LF endings to Unix-style LF when committing code, and it converts the other way when code is checked out. Besides suspecting that this was causing the problem I was trying to fix, I also found it unsettling that code I was creating was being altered.

My initial solution was to add a .gitattributes file to the root directory of the Optimizely module, which is where I had initialized Git. This file simply contained one line:

*  text  eol=LF

The asterisk is a file wildcard. The line means all files (that Git thinks are textual) are to be treated as text and their line endings are to be LF only.

A .gitattributes file applies to the Git repo for all users. It eliminates the problem of different users possibly having different Git settings.

Later, I found that Drupal 8 core ships with a standard .gitattributes and used that instead. Rather than the overly broad wildcard that I used, the Drupal 8 version carefully lists all the file extensions that should be treated as text as well as those that should be treated as binary. Text files are specified to have LF line endings. You can access the file at the url mentioned below.

N.B. I'm using a text editor, Sublime Text 2, that can render all three kinds of line endings and can readily convert the line endings in a file from one kind to another. So editor limitations are not a consideration for me,

Sources:

Line endings for Drupal in git
http://ithomas.name/2013/line-endings-for-drupal-in-git/
A very brief mention of using .gitattributes files.

Core ships with a .gitattributes file to improve git patches, October 2012
https://drupal.org/node/1803766

The Drupal 8 core .gitattributes file
http://cgit.drupalcode.org/drupal/plain/.gitattributes?id=refs/heads/8.x

Mind the End of Your Line, March 2012
http://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/
This is an excellent, detailed description of managing line endings in Git.

No comments:

Post a Comment