Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept "git commit -a(m)"

Tags:

git

I like the fine-grained commits that the git index allow, i.e. the staging of individual files or even hunks through git add before the final commit. Unfortunately, sometimes after spending some time staging a particular commit, muscle-memory kicks in so that I git commit -a -m "msg". Then I either have to live with it, or jump through some reset or --amend hoops.

Is there a way for me to (ideally, globally) configure Git so that if I issue a git commit -a, it gets intercepted? Maybe a script asking me to confirm if I really want to commit all? I've thought about delegating the commit operation to a wrapper script (e.g., "gitcommit"), but do not think that will work very well as it does not stop me from doing a git commit -a -m "msg", which is the problem in the first place.

like image 543
Jeet Avatar asked Apr 08 '26 09:04

Jeet


1 Answers

Try pre-commit hooks:

something like this (not tested)

.git/hooks/pre-commit

#!/bin/sh
git diff-files --quiet    # check if the working directory have non-staged files
DIRTY_WORKING=$?

if [ ! $DIRTY_WORKING ] ; then        #  check if we are committing all files
   # list all files to be committed
   git diff-index --name-status --cached HEAD

   echo "Are you sure? (type YES to continue)"
   read VALUE
   [ "x$VALUE" != "xYES" ]
   exit $?
fi
exit 0

You can find out the number of files to be committed using git diff-index --cached HEAD | wc -l. But I think I would leave this to yourself.

like image 125
J-16 SDiZ Avatar answered Apr 10 '26 03:04

J-16 SDiZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!