Search code examples
gitpackage.jsongit-husky

Custom git hook in package.json with husky


I am trying to validate the commit message at commit. For that, I am using Husky and the commit-msg hook.

However, as I also do commit message validation at build time, I want the validation code to be available in a separate JS file. So I am trying to call an external JS file to perform my commit validation. In my package.json file, I have:

"commitmsg": "node validation.js"

However, I cannot get the validation to be performed properly. Right now, validation.js looks like this:

console.log('Here');
const config = (a, b) => {
  console.log(a);
  console.log(b);
};

module.exports = config;

Here is displayed, but the console.logs in the function are not called.

Any idea how I can get my function to get called? Also, how can I access the commit message?


Solution

  • I was being silly, I found the solution. In case it is useful to somebody else in the future:

    const myRegex = new RegExp('.*');
    const commitMsg = require('fs').readFileSync(process.env.HUSKY_GIT_PARAMS, 'utf8');
    
    if (!myRegex.test(commitMsg) ) {
      console.error(`Invalid commit message!`);
      process.exit(1);
    }