How to Write a Git Hook with Node.js
As setup for a future Zowe / mainframe topic, we’ll look at the basics of writing Git Hooks.
Git Hooks Defined
Git is an extensible version control system . One way to extend git
is through writing hooks
which is just some extra code that you write which is called from git
(you don’t invoke your hooks directly).
Hooks can be written to enforce certain site-specific standards or to do other processing behind-the-scenes.
Hooks are client or server side and usually have a pre-
or post-
flavor; meaning they run before or after a git
operation. To see a given hook and what type it is, look here.
Input, output, and behaviors for various hooks are described here.
Running Example
The example code above is a hook that prints hello hook world
every time someone runs git commit -m "some commit message"
(commit message may vary 😃).
This hook, the pre-commit
hook, runs when you run the corresponding git commit
command:
How to Build the Example
Hooks can be written in different languages. We’ll look at writing a sample in JavaScript running in Node.js.
Open a terminal and create a directory / folder (e.g. githooks
), cd
into it, and git init
it as a git
repo:
After git init
open the .git
folder that is created (folders starting with .
might be hidden). Navigate to /hooks
:
git
provides sample shell-script hooks . Tto run one of these hooks as-is, remove the .sample
extension from the file name and run the corresponding command.
Writing a Node.js Hook
Edit the pre-commit.sample
file here to contain this content:
#!/usr/bin/env nodeconsole.log(`hello hook world`)
Then, rename the file to pre-commit
(without an extension). Run git commit
and see your hook print:
Summary
This is just a starter introduction into the basics of building hooks. In subsequent posts, we’ll look at how to add other packages and parsing input.