-1

Imagine I have the last three commits:

fwr5678 most recent commit
46545ac fix for old commit
3c337c1 old commit message

I want to rewrite my history so the oldest two (46545ac and 3c337c1) are merged into the same commit. I want my history to look like

fwr5678 most recent commit
3c337c1 fix for old commit + old commit message

How can I do this?

ZakTaccardi
  • 12,212
  • 15
  • 59
  • 107
  • Look at this https://github.com/rotati/wiki/wiki/Git:-Combine-all-messy-commits-into-one-commit-before-merging-to-Master-branch – iAviator May 19 '18 at 04:43
  • Merging the two past commits is possible but both commits you get after this operation will have different hashes than they initially had (because, in fact, they are new commits.) – axiac May 19 '18 at 06:31
  • Possible duplicate of [Squash my last X commits together using Git](https://stackoverflow.com/questions/5189560/squash-my-last-x-commits-together-using-git) – phd May 19 '18 at 13:33
  • @phd I'm not squashing my last two commits commits together. I'm trying to squash the previous second and third commits into one, and leave the most recent commit in tact. – ZakTaccardi May 19 '18 at 14:58
  • Doesn't matter, the command is the same. – phd May 19 '18 at 17:04

2 Answers2

1

The easiest way is:

git rebase --interactive HEAD~3

Then fill in:

pick   3c337c1 old commit message
squash 46545ac fix for old commit
pick   fwr5678 most recent commit

Finally, another prompt will show up asking you how to merge the commit messages. Simply write:

fix for old commit + old commit message

Obviously, all the standard git adages apply. (e.g. "Don't rewrite public history.")

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
0

I don't think that this is possible to do in Git, by design.

A commit ID is based on older commits, so if your old commits change, then your newer ones should change as well.

In any case, I'm assuming you've already pushed this history to a remote, since you want to keep the top commit ID the same, and that you shouldn't be doing; it'll mess up other people's repos.

On the other hand, if you haven't pushed, then simply do a squash.

...one of the most widely used is the ability to squash commits. What this does is take smaller commits and combine them into larger ones, which could be useful if you’re wrapping up the day’s work or if you just want to package your changes differently.

A word of caution: Only do this on commits that haven’t been pushed an external repository. If others have based work off of the commits that you’re going to delete, plenty of conflicts can occur. Just don’t rewrite your history if it’s been shared with others.

cst1992
  • 3,823
  • 1
  • 29
  • 40