How do I squash commits in one branch while keeping them in the other?

Viewed 948

I commit often. I want to keep my history of fine-grained commits in a branch on my local Git repository, and just push much coarser-grained commits into the remote repo.

I want to be able to find corresponding commits in my "fine-grained" local branch.

How do I do that?

1 Answers

In order to keep your local branch out of the remote:

  1. Create and checkout the local branch (let's call it Ruby branch). Commit as needed all your fine-grained commits.

    m1 - m2     <- master, origin/master
      \
       r1 - r2 - r3  <- Ruby (fine grained commits - no origin/Ruby)
    
  2. Whenever you have a coarse-grained piece of work complete in Ruby that you want to send to the remote, merge it an appropriate branch on your local repo that is also a branch on the remote. Let's assume this branch is master, but it might be something else like dev, release-xyz, feature-123, etc.)

    m1 - m2 ------- m3   <- master (new merge m3 from Ruby)
      \            /
       r1 - r2 - r3  <- Ruby
    
  3. To create merge commit (m3 in diagram above), checkout the branch to be merged (i.e. master, etc.) and don't rebase the Ruby branch onto master, which would copy all of the commits r1, r2, and r3 onto master. Instead, just do a normal merge with a commit (i.e. git merge Ruby). In the merge commit, summarize the group of changes in the commit message as you see fit.

  4. Make sure that master is checked out, and push to the remote - or use specific push commands to make sure you are pushing master, and not Ruby.

    m1 - m2 ------- m3   <- master (origin/master updated to m3 from push)
      \            /
       r1 - r2 - r3  <- Ruby (still no origin/Ruby - local only)
    

The idea is that we keep Ruby as a local branch only, and never push it to the remote. Of course, there is no harm in pushing Ruby if anyone else should have access to those fine-grained commits. Also, by pushing Ruby, it will be saved as a backup, in case your PC goes down, and you can clone it to another PC if needed and yours isn't available. So you might want to think about just making Ruby a branch you push to the remote - but even so, you probably will still want to merge with a single commit as described above.

Related