In software development, feature branching is a common practice where each new feature is developed in its own branch. However, there are times when you might need to combine these branches and their commits into one, for instance, if you're aiming to create a single, comprehensive pull request (PR) for a multi-part feature.
Before we begin, ensure you have a backup of your branches, as combining branches can be a destructive process if not handled correctly.
Create a new branch: This branch will be the base for combining the other branches.
git checkout -b combined-branch
Merge each feature branch: Sequentially merge your feature branches into the new branch.
git merge feature-branch-1
git merge feature-branch-2
Resolve any merge conflicts that arise during this process.
Squash commits (optional): If you want to combine all the commits into a single commit, you can use an interactive rebase.
git rebase -i <commit-before-your-branches>
In the interactive prompt, change
squashfor all but the first commit.
Push the combined branch: Once you have combined all the branches and optionally squashed your commits, push the new branch to the remote repository.
git push origin combined-branch
Callout: Remember to communicate with your team before consolidating branches, as it might affect the work in progress.
Graphite can simplify the process of combining branches, especially when dealing with multiple PRs.
Select the branches: Use Graphite's interactive stack view to select the branches you wish to combine.
Combine branches: Use the
gt stack mergecommand to merge the selected branches into a single stack.
gt stack merge --dest combined-stack
Submit the new stack as a PR: With the
gt submitcommand, you can open a new PR for the combined stack.
Graphite's powerful stack management commands, like
submit, streamline complex workflows and make multi-branch operations more manageable.
Once you have your combined branch ready:
Close existing PRs: If you have open PRs for the individual branches, close them with a note explaining that a combined PR will replace them.
Open a new PR: On GitHub, navigate to the
combined-branchand open a new PR. Link back to the closed PRs for reference.
Review and merge: Invite your team to review the new, comprehensive PR. After approval, merge it into the main branch.
Consolidating multiple Git branches and commits into a single branch can be beneficial for creating a unified PR, simplifying code review, and maintaining a clean project history. Whether you choose to use native Git commands or Graphite's CLI, the process requires careful execution and clear communication with your team.
For more detailed instructions and advanced techniques, refer to the official Graphite documentation.