How to combine multiple Git branches

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.

  1. Create a new branch: This branch will be the base for combining the other branches.

    git checkout -b combined-branch

  2. 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.

  3. 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 pick to squash for all but the first commit.

  4. 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.

  1. Select the branches: Use Graphite's interactive stack view to select the branches you wish to combine.

  2. Combine branches: Use the gt stack merge command to merge the selected branches into a single stack.

    gt stack merge --dest combined-stack

  3. Submit the new stack as a PR: With the gt submit command, you can open a new PR for the combined stack.

    gt submit

Graphite's powerful stack management commands, like stack merge and submit, streamline complex workflows and make multi-branch operations more manageable.

Once you have your combined branch ready:

  1. 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.

  2. Open a new PR: On GitHub, navigate to the combined-branch and open a new PR. Link back to the closed PRs for reference.

  3. 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.