Git remote/shared pre-commit hook

Viewed 33807

With a one official repository as the remote, and multiple local repositories cloned from it, can a pre-commit hook be scripted on that main repository and be enforced on all clones of it?

7 Answers

Very very old answers here. This is definitely possible these days.

Since Git 2.9 or so, the config core.hooksPath is available. Per the git documentation:

core.hooksPath

By default Git will look for your hooks in the $GIT_DIR/hooks directory. Set this to different path, e.g. /etc/git/hooks, and Git will try to find your hooks in that directory, e.g. /etc/git/hooks/pre-receive instead of in $GIT_DIR/hooks/pre-receive.

The path can be either absolute or relative. A relative path is taken as relative to the directory where the hooks are run (see the "DESCRIPTION" section of githooks[5]).

This configuration variable is useful in cases where you’d like to centrally configure your Git hooks instead of configuring them on a per-repository basis, or as a more flexible and centralized alternative to having an init.templateDir where you’ve changed default hooks.

This means that you can share Git hooks between client machines (perhaps using a non-.git folder inside the project, or using a dedicated Git repository locally cloned, or using sync software such as OneDrive or Dropbox) by just setting the core.hooksPath config to that (shared) folder.

I create a new file: pre-commit-hook.sh

#!/usr/bin/env bash
CHANGES=$(git whatchanged ..origin)

if [ ! -z "${CHANGES}" ]; then
    echo "There are changes in remote repository. Please pull from remote branch first."
    exit 1;
fi

exit 0;

And this is how I commit to Git:

bash pre-commit-hook.sh && git commit -m "<Commit message>"
Related