Tag Archives: hooks

Git hooks

Git hooks are lovely. Consider automated syntax check before committing changes:

  • git config –global init.templatedir ‘~/.git-templates’
  • mkdir -p ~/.git-templates/hooks
  • vi ~/git-pre-commit-hook.sh and put, for instance, following:


#!/bin/bash

  retcode=0
  for f in $( git diff --cached --name-status|awk '$1 != "R" { print $2 }' ); do
    echo "Veryfying $f..."
    filename=$(basename "$f")
    extension="${filename##*.}"
    if [ "$extension" = "pl" ] || [ "$extension" = "pm" ]; then
      perl -c $f
      lineretcode=$?
      if [ $lineretcode != 0 ]; then
        retcode=$lineretcode
      fi
    fi
  done

  if [ $retcode != 0 ]; then
    echo
    echo "Pre-commit validation failed. Please fix issues or run 'git commit --no-verify' if you're certain in skipping validation step."
    exit 1
  fi

  exit 0

  • chmod a+x ~/git-pre-commit-hook.sh
  • ln -sn ~/git-pre-commit-hook.sh ~/.git-templates/hooks/pre-commit (point of this to have it centralised – on next step global template is copied to repository, so if it’s a symlink – it’s easier to adjust for all later)
  • cd to your repository and run git init there – it’d re-instantiate the repository with copying global hook templates there

That’s it – now you have yourself neat little safeguard. There are better techniques of course – flymake, for one, or some IDE build/check configuration. That works, too – but gets too tricky when you have to patch the code on remote instances. In my case, I have to edit files remotely – and while Emacs has no problem with that (Sublime has plugin for that, too, and you can always add some fuse SSH mount), my flymake settings suck, and I’m not keen to dive into a bloodthirsty piragna pool of its remote execution configuration.

So… git hooks it is.