如何理解git中的HEAD和branch?

在git中HEAD和branch是两个特殊的引用,它们都指向commit。而且一般情况下,是HEAD指向branch然后再指向commit,但是当HEAD处于游离状态时它就不再指向branch而是直接指向commit,所以说HEAD是指向活跃分支的游标这句话似乎不太准确,而是指向当前的commit。

关于branch,本质是指向commit的引用,这里的commit是单个的commit,当有新的commit提交时,branch会移动到新的commit。但是我们在分支上会提交很多的commit,然后再进行合并的时候是将分支的所有commits合并过去,这样的话是否可以将branch理解成一个commit串,它代表了所有提交的commit,在进行合并的时候本质合并的就是commit串,这样看似是合理的,但是它和“branch的本质是指向commit的引用”这句定义不太相符,这句话在我的理解中就是branch只指向单个commit。

还请各路大神帮助我理解一下,谢谢!!

阅读 5.4k
2 个回答

branch只指向单个commit这个理解是对的。

之所以你的理解是将branch理解成一个commit串,是因为git存储这些commit是一个树结构,用来描述他们的先后关系

用代码来解释一下:

function Branch(name, commit) {
    this.name = name;
    this.commit = commit;
}

function Git(name) {
    this.name = name; // Repo name
    this.lastCommitId = -1; // Keep track of last commit id.
    this.HEAD = null; // Reference to last Commit.

    var master = new Branch('master', null); // null is passed as we don't have any commit yet.
        this.HEAD = master;
}

Git.prototype.commit = function (message) {
    // Increment last commit id and pass into new commit.
    var commit = new Commit(++this.lastCommitId, this.HEAD.commit, message);

    // Update the current branch pointer to new commit.
    this.HEAD.commit = commit;

    return commit;
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进