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

◇◆丶佛笑我妖孽 提交于 2019-12-22 06:09:43

问题


I have a file, let's say file.txt I have done git mv file.txt to file1.txt, then I created a new file called file.txt and worked on it. Unfortunately I didn't add that file to git yet. Anyway the problem is that I did git stash, then git stash apply, but the new file.txt disappeared... anyway to get it back?


回答1:


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).




回答2:


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.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/2613956/strange-git-case-git-stash-followed-by-git-stash-apply-lost-uncommitted-data

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