Wednesday, December 12, 2012

Note to Self: Commit code frequently on git

Its been a long time since I blogged here. I have written drafts of THE post which was supposed to end this long hiatus from blogging, but I guess the short note I am writing today is short enough to go from draft to publish.

Since the last post, much has happened. One such thing is that I have started using Git. Its awesome. It is the way a SCM should be. Well at least most of it. I came across an issue today where I ended up losing some code I had written. In fact, it took a while to realize that code was lost. Here is how it can happen if you are not careful.

Create a temporary directory. Then try the following commands:

$ git init
$ echo “Baba Black Sheep” > blacksheep.txt
$ git add blacksheep.txt
$ git commit –m “First Commit”
$ git checkout –b whitesheep
$ echo “No black sheep, only white sheep here” > blacksheep.txt
$ cat blacksheep.txt
$ git checkout master
$ cat blacksheep.txt

The changes done in branch whitesheep are carried over to the master branch. I found this behaviour unexpected. I was expecting that when I create a branch, whatever changes I do there, remain in that branch. But apparently that is not the case.

Thus, this small note to self that whenever done with a piece of code, even on another branch, always commit. In case you are wondering how I lost the code, I think I made changes to a branch, forgot to commit the code, changed to master, and then pulled from bitbucket and during the rebase the changes made on the other branch were overwritten. At least that is what I think happened.
Will play around with this a bit more, but if I expected that changes made on whitesheep should not have reflected on master, I guess there would be others who would expect the same. So just something to keep in mind.

To end, I hope to be blogging more often here.