Squash commits directly on feature without rebase or merge

Vivendi picture Vivendi · Jul 14, 2015 · Viewed 7.7k times · Source

I've been reading a little about --squashing commits, but they all seem to be go hand in hand with a --rebase.

I have a feature branch with a set of commits like this:

(Feature)          A --> B --> C --> D --> E --> F --> G
                  /
(Master)  M1 --> M2 --> M3

Suppose I want to merge back to the Master branch, but I want to clean up the commits on my feature first.

Is it possible to:

  • Pick commit B, E and F and squash them together as one commit?

OR

  • Can I only squash the commits that come in order, so squash: (A, B and C), or squash (D, E and F) etc?

Either way, can I do a squash directly on my feature, WITHOUT immidiately initializing a Merge or Rebase with it?

If so, how can I do this with Git?

Answer

BoltzmannBrain picture BoltzmannBrain · Sep 7, 2017

In my team's workflow we often merge with upstream in the middle of a bunch of commits, and rebasing could get ugly. I've found this helpful to squash all commits that are ahead of master down into one:

# Commit any working changes on branch "mybranchname", then...
git checkout master
git checkout -b mybranchname_temp
git merge --squash mybranchname
git commit -am "Message describing all squashed commits"
git branch -m mybranchname mybranchname_unsquashed
git branch -m mybranchname

# Optional cleanup:
git branch -D mybranchname_unsquashed

# If squashing already-pushed commits...
git push -f