Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to install git hooks on "npm install"?

I'd like to install a pre-commit git hook (that lints the code) when someone installs my-package.

I tried to add a postinstall script:

"scripts": {
  "postinstall": "./scripts/install-git-hooks"
}

This works great. When someone runs npm install, they get the pre-commit hook installed.

However, if another-package depends on my-package, running npm install for another-package runs the postinstall script as well, which is undesired.

What's the cleanest way to avoid this undesired affect?

like image 683
Misha Moroshko Avatar asked May 12 '16 07:05

Misha Moroshko


People also ask

Can we install Git from npm?

npm install git doesn't install git (i.e. the command line tool to manipulate git repositories). It installs the npm package called git which seems to be a JavaScript library to interact with git repositories (which makes the name accurate, but still misleading). npm is not a general-purpose package manager.

How do I get Git hooks?

To install the hook, you can either create a symlink to it in . git/hooks , or you can simply copy and paste it into the . git/hooks directory whenever the hook is updated. As an alternative, Git also provides a Template Directory mechanism that makes it easier to install hooks automatically.

Is npm I npm install?

There is no difference, since "npm i" is an alias for "npm install". They both do the exact same thing (install or update all the dependencies in your package-lock.


2 Answers

You can use the ghooks npm module and add it as a dev-dependency. You can configure what to run before commit in your package.json like so:

[...]
"config": {
    "ghooks": {
        "pre-commit": "npm test"
    }
}
[...]
like image 67
vincent Avatar answered Oct 09 '22 12:10

vincent


Hacky, but might work for you.

The trick is to identify (within the script) if it is a sub-dependency or a root dependency for the NPM installation. Simply check if ../../package.json exists. If so, it's a sub dependency and you should skip installing the hooks.

It should be noted that you are breaking any consistent installation rules, which is exactly against the spirit of the installation scripts. This is to install client-side hooks which cannot be trusted by any means, if you need the linting to be enforced, this should be done server side, where it can just reject code that doesn't comply.

Potentially this issue would be better solved like you mentioned, by having it as a custom install script, and just dealing with the additional communication overhead.

like image 35
Luke Exton Avatar answered Oct 09 '22 12:10

Luke Exton