0

How can I make git commit call a custom wrapper shellscript I've written (~/.gitcommit for example), but all other git commands are just passed to git like normal.

I am trying as pointed out by https://superuser.com/a/175802/325613

preexec () {
  echo preexecing "$1"
  if [[ "$1" =~ ^[:space:]*git[:space:]+commit[:space:].* ]]; then
    echo git commit detected
  fi
}

preexec_invoke_exec () {
    [ -n "$COMP_LINE" ] && return  # do nothing if completing
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return # don't cause a preexec for $PROMPT_COMMAND
    local this_command=`HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//"`;
    preexec "$this_command"
}
trap 'preexec_invoke_exec' DEBUG

but this prints like this

$ git commit
preexecing git commit
fatal: not a git repository (or any of the parent directories): .git
$ git commit with some args
preexecing git commit with some args
fatal: not a git repository (or any of the parent directories): .git
$          git commit now now now
preexecing git commit now now now
fatal: not a git repository (or any of the parent directories): .git
$ git       commit        space
preexecing git       commit        space
fatal: not a git repository (or any of the parent directories): .git

It seems my regex is never matching. Why?

1 Answer 1

1

You regex does not match because [:space:] is the same as [aceps:]; a character class that matches one of a, c, e, p, s, or :. You probably meant [[:space:]]. The following should work

if [[ "$1" =~ ^[[:space:]]*git[[:space:]]+commit[[:space:]] ]]

However, your current approach is a bit strange. Have you considered writing a pre-commit git hook?

Even if you have a very rare case where a git hook is not an option then a bash function would be way better:

git() {
  if [ "$1" = commit ]; then
     # do stuff, e.g. insert arguments using `set --`
  else
    # in every case, run the real git
    command git "$@"
  fi
}
Sign up to request clarification or add additional context in comments.

5 Comments

What are the arguments to the pre-commit git hook?
I don't see any arguments in $@ no matter how I git commit, so I don't see how I can wrap it...
Yeah, seems like you cannot inspect the command line arguments inside a pre-commit hook. In that case the shell function would be better. However, why would you want to do this if you want to always ask for the author? Just ask away without inspecting anything.
It wasn't obvious to me how to set the author and git committer every pre-commit. I will just use git() wrapper function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.