Search code examples
gitbranchcommitsquash

How can I create a sibling branch that includes all the commits from another branch into one node?


I have a branch, mybranch, that has six commits and stems from commit C. I would like to create a new branch, also based on commit C, that effectively includes all the commits from mybranch, squashed into one commit. What's the easiest way to do this?

I need to do this due to the mantra of "squash before you git-push". For the new branch, I don't want any mention of mybranch in the history pushed up to the remote server. The reason I want to create a whole new branch used to push is because I'd like to keep all the commits in mybranch for reference.


Solution

  • Why only push squashed commits? That sounds crazy (and wrong).

    But to answer your question:

    git checkout -b newbranch # checkout new branch
    git reset --soft C # move to commit C
    git commit -m 'squashed commit'
    

    Another possibility would be to use rebase -i to squash/fixup all commits into a single one:

    git checkout -b newbranch
    git rebase -i C # now, replace every 'pick' with 'fixup'/'squash' except the first one
    

    Also of interest is git merge --squash:

    Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit or move the HEAD, nor record $GIT_DIR/MERGE_HEAD to cause the next git commit command to create a merge commit. This allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).

    git checkout -b newbranch C # create newbranch at commit C
    git merge --squash mybranch
    git commit -m 'squashed commit'