Incremental Git Squashing for Long-lived Branches

The Problem

Soon after joining a team where multiple developers were committing frequently to a git repository, it became apparent that rebasing on the main branch could become painful. I woudld rebase in order to keep my feature branch in sync with changes happening in the main branch. However, I'd have to go through certain conflicts multiple times per rebase, and often I'd be rebasing multiple times through the branch's history. Enough was enough - it was time for a script.

The Approach

Here's how the script works:

  1. It first checks if you're in a Git repository.
  2. It creates a backup branch with a timestamp.
  3. It enters a loop where you can specify how many commits to squash in each iteration.
    • For each iteration, it:
      1. Performs an interactive rebase on the specified number of commits.
      2. Prompts you to run tests and verify changes.
      3. Pushes the changes using --force-with-lease to make sure you don't accidentally trample more recent changes on the remote.

Usage

You can find the rebase_squash script in my dotfiles repo. Just make it executable and run it from within your repository.

Concluding Remarks

This is one way to deal with the issue - there are others. I like using rebase. The main issue is that the default experience offered by git for this workflow is not great. If you see any room for improvement or would like me to link to alternatives, please let me know.