531

We'd like to make a few basic hook scripts that we can all share -- for things like pre-formatting commit messages. Git has hook scripts for that that are normally stored under <project>/.git/hooks/. However, those scripts are not propagated when people do a clone and they are not version controlled.

Is there a good way to help everyone get the right hook scripts? Can I just make those hook scripts point to version controlled scripts in my repo?

4
  • 23
    A good question. I only wish there was a better answer (with no complaints to @mipadi, I just wish git had a way to do this in a more automatic way -- even if only with an option specified to git clone.)
    – lindes
    Commented Feb 8, 2011 at 5:43
  • I agree, @lindes! But perhaps restricting this sharing of hooks in intentional? Things would get messy for Windows users, I suppose.
    – kristianlm
    Commented Sep 21, 2011 at 11:21
  • @kristianlm: There are all sorts of reasons it could be messy at times... and also times when it's nice to have it there. I just wish there was some option or something that would copy the hooks. I guess I'll just have to check out the git-core code sometime, and make a patch. :) (Or hope that someone else does... or live with the workaround in mipadi's answer, or whatever.)
    – lindes
    Commented Jan 15, 2012 at 5:09
  • 2
    pre-commit makes this easy for pre-commit hooks. Doesn't answer the OP's question about managing any arbitrary git hook, but pre-commit hooks are probably the most frequently used for code quality purposes.
    – ericsoco
    Commented Jul 25, 2017 at 20:27

15 Answers 15

359

In Git 2.9, the configuration option core.hooksPath specifies a custom hooks directory.

Move your hooks to a hooks tracked directory in your repository. Then, configure each instance of the repository to use the tracked hooks instead of $GIT_DIR/hooks:

git config core.hooksPath hooks

In general, the path may be absolute, or relative to the directory where the hooks are run (usually the working tree root; see DESCRIPTION section of man githooks).

11
  • 17
    ... and the hooks directory to point to can be s separate hooks repository ;)
    – René Link
    Commented Jun 17, 2016 at 14:25
  • 35
    Well, is this config parameter auto set when you do a git clone?
    – Ring
    Commented Oct 7, 2016 at 16:22
  • 8
    As a rule git config variables can't be set by the repository you are cloning. I think this is to prevent the execution of arbitrary code. git config controls the execution of code through hooks, the user name on commit messages, and other important functions. Commented Oct 11, 2016 at 15:31
  • 3
    What if someone in the team does a git checkout to another branch? They have to include it in every branch.. Commented Jun 12, 2018 at 12:34
  • 1
    That‘s true. On the other hand, if you update the hooks in newer commits, cloned repos will automatically get them when working on branches built on top of that commit. Both ways have their up- and downsides.
    – fabb
    Commented Jul 8, 2018 at 20:54
165

Theoretically, you could create a hooks directory (or whatever name you prefer) in your project directory with all the scripts, and then symlink them in .git/hooks. Of course, each person who cloned the repo would have to set up these symlinks (although you could get really fancy and have a deploy script that the cloner could run to set them up semi-automatically).

To do the symlink on *nix, all you need to do is:

root="$(pwd)"
ln -s "$root/hooks" "$root/.git/hooks"

use ln -sf if you're ready to overwrite what's in .git/hooks

2
  • 41
    this was non-trivial, so i'm including a link as to how to symlink properly: stackoverflow.com/questions/4592838/…
    – David T.
    Commented Nov 24, 2014 at 2:33
  • 36
    git version 2.9 now has a config option for core.hooksPath to set up a file outside of .git to link to the hooks folder. Commented May 29, 2018 at 16:52
59

For Node.js users a simple solution is to update package.json with

