Skip to content

Instantly share code, notes, and snippets.

@thomd
Last active December 16, 2021 17:27
Show Gist options
  • Save thomd/c9615db4901afd15367a060652c1d5f5 to your computer and use it in GitHub Desktop.
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

Setup

  1. add husky hook into package.json
  2. add husky with the given version as a dependency
  3. add npm script
  4. place commit-message.js into project root folder
  5. edit line #9 in commit-message.js and replace JIRA-ID
  6. run npm install
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)
{
"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