Skip to content

Instantly share code, notes, and snippets.

@romaricpascal
Last active December 29, 2022 23:47
Show Gist options
  • Save romaricpascal/6092859 to your computer and use it in GitHub Desktop.
Save romaricpascal/6092859 to your computer and use it in GitHub Desktop.
commit-msg Git hook to ask user for an issue ID when he commits and prepend it to the original commit message
#!/usr/bin/env node
var fs = require('fs'),
util = require('util');
// Rattern to format the message with the issue ID
var MESSAGE_FORMAT = '[%s] %s';
// Git commit messages are stored in a file, passed as argument to the script
// First and second arguments will be 'node' and the name of the script
var commitFile = process.argv[2];
// Let's start by reading the current commit message
fs.readFile(commitFile, 'utf-8', function (err, message) {
if(err) {
console.log('Original commit message could not be read :(');
process.exit(-1);
}
if (message === '') {
// If the commit message is empty, just pass it on to git
// The commit wil abort anyway
process.exit(0);
}
// Now we have the message, let's read the user input
var stream = fs.createReadStream('/dev/tty');
stream.setEncoding('utf-8');
// Displays a message to the user when the hook's ready to get input
stream.on('open', function () {
console.log('Which issue were you working on?');
});
// Handles the data provided by the user
stream.on('data', function (data) {
// First, we get rid of the trailing carriage return at the end
data = data.replace('\n','');
// User must provide an issue ID, so we'll prompt them again if they don't
if (data === '') {
console.log('You need to provide an issue ID. What issue were you working on?');
return;
}
// Otherwise we prepend the issue ID to the commit message
var finalMessage = util.format(MESSAGE_FORMAT, data, message);
// And replace the content of the commit message file
fs.writeFile(commitFile, finalMessage, function(err) {
if (err) {
console.log('Commit message could not be written :(');
console.log(err);
process.exit(-2);
}
console.log('The issue ID has been added to the commit message.\nPress RETURN to complete commit');
process.exit();
});
});
});
@Punit-wingify
Copy link

Awesome 👍

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