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:

  • gitignore file not working properly
  • How to ignore files from 'git status' if only white spaces and line breaks changed
  • Sync exists git repo with p4 repo and continue working
  • Untrack and stop tracking files in git
  • How do I setup Cordova?
  • Tracking code versions in an executable
  • "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?

  • Reflecting Heroku push version within the app
  • Split text file using Unix utilities, like grep and sed
  • Problems in rebasing in git
  • git add auto-complete filename
  • how show the diff from my current working directory and my last commit?
  • How to show Git revisions that are either tips of branches or not merges?
  • 2 Solutions collect form web for “How to install git hooks on “npm install”?”

    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"
        }
    }
    [...]
    

    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.

    Git Baby is a git and github fan, let's start git clone.