The problem: unexpected unstaged changes after a revert
Recently, when using the GIT command-line to switch to an existing user branch, the checkout failed due to some local changes in the current workspace. In this case, git suggests to commit or to stash the local changes.
Since I was not interested in the local changes, I decided to revert these files to the last commit (HEAD). The revert process succeeded 😊.
Surprisingly, when trying to checkout the new user branch, the same files were shown as unstaged.
Initially, I tried reverting again the changes to the last commit. Instead of git revert, I used the following command:
git reset --hard HEAD
Unfortunately, it did not work. 🙁
Indeed, when running the command:
the same files were shown again as unstaged.
I immediately realized that Git was not reverting the CRLF/LF characters at the end of the lines of the relevant files. These characters were ignored during the revert process.
This was pretty evident because when running the git command:
the whole content of these files was shown.
In order to solve this issue, I found a workaround solution:
git checkout --force mySuperUserBranch
When switching branches using the “–force” option, then the checkout proceeds even if the index or the working tree differs from HEAD. In this way, all local changes are thrown away.
Nevertheless, it is clear that this issue depends on some settings of the .gitattributes file.
The .gitattributes file allows you to specify the files and paths attributes that should be used by git when performing any git action. In this file, the user can his own configuration. For example, we can specify which characters should be used at the end of the lines, i.e., CRLF or LF.
Therefore, in order to solve this issue, an easy fix is provided by the following sequence of operations:
git rm .gitattributes git add -A git reset --hard
After getting the correct version of the .gitattributes file, it is possible to execute all those git commands that require no local changes (e.g., a git checkout or pull operation).