Strange git case - git stash followed by git stash apply lost uncommitted data?

梦想的初衷 提交于 2019-12-05 07:55:54

The problem here is mostly a misunderstanding of what git stash save does. It saves only changes to tracked files. Untracked files are not saved by git stash. When you moved file.txt to file1.txt, the new file.txt is an untracked file and will not be saved by git stash. This isn't a bug, it's just the way that git stash behaves. It could be that the documentation for git stash should be more clear about this.

As the documentation for git stash save states, it will do a git reset --hard after saving your changes. It was the git reset --hard that overwrote the new file.txt. One might argue that git reset --hard should generate a warning if an untracked file will be overwritten, but I still wouldn't call this a bug. It's doing what it's supposed to do.

The important thing to understand here -- and what would have saved you a lot of trouble -- is that git stash save does not save untracked files (and it probably shouldn't).

This looks like serious (i.e. data loss) bug in stash. Please report it. Unfortunately, I don't believe that there's any way to get the new file.txt back.

This bug has now been fixed in git >=1.7.1.1.

for the future, use git stash -u to stash uncommitted files (http://www.kernel.org/pub/software/scm/git/docs/git-stash.html) You can do this starting from git version 1.7 i believe.

This is post is to simply illustrate the recreation process without getting crammed into a comment. Note: Using Git version 1.7.0.2

To recreate:

~/test $ git init
~/test $ echo "hello" > file.txt
~/test $ git add .
~/test $ git commit -m "init commit"

~/test $ git mv file.txt file1.txt
~/test $ echo "new data" > file.txt
~/test $ git stash
~/test $ git stash apply

~/test $ cat file.txt
cat: file.txt: No such file or directory

~/test $ cat file1.txt
hello
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!