geckos
geckos

Reputation: 6279

How husky works?

https://github.com/typicode/husky has the ability to run git hooks automatically in a way that they can be shared between teams in the repository it self.

How can this even work? Since the hooks need to be in .git/hooks which is not added to repository.

Does it wraps git command and intercept commands, running hooks when they happen?

I want to reproduce this behavior for python and php projects without the need to depend on npm or node.

Upvotes: 25

Views: 7747

Answers (2)

succerror
succerror

Reputation: 551

As of version 5 husky uses git's core.hooksPath git config core.hooksPath .husky to be exact. This is done in husky install step.

Since .husky folder created by husky install contains pre-commit script, it will be run before commit. By default it will have npm test in it but you can edit it to your wish.

You can do something similar in any project. Just add .githooks folder and hook files inside it(check .git/hooks for sample files). But you have to run git config core.hooksPath .githooks while cloning the repo(or setting up hooks for the first time). You can have some init script to do that.
npm has scripts.prepare which can run commands on npm install which is husky install in this case.

Upvotes: 30

Nico
Nico

Reputation: 215

While the husky dependency is installed (through npm install, npm add husky, yarn install, ...) git hooks are created/updated in the .git/hooks directory. If the hook is triggered through a git command a script from husky is triggered that will execute a command based on the package manager you used for the installation. If you use npm npx --no-install husky-run $hookName "$gitParams" is executed. That command looks into your configuration and executes the command defined for the hook there.

It's like a proxy for git hooks. The proxy is installed once and executed every time by a normal git hook. If it is executed it looks into the configuration and executes the commands defined there.

Upvotes: 6

Related Questions