git - git checkout 是如何实现的?

标签 git implementation

当运行 git checkout 时,旧的 HEAD 和新的 HEAD 的 merge 库可以任意远。天真的实现是线性应用每个差异,但操作会立即运行。

我有一种预感,它可能会通过某种用于中间差异缓存的跳过列表来实现,但这只是一个猜测。

有人知道它是如何实现的吗?谢谢! :)

最佳答案

关于如何(原则上)在 javascript implementation of Git (as an exercise) Gitlet 中实现 checkout ,您有一个很好的例子作者:Mary Rose Cook

参见 annotated source code

对于 checkout ,步骤是:

  • checkout() changes the index, working copy and HEAD to reflect the content of ref.
    ref might be a branch name or a commit hash.
  • Get the hash of the commit to check out.
  • Abort if ref cannot be found.
  • Abort if the hash to check out points to an object that is a not a commit.
  • Abort if ref is the name of the branch currently checked out. Abort if head is detached, ref is a commit hash and HEAD is pointing at that hash.
  • Get a list of files changed in the working copy.
    Get a list of the files that are different in the head commit and the commit to check out.
    If any files appear in both lists then abort.
  • Otherwise, perform the checkout.
  • If the ref is in the objects directory, it must be a hash and so this checkout is detaching the head.
  • Get the list of differences between the current commit and the commit to check out. Write them to the working copy.
  • Write the commit being checked out to HEAD.
    If the head is being detached, the commit hash is written directly to the HEAD file.
    If the head is not being detached, the branch being checked out is written to HEAD.
  • Set the index to the contents of the commit being checked out.
  • Report the result of the checkout.

同样,它是一种简化(与实际的 Git 代码相比),但提供了一个关于 checkout 应该如何工作的好主意。

更多可以收听GitMinutes #31: Mary Rose Cook on Gitlet Thomas Ferris Nicolaisen 的播客片段。

关于git - git checkout 是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28187319/

相关文章:

git - IntelliJ IDEA Bitbucket Git 集成不推送

windows - msysgit git clone忽略ssh配置

git - 在 git 中删除远程提交

cross-platform - 如果我想在 Java、C++ 或 C# 中使用 DCCP,我有哪些替代方案?

git - 在提交模板中包含当前分支名称

git - Zend Framework 1.x git 存储库

java - 代码在 java 中正常工作,但相同的代码在 C 中的某些测试用例中失败

c#类同时实现和继承

java - 在java中实现随机搜索算法

stack - 如何用 LISP 语言实现 Stack