git hooks - commit-msg示例代码,用于校验提交注释
#!/usr/bin/env node /** * Generated by ghooks. Do not edit this file. */ 'use strict'; var fs = require('fs'); var util = require('util'); var packageObject = {}; var MAX_LENGTH = 100; var PATTERN = /^((feature|fixbug|book)(\w*))(\s*)(.*)$/; var IGNORED = /^Merge branch/; try{ packageObject = require('../../package.json').config['validate-commit-msg']; }catch(e){} if(packageObject && packageObject.validRegex){ PATTERN = new RegExp(packageObject.validRegex); } if(packageObject && packageObject.validRegex){ IGNORED = new RegExp(packageObject.ignoreRegex); } MAX_LENGTH = packageObject.maxLength || MAX_LENGTH; var error = function() { // console.log('[commit-msg] process.argv:', process.argv); console.error('[validate-commit-msg]: ' + util.format.apply(null, arguments)); }; var validateMessage = function(message) { // var isValid = true; if (IGNORED.test(message)) { return true; } if (message.length > MAX_LENGTH) { error(packageObject.maxErrorTip || '提交注释超过最大字符数(%s)', MAX_LENGTH); return false; } var match = PATTERN.exec(message); if (!match) { error(packageObject.validErrorTip || '注释不符合规范' + message); return false; } // var type = match[1]; // var scope = match[3]; // var subject = match[4]; // if (!TYPES.hasOwnProperty(type)) { // error('"%s" is not allowed type !', type); // return false; // } // Some more ideas, do we want anything like this ? // - allow only specific scopes (eg. fix(docs) should not be allowed ? // - auto correct the type to lower case ? // - auto correct first letter of the subject to lower case ? // - auto add empty line after subject ? // - auto remove empty () ? // - auto correct typos in type ? // - store incorrect messages, so that we can learn return true; }; var firstLineFromBuffer = function(buffer) { return buffer.toString().split('\n').shift(); }; // publish for testing exports.validateMessage = validateMessage; var commitMsgFile = process.argv[2]; var incorrectLogFile = commitMsgFile.replace('COMMIT_EDITMSG', 'logs/incorrect-commit-msgs'); fs.readFile( commitMsgFile, function(err, buffer) { var msg = firstLineFromBuffer(buffer); if (!validateMessage(msg)) { fs.appendFile( incorrectLogFile, msg + '\n', function() { process.exit(1); } ); } else { process.exit(0); } } );