Git has a plethora of commands at your disposal. But we often end up using only a handful of those in our daily git workflow. The
git add and
git checkout are one of those indispensable commands:
git add . // stage the modified content of the working directory
git checkout <branch-name> // for checking out to other branches
But, I have often seen devs not leveraging these commands to their full power. The aforementioned usages are often enough to get the job done. Moreover, our mind is so comfortable in using them that we don’t want to explore what rest they have to offer.
This article is my attempt to change how you think about these two commands. Welcome to the world of git interactive.
git add -p
This command gives you the flexibility of selecting granular changes, and mark them accordingly to go into your staging area. Instead of adding a complete file, You can stage only desired hunks of diffs from it and leave the rest. For e.g, If you have made two changes in your tracked file
README.md , you can stage one of them and not the other.
We should strive to keep our commits smaller. A commit subject should be enough to justify your reason for the specified change.
In those scenarios, where you have gone too far and refactored a huge bunch of code,
git add -p is your best bet. It helps you to add small and isolated changes and make them ready for a commit. You can re-visit and select more hunks to be part of the subsequent commits.
While diagnosing an issue, you might have sprinkled a whole bunch of console.log statements. Doing so, you might have refactored a few lines of code that you might want to keep for future commits.
You can smartly use
git add -p to cherry-pick those useful lines of code and create a commit out of that. This will leave the log statements in your working directory, which you can safely discard later on.
git checkout -p
This command allows you to discard hunks interactively from your working directory. In other words, it does the opposite of interactive staging. Instead of discarding all the changes in a file, you can choose which part of the file you want to remove and keep the rest 🚀.
If you have been brainstorming about an idea, and have quickly scribbled a few lines to code. You can invoke this command and interactivity remove irrelevant code from your working directory, leaving important bits to become part of the staging area.
The same use case as we have for interactive staging, but works in reverse order. Instead of cherry-picking useful bits, you can discard the unnecessary log statements and leave the important work for future staging.
This is all for now. To learn more about git tools and command, I highly recommend reading this book here. Now go ahead and give these commands a try. Let me know your thoughts in the comments below.
Also, if you've enjoyed reading this article, please don’t forget to show some ❤️.