Tip: Never Forget a console.log In Your Patch Again

ยท

3 min read

TLDR; stage your changes git add . -p to slow down your personal code review process.

Yes, we've all been there. You've spent the last 5 hours looking for a bug in your codebase and finally came up with a fix. You implemented the patch and removed all your log statements or thought you did. You called for a review only to get rejected because you left some unnecessary logs in your patch.

Have you tried running git add with the -p flag?

With git add <path/to/the/changed/files> -p, git brings back your changes a chunk at a time or, in git lingo, one hunk at a time.

Geek bit: See here for more info about what a hunk is.

As git gradually reveals the changes you made, it presents the following options: y - stage this hunk n - do not stage this hunk q - quit; do not stage this hunk or any of the remaining ones a - stage this hunk and all later hunks in the file d - do not stage this hunk or any of the later hunks in the file e - manually edit the current hunk ? - print help

Side Note: For the e option, git presents Vim as your default editor. Again, you meet Vim ๐Ÿ˜ˆ . To change git's default editor from Vim to vscode, run git config --global core.editor = "code" assuming you have already added vscode to your path variable. I'll advise against this, though; take this opportunity to learn basic Vim motions.

Once git has presented you with all the hunks, you'd be left with only the ones you accepted. The rejected hunks would be left unstaged. Staging your file in git like this allows you to slow down and do a personal code review, allowing you to catch those annoying leftover comments, logs, and debug statements.

Gotchas

The -p flag only works for files already known by git. If you've never staged a file before, git will never present you with hunks from new files because there are no hunks. A hunk is nothing but a diff between the previous version of a file and the newest version, revealed one chunk at a time. There is nothing to diff for a new file, so I like to stage new files with the -N flag, i.e., git add . -N. The "N" flag does not stage the new file but instructs git that you intend to do so later. Now git knows about the file and will present the entire file to you when you're staging your changes with the -p flag.

Conclusion

I couldn't think of a way to conclude this article, so I inserted a dry joke here.๐Ÿ‘‡๐Ÿฝ

If git is a tool, and this article presents tips about git, does that make it a tooltipโ“๐Ÿค”

Okay, I'll give you the time to cringe now. See you on the next one.

ย