开发者

git checkout HEAD~2 (example) deletes untracked files if they were added with last commit

I add new files (which were present before as untracked files) and commit them. When I checkout to before this commit, these files are deleted. They should not.

It does not matter whether .gitignore lists these files or not (whi开发者_开发知识库ch requires to do git add -f ...).


They should not [be deleted].

Yes, they should. Commits are historical states. You're checking out a state before they were committed, so they should not be there. Just imagine working on your project a year from now. Half the files have been renamed, there are dozens of new files, and for whatever reason you decide to check out today's version. Surely you wouldn't want all those dozens of files to just sit around and clutter it up! They don't belong there! (And of course "untracked files...added with last commit" doesn't make any sense - if you committed them, they're now tracked.)

If the files really should have been in the old commit, likely what you want to do is use an interactive rebase (git rebase -i <start commit> <branch>, further instructions provided by git)to squash a couple commits together. Perhaps you'll need to reorder the commits too, pushing the "add these files" commit back farther in the history where it belongs. Or, if you notice this right after you forget to add the files, simply add them and use commit --amend to amend to the previous commit instead of creating a separate one.

Finally, if you really do get this set in the history this way (others have pulled so you don't want to rebase/amend), you can check out the old commit, and then check out the files from the newer commit:

git checkout <old-commit>
git checkout <new-commit> file1 file2 dir1 dir2/file3 ...


Just checkout HEAD again and you get those files back. Git checkout HEAD~2 reverts the directory of your repository back to the tracked status you had two commits ago. This is totally expected behaviour.


Possible solution when the last commit only contains the file additions:

$ git diff HEAD^ >diff
$ git checkout HEAD^
$ git apply diff

At this time the branch is detached and contains the formerly untracked files. From now on, further checkouts in commit history are possible, and consistent.


You might like git commit --amend to tack on stuff to the previous commit that you forgot.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