Why won't “git reset HEAD” undo my uncommitted, unstaged changes?

后端 未结 6 1507
失恋的感觉
失恋的感觉 2021-02-05 09:30

I\'ve previously been able to undo changes through SourceTree by performing the \"Discard\" function, which under the hood produces this command:

git -c diff.mne         


        
6条回答
  •  天涯浪人
    2021-02-05 09:38

    I suspect that you had files saved with CRLF line endings in your repository, and then somewhere along the way your configuration was changed so that git started normalizing end-of-line characters (either core.autocrlf was set to true, or the .gitAttributes file was added or changed). When I ran into this problem, it turned out that a .gitAttributes file that contained * text=auto had been added to my repo.

    (EOL normalization means that git will write the end-of-line characters as LF in its database, regardless of what you use in your working copy).

    Git doesn't automatically check your files to see if they require EOL normalization after you enable it. You have to explicitly tell it to check all of your files, or else you end up in this situation: the files in your repository still have CRLF line endings, and git will only notice that it should normalize them when it touches each file. So the next time you commit some changes to a file, git will write the file to its database with LF line endings.

    The problem occurs when git touches the file through a read operation. Say you make changes to a file that has CRLF line endings and then try to discard your changes. Git will read the clean copy from its database, see that it has CRLF line endings, and then mark the file as modified. The file has not actually been modified, but git is saying that it wants to write a change to the EOL characters to its database. This happens every time you attempt to discard your changes, check out that file, or even do a hard reset. That is why it seems to be impossible to undo those modifications.

    You should have git normalize the line endings on all of your text files, so this problem doesn't continue to pop up (see https://stackoverflow.com/a/4683783/1369 for instructions on how to do that). If it's possible, you might even want to modify your history so the line endings are normalized at the same time the .gitAttributes settings were changed.

    If you cannot modify your history, then you may run into situations where you need to check out old versions of your files that still have the CRLF line endings. You will probably get stuck with a list of modified files that you cannot discard and don't want to commit. In that case, you can use this work-around to essentially make git forget that it wants to modify those files:

    1. Check out the old version
    2. Turn off end-of-line normalization
    3. git reset
    4. Re-enable end-of-line normalization

提交回复
热议问题