Pages

Friday, April 07, 2023

Start git repos as empty repos

So you know how to use git. You create a folder, smack in some files, git init, git add ., git commit -m "Initial commit". You don't even use a GUI tool. Madness.

Stop doing that. Well, not not [sic] using a GUI tool. Stop git add . first. Start with an empty commit initially.

Why? Because then you don't have a linear repo any more. You can start branches that go "backwards", essentially. This may seem insane, but, trust me, someday it will come in handy.

Great step-by-step by VonC:

You can even rebase your existing history on top of that empty commit (see "git: how to insert a commit as the first, shifting all the others?")

In both cases, you don't rely on the exact SHA1 value of that empty tree.
You simply follow a best practice, initializing your repo with a first empty commit.


To do that:

git init my_new_repo
cd my_new_repo
git config user.name username
git config user.email email@com
git commit --allow-empty -m "initial empty commit"

That will generate a commit with a SHA1 specific to your repo, username, email, date of creation (meaning the SHA1 of the commit itself will be different every time).
But the tree referenced by that commit will be 4b825dc642cb6eb9a060e54bf8d69288fbee4904, the empty tree SHA1.

git log --pretty=raw
commit 9ed4ff9ac204f20f826ddacc3f85ef7186d6cc14
tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904      <====
author VonC <vonc@laposte.net> 1381232247 +0200
committer VonC <vonc@laposte.net> 1381232247 +0200
    initial empty commit

An interesting bit of trivia: Though the SHA of the commit will change from repo to repo, the tree's SHA will always be the same: 4b825dc642cb6eb9a060e54bf8d69288fbee4904.