Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to squash my git branch commits into the same branch without rebasing?

I have a local branch, we're using git-flow with Pull Requests and I'm looking to squash a few commits after receiving PR feedback.

How can I squash all my commits (from PR's for example) into the same branch?

I imagine it would be something like:

git checkout master                    # For master
git pull                               # Get all branches up-to-date
git checkout feature1                  # Checkout the branch
git checkout -b feature1_squash        # Make a copy of the branch
git branch -D feature1                 # Delete original branch
git checkout master                    # (?) Branch off latest master for safety
git checkout -b feature1               # Make new (empty) original branch
git merge --squash feature1_squash     # Merge with squash into it
git push -f feature1                   # Push, force will be required

but I'm not sure.
With that many steps it also seems like a good case for using a function to tie it all together and just pass the branch name as a parameter. Of course automating it would mean making sure to handle errors, exceptions, edge cases, etc.

I don't want to use interactive rebase because it's a little tricky to get right for newbies that I train. I also don't want to have to know the number of commits, I just want to do all the ones that exist on this branch.

like image 325
Michael Durrant Avatar asked Dec 04 '15 13:12

Michael Durrant


1 Answers

The answer from VonC is almost there. but knowing that you want to go 3 commits back is tough.

instead you should use merge-base

git reset --soft $(git merge-base YOUR_BRANCH WHERE_YOU_BRANCHED_FROM)
git commit

and edit your message (or use git commit -m instead)

if your on that branch, you can use HEAD and assuming you branched from master your commands would be (using origin/master due to local master being potentially out of date)

git reset --soft $(git merge-base HEAD origin/master)
git commit

If you cant remember where you branched from, the place you are merging the PR back in to is likely correct

like image 120
exussum Avatar answered Nov 08 '22 18:11

exussum