Short Tip: Moving commits between branches

Sometimes you are developing on a huge new feature on a software project. If you are smart you do it in a separate (feature-) branch. During the development cycle you may modify existing code and after a few days you notice that this was a security bugfix. Merging the complete branch to get the fix is a really bad idea because your feature isn’t ready yet. Thankfully git offers a solution for moving commits from one branch to another, so we can easily create a bugfix branch, move the commits into it, review and than merge it. Here is a little example:


bastelfreak@tmu ~/virtapi $ git checkout master
Switched to branch 'master'
Your branch is behind 'origin/master' by 2 commits, and can be fast-forwarded.
(use "git pull" to update your local branch)
bastelfreak@tmu ~/virtapi $ git pull
Updating 061bb98..1bae1ed
Fast-forward
database/images/virtapi.svg | 5306 ++++++++++++++++++++++++++++++++++++++-----------------------------------------
database/virtapi.sql | 295 +++--
database/workbench/virtapi.mwb | Bin 23848 -> 25329 bytes
3 files changed, 2727 insertions(+), 2874 deletions(-)
bastelfreak@tmu ~/virtapi $ git checkout -b fix-markdown
Switched to a new branch 'fix-foobar'
bastelfreak@tmu ~/virtapi $ git cherry-pick 9d1792019fe903a986e18f4f1e95701f4a0a0154 faae8809d5f802fa1d9c258820812f4d5ddb7719 94cbb0702e67a0b76142bdc7a7482364e0ae6ee9
[fix-markdown 57af32e] fix intendation
Date: Fri Jan 8 16:17:57 2016 +0100
1 file changed, 9 insertions(+), 9 deletions(-)
[fix-markdown 85782a3] fix intendation
Date: Fri Jan 8 16:09:13 2016 +0100
1 file changed, 23 insertions(+), 23 deletions(-)
[fix-markdown fa71ab5] fix intendation
Date: Fri Jan 8 15:25:51 2016 +0100
1 file changed, 13 insertions(+), 13 deletions(-)
bastelfreak@tmu ~/virtapi $ git push
Username for 'https://github.com': bastelfreak
Password for 'https://bastelfreak@github.com':
Counting objects: 8, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (8/8), 820 bytes | 0 bytes/s, done.
Total 8 (delta 5), reused 0 (delta 0)
To https://github.com/virtapi/virtapi.git
+ fa71ab5...c6f62ac fix-markdown -> fix-markdown
bastelfreak@tmu ~/virtapi $

Tip: Always take a look which branch is the base for your new one, if you don’t specify a base branch during the checkout -b, git will use the currently checked out branch. During my first try I created the fix-markdown branch based on my dev-branch, this will result in very strange issues.

This entry was posted in General, Linux, Short Tips. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.