我对git checkout <commit>
的理解是,git会将我的工作目录恢复到之前提交时所处的状态。但这根本不是发生的事情。例如:
rwilson@855:~/jt$ cat > x.x
1st line
rwilson@855:~/jt$ git add x.x
rwilson@855:~/jt$ git commit -m "Initial commit"
[master (root-commit) f5df7c2] Initial commit
1 file changed, 1 insertion(+)
create mode 100644 x.x
rwilson@855:~/jt$ cat >> x.x
2nd line
rwilson@855:~/jt$ git log --oneline
f5df7c2 Initial commit
rwilson@855:~/jt$ # I want to go back to old version of x.x now
rwilson@855:~/jt$ git checkout f5df7c2
M x.x
Note: checking out 'f5df7c2'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at f5df7c2... Initial commit
rwilson@855:~/jt$ cat x.x
1st line
2nd line
所以我的问题是(1)我如何要求git
将我的工作目录置于初始提交后的完全相同的状态? (2)为什么git
允许我回到旧的提交但保持本地更改?谁会想要这些旧文件(来自旧提交)和新的非分段更改的混合?似乎非常反直觉。
答案 0 :(得分:1)
您当前的修改(向x.x
添加一行)不会保存在任何地方,也不会与提交f5df7c2不兼容。
因此,git允许您在不删除当前工作树修改的情况下浏览历史记录。两种可能性:
git stash
暂停您的修改(您可以稍后使用git stack pop
git checkout .
完全删除您的修改。使用此命令,您确定您拥有当前提交中的文件(除非您有暂存文件)答案 1 :(得分:1)
这是因为你没有承诺或隐藏它们。因此,您可以转到之前的提交。
您可以在检出先前提交或git stash
之前向文件添加其他行时git commit
更改,以便在检出先前提交时看到以前版本的文件