bytama

ยท 1 min read

Normalize CRLF to LF in a Git repository

Turn off autocrlf, rebuild the index, and keep the working tree unchanged.

A repository that was committed from Windows can end up with CRLF line endings in the history. Editors and linters then disagree with each other, and every diff looks like the whole file changed.

The recipe

git config core.autocrlf false
git rm --cached -r .      # the dot matters
git reset --hard

git rm --cached -r . empties the index without touching the working tree. git reset --hard then repopulates it from the checked-out files, this time applying the new core.autocrlf=false setting. The working tree itself is restored to what you had.

Finish with a commit

git add -A
git commit -m "Normalize line endings to LF"

The commit is the point: the blobs now contain LF, and clones get LF regardless of the platform.

Before you run it

git reset --hard discards uncommitted changes. Commit or stash first, and check that the working tree is clean:

git status --short

If the repository should never contain CRLF, make it a rule instead of a cleanup โ€” a .gitattributes file does that without anyone remembering:

* text=auto eol=lf