- add husky hook into
package.json
- add husky with the given version as a dependency
- add npm script
- place
commit-message.js
into project root folder - edit line #9 in
commit-message.js
and replace JIRA-ID - run
npm install
Last active
December 16, 2021 17:27
-
-
Save thomd/c9615db4901afd15367a060652c1d5f5 to your computer and use it in GitHub Desktop.
simple husky hook for ammending a commit message with a JIRA ID. #husky #git #jira
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const path = require('path') | |
const chalk = require('chalk') | |
const { spawnSync } = require('child_process') | |
const cwd = process.cwd() | |
const messagePath = path.join(cwd, '.git', 'COMMIT_EDITMSG') | |
const JIRA_ID = new RegExp(/ABCD-\d+/) | |
// first, check for jira-id in commit message | |
try { | |
var message = fs.readFileSync(messagePath, 'utf8').replace(/^#.*$/gm,'').trim() | |
} catch(err) { | |
console.log(chalk.red('[ERROR] Commit Message Missing')) | |
process.exit(1) | |
} | |
const messageMatch = message.match(JIRA_ID) | |
if (messageMatch) { | |
process.exit(0) | |
} | |
// if no jira-id is in the commit message, search in branch name for a jira-id and prepend to commit message | |
const { status, _, stdout } = spawnSync('git', ['symbolic-ref', '--short', 'HEAD'], { cwd }) | |
if (status === 0) { | |
const branchName = stdout.toString().trim().split('/').pop() | |
const branchMatch = branchName.match(JIRA_ID) | |
if (branchMatch) { | |
const jiraId = branchMatch[0] | |
fs.writeFileSync(messagePath, `${ jiraId } ${ message }`, { encoding: 'utf-8' }) | |
console.log(chalk.green(`[INFO] Amended the commit-message with: ${ jiraId }`)) | |
process.exit(0) | |
} | |
} | |
// finally, if there is no jira-id available at all, then break commit | |
console.log(chalk.red('[ERROR] Please prepend commit-message with a JIRA-ID')) | |
process.exit(1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "my-project", | |
"version": "0.1.0", | |
"scripts": { | |
"commit-message": "node commit-message.js" | |
}, | |
"dev-dependencies": { | |
"husky": "^4.3.8" | |
}, | |
"husky": { | |
"hooks": { | |
"commit-msg": "npm run --silent commit-message" | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment