2

Is there a simple Git command to squash all commits with the same commit message to one commit in a new branch?

A simple command seems to me:

git merge --squash BRANCH_WITH_SAME_COMMIT_MESSAGES

The problem is that I created that branch from the develop branch. All our done tickets gets merged into develop. So during working on BRANCH_WITH_SAME_COMMIT_MESSAGES our workflow is to merge the develop into BRANCH_WITH_SAME_COMMIT_MESSAGES if a done ticket gets merged into develop.

The problem is that also all the other stuff from develop gets squashed, but I only want the commits squashed, that have the same commit message.

How can I do that?

BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
  • 1
    Does this answer your question? [Squash my last X commits together using Git](https://stackoverflow.com/questions/5189560/squash-my-last-x-commits-together-using-git) – Liam Nov 11 '20 at 10:42

1 Answers1

2

I think what you are looking for is git rebase. You can selectively squash together commits in a branch using the Interactive Mode.

To do this automatically by commit message you can use --autosquash. But for this the commits you want to squash/fixup must beginn with "squash! <original message subject>" / "fixup! <original message subject>". You can create such commit messages using git commit --squash <original commit> (or --fixup).

However as I read your question what you're actually want to do is remove duplicate commits, since the commits with the same message in your branches also contain the same changes?

In that case you should also use git rebase on your feature branch:

git rebase develop

This will rebase your branch with all commits that are not yet in develop onto of that effectively removing all duplicate commits and merges.

acran
  • 7,070
  • 1
  • 18
  • 35
  • It is only one branch with that commits. I used the same commit message as a marker so that I can later squash them. – BuZZ-dEE Nov 11 '20 at 14:29
  • If you already use the same commit message explicitly just prefix it with `squash! ` / `fixup! ` and use `git rebase --autosquash` then. – acran Nov 11 '20 at 22:32
  • What do you mean by "just prefix it..."? Do I have to change all the commit messages afterwards? – BuZZ-dEE Nov 11 '20 at 22:45
  • You could edit all existing commit messages - e.g. with [`git rebase -i`](https://git-scm.com/docs/git-rebase#_interactive_mode) - and then apply the above approach. But my recommendation was meant for _future_ commit first of all. – acran Nov 11 '20 at 23:00
  • For an existing branch probably not. Still your best bet on this is to use `git rebase -i` which gives you a plain text file where you can reorder and squash/fixup commits. If there are too many commits to do this manually you may still find a way to order them programmatically with a small script or something. – acran Nov 18 '20 at 22:50