Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge two git commits

Tags:

git

git-rebase

I have done a series of commits and now I'm seeing that I would have liked to have 2 commits merged. Not the last two, but a bit further away

My log:

commit 326f35d83963660893d065e480f231b76f052dd2
Author: Peter Smit <[email protected]>
Date:   Thu Dec 16 11:13:47 2010 +0200

    Small editing in ASR chapter

commit 652b4c27a5fcb2125ed82aea31421fca4e8eee47
Author: Peter Smit <[email protected]>
Date:   Thu Dec 16 11:12:55 2010 +0200

    Added longtable package for abbreviations

commit 74069a151cce9c47484403c1db76e68e1360d8ee
Author: Peter Smit <[email protected]>
Date:   Thu Dec 16 11:12:23 2010 +0200

    Changed some headings in the introduction

commit 94126f79fdc6f4927a3f270c152393377e9ef5a5
Author: Peter Smit <[email protected]>
Date:   Thu Dec 16 11:11:57 2010 +0200

    Added abbreviations chapter

All four commits are changing seperate files, so there can't be any merge conflicts.

I would like to add the 652b4 (Added longtable) to the 94126 (Added abbreviations) commit. How can I do this?

like image 634
Peter Smit Avatar asked Dec 13 '22 17:12

Peter Smit


2 Answers

This situation is handled by interactive rebase. The standard warning about not rewriting history that has been pushed applies. There is a decent explanation in the Git Book, but I personally find the interface of rebase -i to be exactly upside down.

Begin the rebase by naming the parent of the earliest commit you need to modify:

$ git rebase -i 94126f7^

An editor pops up listing the commits in forwards chronological order (so you have to turn your head upside down). Every commit from the HEAD to the child of the commit named is listed, which is why you named its parent:

pick 94126f7 Added abbreviations chapter
pick 74069a1 Changed some headings in the introduction
pick 652b4c2 Added longtable package for abbreviations
pick 326f35d Small editing in ASR chapter

What you want to do is squash the commit 652b4c2 onto 94126f7, so you change its command to “squash” and move it directly after the latter:

pick 94126f7 Added abbreviations chapter
squash 652b4c2 Added longtable package for abbreviations
pick 74069a1 Changed some headings in the introduction
pick 326f35d Small editing in ASR chapter

Save and exit; the next editor that pops up will be for the combined commit message. You can change this however you want, then when you exit it will finish the rebase.

Conflicts while rebasing can be annoying (some patches simply will not commute), and merges can be especially ugly, but there won’t be any problems reordering file additions.

like image 130
Josh Lee Avatar answered Jan 03 '23 10:01

Josh Lee


If you haven't push those commit yet, do a git rebase --interactive (See Interactive Rebasing).
You will be able to make those two commits into one.

like image 42
VonC Avatar answered Jan 03 '23 10:01

VonC