Thursday, December 20, 2012

Git : Editing A Previous Commit

When you work with Git, making branches is a very common task and when you are flooded with ideas, you  may be in a hurry and sometimes make mistakes. The most common example of making mistakes when committing in git is - the commit message. Sometimes, just after committing, you would realize that you forgot to mention something crucial.

Sometimes, it may also happen that when you create your commit, you might accidentally forget to add a particular file to the commit. Even this is a likely scenario since git does not automatically add new directories under version control when you add them through your local file system. So if you did a git add . during your first commit and then created lots of subdirectories and files, they will not be added automatically just because you had done an initial "git add .".

Well, there is one small source of relief - and that is - you can easily amend the last commit in git and fix these tiny issues. For example, let us say that you just committed with a very nonsensical and convoluted message. like this

git commit -m "I was so drunk when I wrote this shit".

And then, the next morning when you wake up, you do a git log and you see this message pop up on your screen and jump out of your seat. Well, if you have not pushed your changes upstream, i.e. the commit still resides only on your local repository, it would really serve a noble purpose if you actually make the message more sensible. Here's how you can do that.

git commit --amend -m "This commit has all the equations that prove the String Theory"

The above command will simply edit the commit message of the latest commit.

However, if you have done something more grave, like missed out on files that were supposed to be added in the previous commit, then you can simply add them using the git add . command then use the git commit with the --amend option in the same way as shown above. Basically what you did was that you rebuilt the tree that represents the files of this commit, discarded the previous commit and created a new one in its place. You can say so because when you amend a commit, it results in a new commit checksum.

Hope this helps!

Signing Off
Ryan

No comments: