Git commit safety

Standard
Git commit horror
CREDIT: Raffles Medical Group

I don’t know if I’m the only one that faces it, but I seem to regularly edit the contents of a local Git branch, add/remove files, commit, only to realise that I’ve been working on the wrong branch! Pulling-your-hair-out kinda stuff when you do it time and time again!

I’ve Googled this a bit and it doesn’t seem like there is a “safe mode” for committing. There are a number of StackOverflow threads that suggest solutions (e.g., Git: committed to wrong branch, Git mess: commits in the wrong branch, etc.)

It seems like it’s easy enough to fix this error by creating a new topic branch off of the branch with the erroneous commits and then reverting the original branch to the hash before those commits.

This though seems to me to be a roundabout way of doing something that I think should be prevented in the first place.

So how would you go about preventing this? My suggestion would be that the git commit command itself should always take the current topic branch name as an argument. The reason for this is that you are then forced to think about the branch that you’re committing to. If you end up passing the wrong branch name to git commit (i.e., not the name of the branch you’re currently on), git would throw an error indicating as such.

Seems to me that this is a pretty harmless and failsafe method of ensuring that your commits really are on the right branch. Perhaps having to type the branch name in means that your commit workflow takes 2 seconds longer, but I think that’s worth the compromise (could be shortened by autocomplete, though that might also mean that you’re less aware of the branch name and autocomplete the wrong one!).

For the die-hards that are out there, there could be a setting (global or local) to switch this behavior on or off.

Anyway, any reason why this wouldn’t work? Would love to hear your thoughts!

2 thoughts on “Git commit safety

  1. Nice! I’m assuming you’re referring to the following script: https://raw.github.com/git/git/master/contrib/completion/git-prompt.sh

    Just configured it and seems to work well. It’s at least a way of keep the topic branch that you’re working on in your field of view.

    I think that having to explicitly re-type the branch on committing is more robust. Only reason I can imagine that it’s not the standard is because of how “annoying” it can feel to developers. Would be interesting to do a cost-benefit analysis to see how much it affects productivity vs. how much it improves it by ensuring that you don’t have to undo commits on an incorrect branch.

    Thanks!

    Kartik

Leave a Reply

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