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?

theonlygusti
  • 11,032
  • 11
  • 64
  • 119

1 Answers1

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
}
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • What are the arguments to the pre-commit git hook? – theonlygusti Mar 26 '21 at 10:42
  • I don't see any arguments in `$@` no matter how I `git commit`, so I don't see how I can wrap it... – theonlygusti Mar 26 '21 at 10:43
  • I want to do this https://stackoverflow.com/q/66802328/3310334 – theonlygusti Mar 26 '21 at 10:44
  • 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. – Socowi Mar 26 '21 at 11:16
  • It wasn't obvious to me how to set the author and git committer every pre-commit. I will just use `git()` wrapper function – theonlygusti Mar 26 '21 at 11:17