当运行 git checkout
时,旧的 HEAD
和新的 HEAD
的 merge 库可以任意远。天真的实现是线性应用每个差异,但操作会立即运行。
我有一种预感,它可能会通过某种用于中间差异缓存的跳过列表来实现,但这只是一个猜测。
有人知道它是如何实现的吗?谢谢! :)
最佳答案
关于如何(原则上)在 javascript implementation of Git (as an exercise) Gitlet 中实现 checkout ,您有一个很好的例子作者:Mary Rose Cook。
对于 checkout ,步骤是:
checkout()
changes the index, working copy and HEAD to reflect the content ofref
.
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 andHEAD
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 theHEAD
file.
If the head is not being detached, the branch being checked out is written toHEAD
.- 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/