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

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 😉

You may also like...