How to add a new root commit?

Viewed 190

I need to simulate an abnormal commit history in order to write a test case, where I want a commit history like:

  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

I expect git rev-list to show:

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

My ultimate goal is to let git rev-list --max-parents=0 HEAD return multiple lines.

1 Answers

sha3 can't be converted to a root commit. A commit is immutable. But it's possible to create new root commits.

By an orphan branch, assuming the current branch is master,

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

By the empty tree object 4b825dc642cb6eb9a060e54bf8d69288fbee4904,

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

By either way, git rev-list --max-parents=0 HEAD now prints 2 root commits.

It's almost impossible to remember the empty tree hash. You can use the command git hash-object -w -t tree --stdin < /dev/null to create the tree and get its hash.

In fact, in order to create a root commit, we don't have to use the empty tree. We can use any existing tree.

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

Here sha3 can be replaced by any other existing commit. The advantage of the empty tree is that it won't cause merge conflicts.

Related