Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add my pre-commit hook to an existing git repository

Tags:

I have a pre-commit hook and I want to add it to the repository so that by checking it out my colleagues have it instantly in place.
However if I try to add it ( being in the root directory of my project) I get the following result:

$ git add  .git/hooks/pre-commit
error: Invalid path '.git/hooks/pre-commit'
error: unable to add .git/hooks/pre-commit to index

Any idea if this work and how to achieve my goal?

like image 674
Calamity Jane Avatar asked Sep 18 '15 10:09

Calamity Jane


People also ask

How do you enforce a pre-commit hook?

If you want enforcement, use an update hook in the central repo. If the hook is doing per-commit verification, you can still provide a pre-commit hook; developers will likely adopt it voluntarily, so that they can find out right away when they've done something wrong, rather than waiting until they try to push.

Can I push git hooks to remote?

No. Hooks are per-repository and are never pushed.

Where are pre-commit hooks stored?

The hooks are all stored in the hooks subdirectory of the Git directory. In most projects, that's .git/hooks .


1 Answers

checking it out my colleagues have it instantly in place

Sept. 2015: That is not possible: a hook can be put in source control (you simply copy the script in your git repo), but it cannot be "automatically in place" (active) on clone/checkout: that would be way too dangerous, depending on what the hook is actually doing.
See also "Git remote/shared pre-commit hook"

You would still need to activate it, by adding a symlink (even on Windows) to the pre-commit hook present in the git repo.

Update Dec. 2016: the OP Calamity Jane mentions in the comments:

I solved it by now in symfony2 projects (and with others, it also should work) to have it as part of the composer.json.
So if a colleague is doing a composer install or composer update, it is automatically placed in the correct place.

"scripts": { "dev-install": [ "bash setup_phpcs.sh" ] }, 

So on dev, setup_phpcs.sh is automatically called and that copies the hook from a folder in the repository to the right place.
And since the hook is part of the repository it can be easily updated and distributed.

As noted by Hi-Angel in the comments:

I figured that out: Emacs has build-aux dir with hooks, and, upon running autogen.sh, all hooks are copied from there.

like image 80
VonC Avatar answered Sep 19 '22 13:09

VonC