DEV Community

Cover image for Automated Cross-Platform Git Hooks with npm
Peace Chen
Peace Chen

Posted on • Edited on

Automated Cross-Platform Git Hooks with npm

Git hooks are a convenient way to help developers sanitize code automatically. Git supports a hook for virtually every Git action. A popular use case is leveraging pre-commit to lint code.

For better or for worse, Git hooks are not committed as part of the repository. Every developer manually installs the team's Git hooks for that repo. There must be a better way.

Not wanting to reinvent this wheel, I searched for pre-made solutions but they didn't meet my requirements: simple, cross-platform, no additional third-party tools. Their typical requirements or limitations:

  • Manual creation of YAML or .rc configuration files, or scripts in a non-native hook format.
  • Installation of heavy dependencies (Python, Ruby...). Remember, every developer who works on the repo has to install those dependencies.
  • Platform-specific scripts (*NIX or Windows only, not both).

Getting out of the way

Ramp up time is crucial. Don't burden new developers with dozens of manual setup steps. Let the computer do the grunt work so that humans can get stuff done.

Projects that use npm or yarn are very likely to have Node installed, and I leveraged that for cross-platform support.

node-git-hooks is deployment- and CI-friendly. It won't install the hooks if your library is used by another project, avoiding the error Appears to be a git repo or submodule.

Installation

npm install node-git-hooks --save

Writing Git hooks should be fast and straight-forward. I kept it as close to the metal as possible. The hooks files are written exactly the same as they exist in the .git/hooks folder. Create a .githooks folder and place hooks files inside. An example pre-commit script that performs linting:

#!/bin/sh
# Lint all files under the `src` directory
./node_modules/.bin/eslint src
Enter fullscreen mode Exit fullscreen mode

Perhaps surprisingly, the above hook works on both *NIX and Windows. I recommend using a current version of npm or yarn. Older versions may not be as cross-platform friendly.

Finally, add the following prepare script to package.json:

"scripts": {
  "prepare": "node-git-hooks"
},
Enter fullscreen mode Exit fullscreen mode

With the above steps in place, running npm install (or npm run prepare) copies the hooks files from .githooks to .git/hooks. The hooks files may be committed to the repo and will be automatically installed to other devs' repos when they run npm install.

Summary

I hope that this helps more teams adopt Git hooks. Source code is available at node-git-hooks. Comments and PRs are welcome!

Top comments (1)

Collapse
 
spock123 profile image
Lars Rye Jeppesen

Great article, thanks.