{
  "name": "name",
  "version": "0.0.1",
  ......
  "scripts": {
    "preinstall": "git config core.hooksPath hooks",

The preinstall will run before

npm install

and redirects Git to look for hooks inside the .\hooks (or whatever name you choose) directory. This directory should mimic .\.git\hooks in terms of file name (minus the .sample) and structure.

Imagine Maven and other build tools will have an equivalent to preinstall.

It should also work across all platforms.

If you need any more information, see Two ways to share Git hooks with your team.

1
17

I wanted to merge several answers into one. Assuming you are in your project/ directory:

Setup your custom hooks

  1. Create .githooks directory and place your hooks in it. (See .git/hooks for examples)

  2. Create a .gitconfig file that points the directory ¹:

    git config -f .gitconfig core.hooksPath .githooks
    
  3. Create the following rule in your Makefile: ²

    enable-git-hooks:
        git config --local include.path ../.gitconfig
        $(warning REMEMBER, YOU MUST HAVE REVIEWED THE CUSTOM HOOKS!)
    

Enable your custom hooks

Every developer should explicitly enable these custom hooks after reviewing them. Add a directive to your README, something like that:

Enable custom hooks AFTER REVIEWING them by make enable-git-hooks.

2
  • 3
    What do you mean with Makefile? This question is language agnostic. Commented May 11, 2023 at 14:26
  • 3
    One could argue that Makefile is language agnostic.
    – MKesper
    Commented Jun 1, 2023 at 9:07
17

If your project is a JavaScript project and you use npm as the package manager, you can use shared-git-hooks to enforce Git hooks on npm install.

Full disclosure: I wrote this package

1
  • 2
    Warning - does not support Windows (unless it's run as admin in git bash). Simple solution is to add "preinstall": "git config core.hooksPath hooks" as a script in package.json. i.e. Where hooks is a folder containing your git scripts. Commented May 2, 2019 at 19:00
10

Most of the modern programming languages, or rather their build tools, support plugins to manage Git hooks. That means all you need to do is configure your package.json, pom.xml, etc. files, and anyone in your team will have no option but to comply unless they change the build file.

The plugin will add content to .git directory for you.

Examples:

Git Build Hook Maven Plugin

githook-maven-plugin

git-hooks-js

1
5

Use git-hooks. It routes .git/hooks invoke into scripts under the project directory, githooks.

There are also a lot of features to enable you to minimize copy and symlink hook all over the place.

0
4

We are using Visual Studio solutions (and thus projects) which have pre and post build events. I'm adding an additional project named 'GitHookDeployer'. The project self modifies a file in the post build event. That file is set to copy to the build directory. Thus the project is build every time and is never skipped. In the build event, it also makes sure that all git hooks are in place.

Note that this is not a general solution, as some projects, of course, have nothing to build.

2

You could use a managed solution for pre-commit hook management like pre-commit. Or a centralized solution for server-side git-hooks like Datree.io. It has built-in policies like:

  1. Detect and prevent merging of secrets.
  2. Enforce proper Git user configuration.
  3. Enforce Jira ticket integration - mention ticket number in pull request name / commit message.

It won't replace all of your hooks, but it might help your developers with the most obvious ones without the configuration hell of installing the hooks on every developers computer/repo.

Disclaimer: I am one of Datrees founders

2

Ideally, hooks are written in Bash, if you follow the sample files. But you can write it in any language available, and just make sure it has the executable flag.

So, you can write a Python or Go code to achieve your goals, and place it under the hooks folder. It will work, but it will not be managed along with the repository.

Two Options

a) Multi Scripts

You can code your hooks inside your help, and add a small fragment of code to hooks, to call your perfect script, like this:

$ cat .git/hooks/pre-commit
#!/bin/bash
../../hooks/myprecommit.js

b) Single Script

A cooler option is to add just one script to rule them all, instead of several ones. So, you create a hooks/mysuperhook.go file and point every hook you want to have to it.

$ cat .git/hooks/pre-commit
#!/bin/bash
../../hooks/mysuperhook.go $(basename $0)

The parameter will provide your script which hook was triggered, and you can differentiate it inside your code. Why? Sometimes you might want to run the same check for commit and push, for instance.

And then?

Then, you might want to have further functionalities, like:

  • Trigger the hook manually to check if everything is OK even prior to a commit or push. If you just call your script (option a or b) would do the trick.
  • Trigger the hooks on CI, so you don't need to rewrite the same checks for CI. It would be just calling the commit and push triggers, for instance. The same as the above should solve it.
  • Call external tools, like a markdown validator, or a YAML validator. You can make syscalls and need to handle standard output and standard error.
  • Make sure all developers have a simple way to install the hooks, so a nice script needs to be added to the repository to replace default hooks with the correct ones
  • Have some global helpers, like a check to block commits to develop and master branches, not having to add it to every repository. You can solve it by having another repository with global scripts.

Can this be simpler?

Yes, there are several tools to help you manage Git hooks. Each of them is tailored to tackle the problem from a different perspective, and you might need to understand all of them to get the one that is best for you or your team. GitHooks.com offers a lot of reading about hooking, and several tools available today.

As of today, there are 21 projects listed there with different strategies to manage Git hooks. Some only do it for a single hook, some for a specific language, and so on.

One of those tools, written by me and offered for free as an open-source project, is called hooks4git. It is written in Python (because I like it), but the idea is to handle all items listed above in a single configuration file called .hooks4git.ini, which lives inside your repository and can call any script you want to call, in any language.

Using Git hooks is absolutely fantastic, but the way they are offered usually only gets people away from it.

1
  • I had post a very shorter version a while ago, and as agreed with moderators, this brings explanation inside it, and a brief link to a tool I wrote myself which I think may help other developers.
    – Lovato
    Commented Apr 23, 2019 at 11:36
2

For Gradle users

I found these scripts very useful for Gradle projects.

build.gradle

apply from: rootProject.file('gradle/install-git-hooks.gradle')

gradle/install-git-hooks.gradle

tasks.create(name: 'gitExecutableHooks') {
    doLast {
        Runtime.getRuntime().exec("chmod -R +x .git/hooks/");
    }
}
task installGitHooks(type: Copy) {
    from new File(rootProject.rootDir, 'pre-commit')
    into { new File(rootProject.rootDir, '.git/hooks') }
}
gitExecutableHooks.dependsOn installGitHooks
clean.dependsOn gitExecutableHooks

pre-commit

.... your pre commit scripts goes here
1
  • File is not copying from custom directory to .git/hooks directory. Along with the above code, if we add this line of code it will work seemlessly. fileMode 0777
    – Geetha KR
    Commented Sep 23, 2021 at 10:51
2

Inspired by a3765910's answer for Gradle but modified to run every build.

Add the following to your app's build.gradle (assuming you already created the githooks/pre-commit file you want to keep in source control):

copy {
    from new File(rootProject.rootDir, 'githooks/pre-commit')
    into { new File(rootProject.rootDir, '.git/hooks') }
}
1

You can make your hooks folder another Git repository and link it as a submodule...

I guess it is worth it only if you have a lot of members and hooks changed regularly.

0

I'm currently working on this in our codebase and I came across a library called husky which simplifies how to use and share GitHub Hooks across your team. I highly recommend looking into that.

3
  • tat is java script specific. Looks like the OP wants a generic solution to it Commented Apr 13, 2022 at 10:20
  • Apologies, I unknowingly downvoted, my bad. I removed that. No need of sarcasm here. I was actually trying to develop something of a similar sort. We tried Husky, I wanted this to happen in Java/ Python without the need to install a npm module. How would you justify the usage of husky in a pure Java project.? I wanted a pre commit hook.. Kind of needed to be on the client side. Do I still ask the person to first install npm followed by husky? or have my master repo polluted with a package.json configuration ? The recent change in husky also means u have to install husky via npm right ? Commented Apr 21, 2022 at 15:36
  • 1
    @vijayakumarpsg587 thank you for removing downvote. I'm not familiar with java/python. You should be able to use GitHub Hooks without the Husky package, it just makes utilizing hooks easier.
    – CWSites
    Commented Apr 22, 2022 at 14:54
-1

To version your hooks directory (assuming it's stored in hooks/), create a .gitconfig file at the working copy root with the following contents:

[core]
hooksPath = hooks

It will override .git/config.

1
  • 1
    the solution doesn't work. a working sample would certainly help! Commented Jan 5, 2023 at 18:04

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.