2023-04-02 05:00:03

Git中的HEAD是什么?

您可以看到Git文档中这样说

分支必须在HEAD中完全合并。

但Git HEAD到底是什么?


当前回答

要把正确答案中的要点讲清楚,一个很好的方法就是跑步 git reflog HEAD,你会得到HEAD所指向的所有地方的历史。

其他回答

一个存储库中可以有多个头。并且头的总数总是等于存储库中存在的分支的总数,这意味着头只是每个分支的最新提交

但是一个存储库只有一个HEAD。HEAD是一个引用,它引用在当前分支完成的最新提交。

它就像git用户的眼睛。无论HEAD引用哪个提交,存储库都开始反映该特定提交期间存储库的条件。

HEAD的基本性质是总是引用当前分支的最新提交,但我们可以通过使用git checkout "commit-hash"将HEAD移动到当前分支的任何提交。

注意:我们可以使用git log——oneline命令轻松获得commit-hash

HEAD只是一个特殊的指针,它指向您当前所在的本地分支。

从Pro Git书籍3.1章Git分支-果壳中的分支,在部分创建一个新的分支:

What happens if you create a new branch? Well, doing so creates a new pointer for you to move around. Let’s say you create a new branch called testing. You do this with the git branch command: $ git branch testing This creates a new pointer at the same commit you’re currently on How does Git know what branch you’re currently on? It keeps a special pointer called HEAD. Note that this is a lot different than the concept of HEAD in other VCSs you may be used to, such as Subversion or CVS. In Git, this is a pointer to the local branch you’re currently on. In this case, you’re still on master. The git branch command only created a new branch — it didn’t switch to that branch.

我还在弄清楚git的内部结构,到目前为止,我已经弄清楚了这个:

假设当前的分支是master。

HEAD是你的.git/目录下的一个文件,通常看起来像这样:

% cat .git/HEAD
ref: refs/heads/master

Refs /heads/master本身是一个文件,通常包含master最新提交的哈希值:

% cat .git/refs/heads/master 
f342e66eb1158247a98d74152a1b91543ece31b4

如果你做git日志,你会看到这是master的最新提交:

% git log --oneline 
f342e66 (HEAD -> master,...) latest commit
fa99692 parent of latest commit

所以我的想法是HEAD文件是一种跟踪最新提交的方便方法,而不是记住长散列值。

在阅读了之前所有的答案后,我仍然想要更清楚。git官方网站http://git-scm.com/blog上的这个博客给了我想要的东西:

HEAD:指向最后一次提交快照的指针

Git中的HEAD是指向当前分支引用的指针,而当前分支引用又是指向您所做的最后一次提交或检出到工作目录的最后一次提交的指针。这也意味着它将是你下一次提交的父节点。通常最简单的想法是,HEAD是上次提交的快照。

感觉HEAD只是您签出的最后一次提交的标记。

这可以是一个特定分支的顶端(例如“master”),也可以是某个分支的中间提交(“detached head”)。