将分离的 HEAD 重置为 BRANCH 应该做什么?

What should RESETING detached HEAD to BRANCH do?

如果我没理解错的话,当你有一个独立的 head(HEAD->commit)时, 然后 git CHECKOUT 分支解决了问题(HEAD->branch[->someCommit])

但是重置到分支有什么用呢?它应该设置 HEAD 指向另一个分支的对象(通常是分支)的指针。 但是因为我们没有这个中间人(分支机构)——那它有什么作用呢?为什么?

它只是移动 HEAD:正如我在“Practical uses of git reset --soft?”中提到的:

git reset is all about moving HEAD.

如果将 HEAD 移至另一个提交,则 HEAD 将保持 detached

a discussion about the difference between git reset and git checkout vs the detached or attached nature of the symbolic reference HEAD 之后,这里是我们一起发现的:

  • 如果 HEAD 指向分支,git reset 也会将分支移动到 <something>:重置它不会使其取消分离,它会更改分支 HEAD
  • 如果 HEAD 指向提交(已经分离),那么它将保持分离:正如 OP 所说:

so when detached and I call git reset <branch> it finds the commit behind the branch and change the commit in .git/HEAD for the commit that <branch> refers to.

让我们考虑一个附加到 branch1 的 HEAD(cat .git/HEAD 会 return branch1):

  • git checkout branch2 会将 HEAD 更改为 branch2 并保持 branch1 不变
  • git reset branch2 会将 branch1 HEAD 重置为 branch2cat .git/refs/heads/branch1 将包含与 branch2.
  • 相同的 SHA1

这就是区别:

  • reset 移动 HEAD(正如我一开始所说的:就是移动 HEAD)
  • 结帐切换分支(或分离 HEAD)

关于 HEAD 的 attached/detached 性质:

  • 重置不会改变 HEAD 的性质(如果它被附加,它仍然附加)
  • 检出可以改变 HEAD 的性质(如果它被附加并且你检出一个提交而不是一个分支,HEAD 变得分离)