首页 > 解决方案 > 如何添加新的根提交?

问题描述

我需要模拟一个异常的提交历史来编写一个测试用例,我想要一个提交历史,比如:

  sha4
  sha3 // i want this to be a root commit
  sha2
  sha1 // this is the first commit of the repo, so it's a root commit

我希望git rev-list展示:

$ git rev-list --max-parents=0 HEAD
sha3
sha1

我的最终目标是让git rev-list --max-parents=0 HEAD返回多行。

标签: git

解决方案


sha3无法转换为根提交。提交是不可变的。但是可以创建新的根提交。

通过孤立分支,假设当前分支是master

git checkout --orphan temp sha3
git commit -m 'init temp'
git checkout master
git merge temp --allow-unrelated-histories

通过空树对象4b825dc642cb6eb9a060e54bf8d69288fbee4904

git merge --allow-unrelated-histories $(git commit-tree -m'new root commit' 4b825dc642cb6eb9a060e54bf8d69288fbee4904)

无论哪种方式,git rev-list --max-parents=0 HEAD现在都会打印 2 个根提交。

几乎不可能记住空树哈希。您可以使用该命令git hash-object -w -t tree --stdin < /dev/null创建树并获取其哈希值。

事实上,为了创建根提交,我们不必使用空树。我们可以使用任何现有的树。

git merge --allow-unrelated-histories $(git commit-tree -m'new root commit' sha3^{tree})

这里sha3可以替换为任何其他现有的提交。空树的优点是不会引起合并冲突。


推荐阅读