Home > Blockchain >  Git - How to split a branch into 2 or more branches?
Git - How to split a branch into 2 or more branches?

Time:08-24

I've read some other questions (here, here, etc) , but didn't answer mine.

In the project I am working on there is a new rule: maximum 5 files changed/created per PR. I know how insane is this rule and sometime impossible to do it, because to make a functionality work sometimes more than 5 files need to be edited/created.

However for now that's the situation and I need to understand a simple way, (maybe there is a software for it) to achieve for example the following:

  1. From a branch with 8 files changed (compared to master)
  2. Split it into two new branches, one with 5 files and the other with 3 files (of my choice)

Now matter if the new branches will not have the functionality working. Still it is needed, no matter how insane is that - not my decision :(

How to split such branch?

Thank you

CodePudding user response:

You have my sympathy. Git handles everything at the commit level.

You can potentially take your feature branch, use git reset --soft to go back in the history and you can stage/unstage your changes to make multiple branches.

CodePudding user response:

You can rewrite entire histories by using rebase tool.

I'll show you an example of how you would do that. Assume your starting branch is feature/big.

Start by creating 2 branches, named feature/small1 and feature/small2 at the same point:

git branch feature/small1 feature/big
git branch feature/small2 feature/big

Switch to one branch and remove some files/commit. You can use --fixup to remind yourself to squash the changes with a certain commit (or --amend if you want to change your last commit). Use git log <filename> to discover the commit id where the changes were made

git switch feature/small1
# remove file1 which was added on commit abcdef
git rm file1
git commit --fixup abcdef
# revert changes of file2 which was changed on commit 12345
git checkout file2 -- 12345^
git add file2
git commit --fixup 12345

Now squash the changes with the original commits where the changes were made, and push the new branch to the remote repository

git rebase -i --autosquash `git merge-base HEAD master`
git push feature/small1

Repeat with feature/small2, but this time remove different files.

Refer to git rebase documentation for the explanation of what these commands do.

  •  Tags:  
  • git
  • Related