0

I have files in main branch and I wanted add new branch NEW_PROJECT so I can later on PR and merge it to main. The problem is that every time i create NEW_PROJECT from main branch I also get its files, and if I delete it they are still visable in commits.

Is there a way to create empty branch without commits that can be later on PR to main?

Alexa
  • 21
  • 4
  • one way to do this would be squash. You will create new branch with old commits, yes. However you can 'squash' them into one to have cleaner history https://stackoverflow.com/questions/5189560/how-do-i-squash-my-last-n-commits-together – Pioter88 Feb 09 '23 at 13:16
  • 1
    I don't see the problem with branching off `main` in the usual way. – chepner Feb 09 '23 at 13:51

1 Answers1

0

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)
ElpieKay
  • 27,194
  • 6
  • 32
  • 53