Skip to content

Instantly share code, notes, and snippets.

@kraihn
Last active February 9, 2018 17:02
Show Gist options
  • Select an option

  • Save kraihn/56f487d328c2b975cc54 to your computer and use it in GitHub Desktop.

Select an option

Save kraihn/56f487d328c2b975cc54 to your computer and use it in GitHub Desktop.
Prefix Commit Message with Jira Issue
#!/usr/bin/env node
var exec = require('child_process').exec,
util = require('util'),
fs = require('fs'),
contents = null,
branch, desc;
// expect .git/COMMIT_EDITMSG
if(/COMMIT_EDITMSG/g.test(process.argv[2])){
// look for current branch name
branch = exec("git branch | grep '*'",
function (err, stdout, stderr) {
if(err){
// git branch will fail if initial commit has not been done,
// so we can safely skip this hook
process.exit(0);
}
// opens .git/COMMIT_EDITMSG
contents = fs.readFileSync(process.argv[2]);
// trims extra characters from start/end of line
var name = stdout.replace('* ','').replace('\n','');
// If the branch has a description, pull that
desc = exec('git config branch.'+ name +'.description',
function(err, stdout, stderr){
// don't handle errors (because we write out branch anyway)
// we found a description, add to 'name'
if(stdout){ name = util.format('%s (%s)', name, stdout.replace(/\n/g,'')); }
// '(no branch)' indicates we are in a rebase or other non-HEAD scenario
if(name !== '(no branch)'){
// matches: /ABC-123, /aBc-123, /abc-123, /AbC-123, /abc-123-456
// Begins with slash because prefix is always: feature, bugfix, chore...
// Project ID is always alpha
// Issue ID is always numeric
var jiraIssue = /\/[a-zA-Z]+([-][0-9]+)+/;
if (jiraIssue.test(name)) {
// Extract issue(s) from branch name
var issueLine = jiraIssue.exec(name)[0].substring(1).toUpperCase().split('-');
name = [issueLine[0], issueLine[1]].join('-');
// Append for multiple issues
for(var i = 2; i < issueLine.length; i++) {
name += ',' + [issueLine[0], issueLine[i]].join('-');
}
}
else {
process.exit(0);
}
// Append name to original contents.
contents = util.format('[%s] %s', name, contents);
// write contents back out to .git/COMMIT_EDITMSG
fs.writeFileSync(process.argv[2], contents);
process.exit(0);
} else {
process.exit(0);
}
});
});
}
@nathanbedford
Copy link

Update gist to remove old hooks first, then re-init (for Windows):
https://gist.github.com/nathanbedford/4e126e81d9ff183cf68e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment