Search code examples
gitgit-mergegit-rebase

Move a Git commit retrospectively to another branch in the history


I accidentally committed a general change on a development branch and already merged it to the master branch a while ago:

* HEAD
* ...
*
* 2c884bc Updated Gradle Root Project Name
*   4926f6a Merge branch 'wip-dev-Logger'
|\
| * 43161fb Revised Logger
| * 13c8303 Switched to JDA 4.4.0_351
* | 599c72e Added Answerer interface
|/
* 4b0dcb8 Switched to Java 17
*
* ...
*

Is it possible to move commit 13c8303 from the development to the master branch without destroying the merge/branch history?

It should then look like this:

* HEAD
* ...
*
* 2c884bc Updated Gradle Root Project Name
*   4926f6a Merge branch 'wip-dev-Logger'
|\
| * 43161fb Revised Logger
* | 13c8303 Switched to JDA 4.4.0_351
* | 599c72e Added Answerer interface
|/
* 4b0dcb8 Switched to Java 17
*
* ...
*

Solution

  • Based on the answer from @IMSop, I came up with the follwoing solution:

    1. In my case there were no other branches apart from master and I have not yet pushed any of my mistakes on a remote

    If you have an unmerged branch pointing to a newer commit, make sure you know how to handle the additional difficulties to come.

    1. git rebase --root --interactive --rebase-merges
    2. Change the order of commits in the editor
    ...
    
    pick 4b0dcb8 Switched to Java 17
    label branch-point
    pick 13c8303 Switched to JDA 4.4.0_351                       <--- COMMIT TO MOVE ---
    pick 43161fb Revised Logger
    label wip-dev-Logger
    reset branch-point # Switched to Java 17
    pick 599c72e Added Answerer interface
    merge -C 4926f6a wip-dev-Logger # Merge branch 'wip-dev-Logger'
    pick 2c884bc Updated Gradle Root Project Name
    
    ...
    

    to

    pick 4b0dcb8 Switched to Java 17
    label branch-point
    pick 43161fb Revised Logger
    label wip-dev-Logger
    reset branch-point # Switched to Java 17
    pick 599c72e Added Answerer interface
    pick 13c8303 Switched to JDA 4.4.0_351                       <--- COMMIT TO MOVE ---
    merge -C 4926f6a wip-dev-Logger # Merge branch 'wip-dev-Logger'
    pick 2c884bc Updated Gradle Root Project Name
    
    ...
    
    1. Save and close the editor. Everything should work fine if you didn't touch any files in the moved commit that could conflict with this merge.

    2. Confirm using git log --graph --oneline:

    * HEAD
    * ...
    *
    * c5d2985 Updated Gradle Root Project Name
    *   31a26e4 Merge branch 'wip-dev-Logger'
    |\
    | * 13e0a2c Revised Logger
    * | 5cebef6 Switched to JDA 4.4.0_351
    * | 599c72e Added Answerer interface
    |/
    * 4b0dcb8 Switched to Java 17
    *
    * ...
    *