Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move an old commit to another branch in git?

Tags:

git

I do have a project in GIT which currently has 3 branches, master, develop and feature/core-md-topbar.

I was working in the feature/core-md-topbar branch and discovered a bug which is present in the development branch which I accidentally fixed in the feature/core-md-topbar branch.

Now, I don't have anything pushed to the remote yet, but I want my fix to be part of the develop branch.

So, this is my current commit:

enter image description here

So, I want the commit starting with FIX and hash 64376b2 to be placed immediately after the second commit with hash 8f928d0.

Off course, I should not lose any work.

What's the gittish way to solve this problem?

like image 937
Complexity Avatar asked Mar 17 '17 13:03

Complexity


1 Answers

Cherry-pick the fix commit from core-md-topbar to development:

git checkout development
git cherry-pick 64376b2

Remove the fix commit from core-md-topbar:

You can try doing an interactive rebase:

git rebase -i HEAD~8

A window looking something like the following should come up. Note that commits are shown from oldest to newest.

pick 2eb670c comment
pick 8f928d0 comment
pick 8b96886 comment
pick 8fa512e comment
pick 995396f comment
pick dd4ab71 comment
pick 64376b2 comment
pick 704c5da comment

Delete the line (DO NOT drop the commit!) containing the fix commit 64376b2, leaving you with this:

pick 2eb670c comment
pick 8f928d0 comment
pick 8b96886 comment
pick 8fa512e comment
pick 995396f comment
pick dd4ab71 comment
pick 704c5da comment

Now save and close the window, which will start the actual rebase. You may get merge conflicts as each commit is reapplied from 8 commits ago.

The first cherry-pick safe is clean and safe. But the interactive rebase runs a potential risk if the core-md-topbar branch is publicly shared and you have published from the fix commit onwards. If you have published already, then you are much safer to revert that fix commit, assuming you don't want in the core-md-topbar branch:

git checkout core-md-topbar
git revert 64376b2

This instructs Git to make a new commit on the HEAD of core-md-topbar which effectively undoes the fix commit. And publishing this won't cause problems for a public branch that others are using.

like image 159
Tim Biegeleisen Avatar answered Oct 20 '22 10:10

Tim Biegeleisen