Can I create a worktree for an empty Git repo?

Issue

I have an empty Git repository (i.e. it contains no commits yet). Is there a way to create a worktree using git worktree add command (with --no-checkout option) for this repo? I mean to instruct Git not to associate a newly created worktree with any HEAD yet.

Solution

In a completely empty repository, there can be no branches, because each branch name must identify one actual, existing commit.1 The main worktree, however, must be on some branch. So Git has it on a non-existent branch, which Git calls both an unborn branch (in various messages and internal code) and an orphan branch (in flags like git checkout --orphan).

In theory, git worktree add could also allow --orphan, to put a new work-tree on an unborn branch. It does not currently do so, however. Should you wish to write new code for Git that allows it to do this, and send it to the Git maintenance folks, it might be a candidate for inclusion in a future Git release. It’s probably a good idea to include some sort of reasonably compelling use case.

Until then, you can’t do this: you must make at least one initial commit (which then allows an infinite number of branch names to be created).

Edit: it seems --orphan might be in the next Git release (2.40, probably). See VonC’s comment.


1This constraint is somewhat arbitrary, but Git makes it anyway, so one must live with it (or rewrite Git).

Answered By – torek

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published