MICROFACT: How To Create An Empty Git Root Commit

// July 11th, 2012 // Uncategorized

I’ve been doing a lot of tooling and implementation with the wonderful Git revision control system.  In my time, I’ve needed to do some magic things involving repository history.  One thing that comes up often is the need to have an empty commit history on some branch.

This is actually pretty easy.  Here’s the run-down:

git read-tree --empty

NEW_TREE="$(git write-tree)"

NEW_COMMIT="$(git commit-tree -m empty "$NEW_TREE")"

git branch NEWBRANCH "$NEW_COMMIT"

git reset

If it’s not obvious from the above code, here’s what’s going on.

  • Git read-tree creates an empty index.
  • Git write-tree creates an empty tree object from the empty index.
  • Git commit-tree creates a new commit with that tree, no parent, and the commit message “empty”.
  • Git branch creates a new branch pointing to that commit.
I hope this is as useful to you as it is to me.
MICROFACT:
Sometimes, a small but very important fact is difficult to definitively find on the Internets.  A microfact post exists to seed this information into Google, so that others won’t have to search as hard as I did.

3 Responses to “MICROFACT: How To Create An Empty Git Root Commit”

  1. Eduardo Mello says:

    I created a new repository. Added a dummy file and commited. Then I followed the commands you listed on the post and got the following anwser:

    error: The following untracked working tree files would be removed by checkout:
    dummy-file
    Please move or remove them before you can switch branches.
    Aborting

    What I did wrong?

    • jayson says:

      Good catch. The state of the working tree was left inconsistent, and newer versions of git seem to complain. Before doing the checkout, you should do a mixed reset (i.e. ‘git reset’) to clean up the working tree. I’ve updated the recipe to reflect this.

  2. Eduardo Mello says:

    Just to be more clear. I got that message when I tried to checkout into the new branch

Leave a Reply