Squash commits directly on feature without rebase or merge Squash commits directly on feature without rebase or merge git git

Squash commits directly on feature without rebase or merge


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 mastergit checkout -b mybranchname_tempgit merge --squash mybranchnamegit commit -am "Message describing all squashed commits"git branch -m mybranchname mybranchname_unsquashedgit branch -m mybranchname# Optional cleanup:git branch -D mybranchname_unsquashed# If squashing already-pushed commits...git push -f


Solution: It is possible to squash multiple commits into single one without rebasing. The best option is to create a new temporary branch from master, then merge the messy branch squashed in only single commit into the temporary branch, then making a pointer to it in your working branch and after delete the temporary one.

Lets assume:

  • master is your master branch,
  • feature is your messy working branch
  • temp is your temporary branch

How to do it?

git checkout -b <temp> <master>git merge --squash <feature>git commit -m "your single message"git checkout <feature>git reset --hard <temp>git push -fgit branch -D <temp>

Before:

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

After:

                           AG -->                           /(Master)  M1 --> M2 --> M3 


Yes and no.

Yes, you can avoid changing the parent of commit 'A' but I believe you can't avoid git rebase. You can do interactive rebase on the same root:

git rebase -i M2 Feature

Then you can do whatever you want and at the end branch Feature will still start from commit M2.