2023-04-02 05:00:03

Git中的HEAD是什么?

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

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

但Git HEAD到底是什么?


当前回答

作为一个概念,头是分支中的最新修订。如果每个命名分支有多个头,那么在进行本地提交时可能会创建它,而没有合并,这实际上创建了一个未命名的分支。

为了拥有一个“干净的”存储库,每个命名分支都应该有一个头,并且在本地工作后总是合并到一个命名分支。

Mercurial也是如此。

其他回答

引用别人的话:

A head is simply a reference to a commit object. Each head has a name (branch name or tag name, etc). By default, there is a head in every repository called master. A repository can contain any number of heads. At any given time, one head is selected as the “current head.” This head is aliased to HEAD, always in capitals". Note this difference: a “head” (lowercase) refers to any one of the named heads in the repository; “HEAD” (uppercase) refers exclusively to the currently active head. This distinction is used frequently in Git documentation.

可以在这里找到另一个很好的源代码,它可以快速覆盖git的内部工作原理(因此可以更好地理解heads/HEAD)。引用(ref:)或头或分支可以被看作是粘贴在提交历史记录中的提交上的便利贴。通常它们指向一系列提交的提示,但它们可以随着git checkout或git reset等移动。

这两个可能会让你困惑:

head

指向分支最近提交的命名引用。除非使用包引用,否则头文件通常存储在$ GIT_DIR/refs/heads/中。

HEAD

当前分支,或者您的工作树通常是从HEAD所指向的树生成的。HEAD必须指向一个头,除非你正在使用一个独立的头。

HEAD几乎字面上就是分支的头。所以当你观察一个分支时,你看到的是最新的提交,也就是这个分支的头。但是,您可以将自己指向该分支历史上更远的另一个提交,当您这样做时,您是在将HEAD移动到前一个提交。由于HEAD自然属于分支中的最新提交,因此它被认为是分离的。

视觉表现。每一根树枝都是一条毛毛虫,每一根树枝都是这个生物的一个部分。因此HEAD将位于最前面的段中。如果您将HEAD从该部分移除到另一个要使用的节段,则您已经将HEAD从自然节段中分离出来。希望你能明白。

现在如果你在主分支中分离HEAD,然后签出newFeature,然后再次签出main, HEAD仍然会被分离,并且是在另一个提交之上。我把HEAD看作一面镜子,你可以把它指向你想要的地方。

我还在弄清楚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文件是一种跟踪最新提交的方便方法,而不是记住长散列值。

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.