0

How to create custom husky hook?

I would like to do something like this:

// package.json
...
husky: {
  "pre-commit": "node customHook.js"
},
...

How to get access to the commit params from the customHook.js file?

P.S. I found almost the same question, but unfortunately it doesn't work for me.

Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68

1 Answers1

0

I found a solution.

Change "pre-commit" hook to "commit-msg" in the package.json file. After, you are able to get commit message by using the next line of code:

// terminal (cmd)
git commit -m "my commit message"
// customHook.js file
const message = require('fs').readFileSync(process.env.HUSKY_GIT_PARAMS, 'utf-8');

console.log(message); // "my commit message"
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68
  • Can you reject the commit for example if regex of commit is not correct? In `customHook.js` can you exit the process if some conditions are not met and commit is prevented? – mjakic Jun 25 '19 at 14:02
  • @mjakic inside your js file you can throw a js Error which would result in the hook throwing and error and your script failing. – siwalikm May 27 '20 at 16:12
  • you can use **process.exit(1)** – Sandeep Aug 19 '21 at 05:36