Get Noticed 2017 Tools

CodeTip #6 – Moving already commited changes to new branch using GIT

Imagine the following situation: your job was to add some functionality to the application. You’ve worked on this for last couple days doing N commits. When the job is over you want to push your changes to the origin but soon after you spot that for the whole time you’ve worked on master/develop branch instead of the feature branch. Sounds familiar to you? Don’t worry, you can still move your changes!

 

The example

Let’s say that we started a new project. We’ve already committed three commits directly from the master branch. The diagram below presents that:

 

 

The solution

Now, let’s say that commit 2 and 3 are supposed to be on some feature branch. In order to do that, we need to divide the whole process into three steps. The first is to undo these two commits and put all modified files to the set of untracked files. You can achieve that using the following command:

git reset HEAD~2

Of course, the number after HEAD word depends on a number of commits to undo. The diagram presents the result of the above command:

 

 

Here’s the step two. All the changes have to be moved to the new branch. First, we need to mark them as tracked using the following command:

git add -A

 

 

Having this done, we move the files using:

git checkout -b <name_of_the_new_branch>

 

 

The last step is to commit our changes:

git commit -m „my functionality”

 

 

Now, you have all your changes on a separate branch, so you can push them to pass the code review (because you do it, right?). Hope, this will help you 😉

  • Pingback: dotnetomaniak.pl()

  • I think that you could also maintain the previous commit structure, without merging all the changes to one.

    1. Create new branch
    2. move to it and use git cherry-pick to bring deltas of those commits
    3. move to master reset head and reset code

    • I guess you’re right. Honestly I forgot about cherry-pick which would be handy in the discussed example 😉 Thanks a lot!

      • Git is ‚enourmous’, there are many different functions and approaches 🙂

  • tmr

    One more way, no cherry-picks, feature commits’ history remains:
    Given the initial state (being on master, three commits done).
    1. Checkout new branch, it’ll contain the full story: git checkout -b „feature”
    2. Go back to master: git checkout –
    3. Get back to the „branching point” state: git reset –hard HEAD~2 & git clean -fdx

    Result (gitk –all): https://uploads.disquscdn.com/images/35a8d8ca4c12c1c1d368f0dee449fc85d5fceed5b827a203ee257ec4edcdb758.png

Don’t miss new posts!

If you enjoy reading my blog, follow me on Twitter or leave a like on Facebook. It costs nothing and will let you be up to date with new posts 🙂