If you don't want any commits or files from main, you can create an empty root commit and then create a branch from the commit,
git branch foo $(git commit-tree -m "some message" 4b825dc642cb6eb9a060e54bf8d69288fbee4904)
4b825dc642cb6eb9a060e54bf8d69288fbee4904
is a special tree object that represents an empty directory. git commit-tree
creates a commit that refers to the empty tree with the commit message some message
. In other words, if you check out this commit, there will be no files or sub-directories. You can add and commit files based on it.
git branch
creates foo from the commit.
This way, foo and main are two unrelated histories. Merging foo with main needs an option --allow-unrelated-histories
.
If you find the special empty tree hash value hard to memorize, we can also use a command to make it,
git hash-object -t tree --stdin < /dev/null
It prints 4b825dc642cb6eb9a060e54bf8d69288fbee4904
.
But for most users, it's as rare a command as 4b825dc642cb6eb9a060e54bf8d69288fbee4904
. There's another method, which may be easier to memorize,
git init /path/to/bar
cd /path/to/bar
git commit --allow-empty -m "some message"
cd /path/to/your/repository
git fetch /path/to/bar main
# Or "git fetch /path/to/bar master" depending on the default branch name
# After fetch, the empty commit is stored in FETCH_HEAD
# Create foo from FETCH_HEAD so you don't have to know its exact hash
git branch foo FETCH_HEAD
# Remove /path/to/bar
rm -rf /path/to/bar
This method needs more steps, but they are more common commands.
If you know a commit (for example abc123
) refers to the empty tree, you can also find the empty tree hash by
git rev-parse abc123^{tree}
# Or
git log -1 --pretty=%T abc123
Once you find out the hash of the empty tree, you can then make a tag on it so that you can reference the empty tree with a more friendly name.
git tag emptytree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
Now when you want to create a branch baz from the empty tree,
git branch baz $(git commit-tree -m "some message" emptytree)