-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidate-commit-msg.js
192 lines (151 loc) · 5.98 KB
/
validate-commit-msg.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env node
/**
* Git COMMIT-MSG hook for validating commit message
* See https://docs.google.com/document/d/1rk04jEuGfk9kYzfqCuOlPTSJw3hEDZJTBN5E5f1SALo/edit
*
* Installation:
* >> cd <angular-repo>
* >> ln -s ../../validate-commit-msg.js .git/hooks/commit-msg
*/
'use strict';
var fs = require('fs');
var util = require('util');
var resolve = require('path').resolve;
var findup = require('findup');
var semverRegex = require('semver-regex');
var config = getConfig();
var MAX_LENGTH = config.maxSubjectLength || 100;
var IGNORED = new RegExp(util.format('(^WIP)|(^%s$)', semverRegex().source));
var PROJECT = config.project || ['FROAD', 'MALL', 'BOSS'];
var TYPES = config.types || ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'revert'];
// fixup! and squash! are part of Git, commits tagged with them are not intended to be merged, cf. https://git-scm.com/docs/git-commit
var PATTERN = /^((\w+)-(\d+): (\w+)(?:\(([^\)\s]+)\))? - (.+))(?:\n|$)/;
var MERGE_COMMIT_PATTERN = /^Merge /;
var error = function () {
// gitx does not display it
// http://gitx.lighthouseapp.com/projects/17830/tickets/294-feature-display-hook-error-message-when-hook-fails
// https://groups.google.com/group/gitx/browse_thread/thread/a03bcab60844b812
console[config.warnOnFail ? 'warn' : 'error']('INVALID COMMIT MSG: ' + util.format.apply(null, arguments) +
'\n\nAn exmaple like: MALL-164: fix(seckill-round) - add withdraw interface\n');
};
var validateMessage = function(raw) {
var messageWithBody = (raw || '').split('\n').filter(function(str) {
return str.indexOf('#') !== 0;
}).join('\n');
var message = messageWithBody.split('\n').shift();
if (message === '') {
console.log('Aborting commit due to empty commit message.');
return false;
}
var isValid = true;
if (MERGE_COMMIT_PATTERN.test(message)) {
console.log('Merge commit detected.');
return true
}
if (IGNORED.test(message)) {
console.log('Commit message validation ignored.');
return true;
}
var match = PATTERN.exec(message);
if (!match) {
error('does not match "<project>-<jiracode>: <type>(<scope>) - <subject>" !');
isValid = false;
} else {
var firstLine = match[1];
var project = match[2];
var jiracode = match[3]
var type = match[4];
var scope = match[5];
var subject = match[6];
var SUBJECT_PATTERN = new RegExp(config.subjectPattern || '.+');
var SUBJECT_PATTERN_ERROR_MSG = config.subjectPatternErrorMsg || 'subject does not match subject pattern!';
if (firstLine.length > MAX_LENGTH) {
error('is longer than %d characters !', MAX_LENGTH);
isValid = false;
}
if (PROJECT.indexOf(project) === -1) {
error('"%s" is not allowed JIRA project !', project);
isValid = false;
}
if (Number.isInteger(jiracode)) {
error('"%s" is not a number! JIRA code should be a number', type);
isValid = false;
}
if (TYPES !== '*' && TYPES.indexOf(type) === -1) {
error('"%s" is not allowed type !', type);
isValid = false;
}
if (!SUBJECT_PATTERN.exec(subject)) {
error(SUBJECT_PATTERN_ERROR_MSG);
isValid = false;
}
}
// Some more ideas, do want anything like this ?
// - Validate the rest of the message (body, footer, BREAKING CHANGE annotations)
// - 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
isValid = isValid || config.warnOnFail;
if (isValid) { // exit early and skip messaging logics
return true;
}
var argInHelp = config.helpMessage && config.helpMessage.indexOf('%s') !== -1;
if (argInHelp) {
console.log(config.helpMessage, messageWithBody);
} else if (message) {
console.log(message);
}
if (!argInHelp && config.helpMessage) {
console.log(config.helpMessage);
}
return false;
};
// publish for testing
exports.validateMessage = validateMessage;
exports.getGitFolder = getGitFolder;
exports.config = config;
// hacky start if not run by mocha :-D
// istanbul ignore next
if (process.argv.join('').indexOf('mocha') === -1) {
var commitMsgFile = process.argv[2] || getGitFolder() + '/COMMIT_EDITMSG';
var incorrectLogFile = commitMsgFile.replace('COMMIT_EDITMSG', 'logs/incorrect-commit-msgs');
var hasToString = function hasToString(x) {
return x && typeof x.toString === 'function';
};
fs.readFile(commitMsgFile, function(err, buffer) {
var msg = getCommitMessage(buffer);
if (!validateMessage(msg)) {
fs.appendFile(incorrectLogFile, msg + '\n', function() {
process.exit(1);
});
} else {
process.exit(0);
}
function getCommitMessage(buffer) {
return hasToString(buffer) && buffer.toString();
}
});
}
function getConfig() {
var pkgFile = findup.sync(process.cwd(), 'package.json');
var pkg = JSON.parse(fs.readFileSync(resolve(pkgFile, 'package.json')));
return pkg && pkg.config && pkg.config['validate-commit-msg'] || {};
}
function getGitFolder() {
var gitDirLocation = './.git';
if (!fs.existsSync(gitDirLocation)) {
throw new Error('Cannot find file ' + gitDirLocation);
}
if (!fs.lstatSync(gitDirLocation).isDirectory()) {
var unparsedText = '' + fs.readFileSync(gitDirLocation);
gitDirLocation = unparsedText.substring('gitdir: '.length).trim();
}
if (!fs.existsSync(gitDirLocation)) {
throw new Error('Cannot find file ' + gitDirLocation);
}
return gitDirLocation;
}