- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommit-msg
More file actions
Latest commit
executable file
·425 lines (343 loc) · 13.9 KB
/
Copy pathcommit-msg
File metadata and controls
executable file
·425 lines (343 loc) · 13.9 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#!/usr/bin/env python
"""
This script will try to enforce the tips given in
http://chris.beams.io/posts/git-commit/.
Line length violations will cause the commit to fail.
* The subject should be shorter than 50 characters
* The line length of the body should be shorter than 72 characters
The script will ensure the following rules, by inserting them in the message.
* Capitalize the subject line
* Remove any punctuation from the subject line
* Seperate the subject line and the body with an empty line
In case of a failed commit the commit message will be saved in the .git folder
in order to used as a templete in the next commit.
The first paramter given to the 'commit-msg' git hook is the name
of the file in which the commit message is stored in.
"""
importos
importsys
importsignal
importre
fromcollectionsimportOrderedDict
importconfig
frommessage_storeimportrun_cmd_output_lines, save
frompattern.enimportSentence, parse, mood
frompattern.enimportINDICATIVE, IMPERATIVE, CONDITIONAL, SUBJUNCTIVE
# If the commit is to fail, due to an incorrect formated commit message,
# the information of why is stored here.
FAIL_REASON= []
# If any fixups was done on to the message, information of what fixups are stored here.
FIXUPS= []
# Warnings are shown in the end to the user. Warnings are not cause for a failure
# and are not fixable either.
WARNINGS= []
COMMIT_MSG_PATH=sys.argv[1]
C_END="\033[0m"
C_RED="\033[91m"
C_BLUE="\033[96m"
C_GREEN="\033[92m"
C_YELLOW="\033[93m"
C_UNDERLINE="\033[4m"
defunderline(text):
"""
Returns the given text, but will be shown as underlined if print to the console.
"""
returnC_UNDERLINE+text.replace(C_END, C_END+C_UNDERLINE) +C_END
defred(text):
"""
Returns the given text, but will be shown as red if print to the console.
"""
returnC_RED+text.replace(C_END, C_END+C_RED) +C_END
defblue(text):
"""
Returns the given text, but will be shown as blue if print to the console.
"""
returnC_BLUE+text.replace(C_END, C_END+C_BLUE) +C_END
defgreen(text):
"""
Returns the given text, but will be shown as green if print to the console.
"""
returnC_GREEN+text.replace(C_END, C_END+C_GREEN ) +C_END
defyellow(text):
"""
Returns the given text, but will be shown as yellow if print to the console.
"""
returnC_YELLOW+text.replace(C_END, C_END+C_YELLOW) +C_END
defindent(text):
"""
Returns the given text, but every line is indented with one tab.
"""
return"\t"+text.replace("\n", "\n\t")
defmood_color_c(_mood):
"""
Returns the color prefix corresponding to the given mood.
"""
if_mood==IMPERATIVE:
returnC_GREEN
elif_mood==INDICATIVE:
returnC_BLUE
elif_mood==SUBJUNCTIVE:
returnC_RED
elif_mood==CONDITIONAL:
returnC_YELLOW
defmood_color(_mood):
"""
Returns the color function corresponding to the given mood.
"""
if_mood==IMPERATIVE:
returngreen
elif_mood==INDICATIVE:
returnblue
elif_mood==SUBJUNCTIVE:
returnred
elif_mood==CONDITIONAL:
returnyellow
defwait_for_input_matching(prompt, regex="[yn].*"):
"""
Prompts the user with the given prompt, until a input is
given that matches the given regex.
"""
sys.stdin=open('/dev/tty')
answer=raw_input(prompt).lower()
whilenotre.match(regex, answer):
answer=raw_input(prompt).lower()
returnanswer
defassert_subject_length(subject):
"""
Asserts that the subject line is shorter than config.SUBJECT_LINE_LENGTH_HARD_LIMIT.
Warns if above config.SUBJECT_LINE_LENGTH_WARNING.
"""
iflen(subject) >config.SUBJECT_LINE_LENGTH_HARD_LIMIT:
FAIL_REASON.append(
"* Too long line ("+red(str(len(subject))) +")! The subject line may not be "+
"longer than "+red(str(config.SUBJECT_LINE_LENGTH_HARD_LIMIT)) +" characters.")
eliflen(subject) >config.SUBJECT_LINE_LENGTH_WARNING:
WARNINGS.append(
"* Long subject line ("+blue(str(len(subject))) +"). The preferable length of the "+
"subject line is below "+green(str(config.SUBJECT_LINE_LENGTH_WARNING)) +", "+
"hard limit at "+red(str(config.SUBJECT_LINE_LENGTH_HARD_LIMIT)) +".")
defassert_body_line_length(lines):
"""
Asserts that the body lines are shorter than config.BODY_LINE_LENGTH_HARD_LIMIT characters.
Warns if above config.BODY_LINE_LENGTH_WARNING.
"""
warned=False
forlineinlines[1:]:
iflen(line) >config.BODY_LINE_LENGTH_HARD_LIMIT:
FAIL_REASON.append(
"* Too long line ("+red(str(len(line))) +")! No line of the body may contain "+
"more than "+green(str(config.BODY_LINE_LENGTH_HARD_LIMIT)) +" characters. ")
break
eliflen(line) >config.BODY_LINE_LENGTH_WARNINGandnotwarned:
warned=True# Only warn once.
WARNINGS.append(
"* Long line ("+blue(str(len(line))) +"). Line lengths above "+
green(str(config.BODY_LINE_LENGTH_WARNING)) +
" are discouraged, however the hard limit is "+
red(str(config.BODY_LINE_LENGTH_HARD_LIMIT)) +".")
defensure_subject_line_non_empty(lines):
"""
Ensures that the subject line is non empty.
If it is empty and there exist a next line, it is removed and a fixup message is added.
If it is empty and there does not exist a following line,
a fail reason is added and the commit will be aborted
"""
whilelen(lines) >0andre.match(r"^\s*$", lines[0]):
iflen(lines) >1:
lines.pop(0)
FIXUPS.append("* Removed the first line, it was all white space.")
else:
FAIL_REASON.append("* The commit message may not be empty.")
ifre.match(r"^\s+.+", lines[0]):
lines[0] =re.sub(r"^\s", "", lines[0])
FIXUPS.append("* Removed leading white space in subject line.")
defensure_capitalization(subject):
"""
Returns a correctly capitalized version of input subject line.
"""
ifsubject[0].islower():
FIXUPS.append("* Capitalized the subject line.")
returnsubject[0].upper() +subject[1:]
else:
returnsubject
defensure_punctuation(subject):
"""
Returns a subject line without trailing punctuations.
"""
whilesubject[-1] =='.'orsubject[-1] =='!'orsubject[-1] =='?':
FIXUPS.append(
"* Removed '"+subject[-1] +
"' from the end of the subject line, no need for punctuations in the subject line.")
subject=subject[0:-1]
returnsubject
defensure_subject_body_seperate(lines):
"""
Ensures that the subject line is seperated by a blank line.
The subject and the body needs to be seperated in order for
git to properly dicern them in the logs. Also i looks better.
"""
iflen(lines) >1andnotre.compile(r"^\s*$").match(lines[1]):
lines.insert(1, "")
FIXUPS.append("* Inserted an empty line between the subject and the body.")
defget_wordlist():
"""
If no wordlist is found one will be created.
"""
ifnotos.path.exists(os.path.expanduser(config.SPELL_CHECK_PERSONAL_WORDLIST)):
print"No person wordlist found, creating one "\
"at '"+config.SPELL_CHECK_PERSONAL_WORDLIST+"'"
wordlist=open(os.path.expanduser(config.SPELL_CHECK_PERSONAL_WORDLIST), 'a+')
wordlist.write("personal_ws-1.1 en 0\n")
else:
wordlist=open(os.path.expanduser(config.SPELL_CHECK_PERSONAL_WORDLIST), 'a')
returnwordlist
defdo_language_checks(message):
"""
Perform a spell check and a mood check and prompt the user
with the result if the result is negative.
"""
bad_mood_subject_line=False
bad_mood_sentence=False
bad_spelling_found=False
# Run spell checking, if enabled and available.
aspell=run_cmd_output_lines("which aspell")[0]
ifconfig.DO_SPELL_CHECKandaspell=="":
print"No `aspell` found, install it to enable spell check."
ifconfig.DO_SPELL_CHECKandnotaspell=="":
aspell_cmd="echo '"+message.replace("'", "'\\''") +"' | "+aspell+" list"
misspelled_words=set(run_cmd_output_lines(aspell_cmd)[:-1])
forwordinmisspelled_words:
message=re.sub(r"\b"+word+r"\b", underline(word), message)
bad_spelling_found=True
# Continue with mood check if enabled
ifconfig.DO_MOOD_CHECK:
mood_by_sentence=OrderedDict()
sentenceable_message=message
# The subject line might not contain any punctuation
# But should allways be treated as a sentence.
subject=message.split("\n", 1)[0]
iflen(subject) >0and (subject[-1] !="."orsubject[-1] !="!"orsubject[-1] !="?"):
sentenceable_message=message.replace(subject+"\n", subject+".\n", 1)
# Split on punctuation and start of bullet point
sentences=re.split(r"[.?!]|^\s?[-*]\s?", sentenceable_message)
forsentenceinsentences:
ifre.match(r"^\s*$", sentence):
continue
sent=Sentence(parse(sentence, lemmata=True))
mood_by_sentence[sentence] =mood(sent)
ifsentences[0] inmood_by_sentenceandmood_by_sentence[sentences[0]] !=IMPERATIVE:
bad_mood_subject_line=True
complete_message=""
forsent, sent_moodinmood_by_sentence.iteritems():
end=message.find(sent) +len(sent)
complete_message+=message[0:end].replace(sent, mood_color(sent_mood)(sent))
message=message[end:]
ifsent_mood==SUBJUNCTIVE:
bad_mood_sentence=True
message=complete_message
# Prompt the user with any errors found.
ifbad_mood_subject_lineorbad_mood_sentenceorbad_spelling_found:
count=1
prompt=""
ifbad_mood_subject_line:
prompt+=str(count) +". "
prompt+="The mood of the subject line should be "
prompt+=mood_color(IMPERATIVE)(IMPERATIVE)
prompt+=" not "
prompt+=mood_color(mood_by_sentence[sentences[0]])(mood_by_sentence[sentences[0]])
prompt+=".\n"
count+=1
ifbad_mood_sentence:
prompt+=str(count) +". "
prompt+="No sentence in the body of the message should be "
prompt+=mood_color(SUBJUNCTIVE)(SUBJUNCTIVE)
prompt+=".\n"
count+=1
ifbad_spelling_found:
prompt+=str(count) +". "
prompt+=underline("Underlnied")
prompt+=" some questionable spellings"
prompt+=" in the message.\n"
count+=1
print""
printprompt
print""
printindent(message)
print""
printmood_color(IMPERATIVE)(IMPERATIVE+" (command)")
printmood_color(INDICATIVE)(INDICATIVE+" (fact/belief)")
printmood_color(CONDITIONAL)(CONDITIONAL+" (conjecture)")
printmood_color(SUBJUNCTIVE)(SUBJUNCTIVE+" (opinion/wish)")
print""
ifbad_spelling_found:
print"To extend your dictionary enter "+green("add") +"."
answer=wait_for_input_matching("Would you like to continue anyway? ", regex="[yna].*")
else:
answer=wait_for_input_matching("Would you like to continue anyway? ")
ifanswer.startswith('n'):
save(ORIGINAL_MESSAGE)
sys.exit(1) # Aborts the commit.
elifanswer.startswith('a'):
wordlist=get_wordlist()
forwordinmisspelled_words:
add=wait_for_input_matching("Add "+green(word) +"? ")
ifadd.startswith('y'):
wordlist.write(word+"\n")
print"Added "+green(word)
print""
wordlist.close()
answer=wait_for_input_matching("Would you like to continue now? ")
ifanswer.startswith('n'):
save(ORIGINAL_MESSAGE)
sys.exit(1) # Aborts the commit.
defsignal_handler(signal, frame):
"""
Saves the commit message and kills the program with a
non zero exit code, which in turn will abort the commit.
"""
save(ORIGINAL_MESSAGE)
sys.exit(1)
signal.signal(signal.SIGINT, signal_handler)
MESSAGE_FILE=open(COMMIT_MSG_PATH, 'r')
ORIGINAL_MESSAGE=MESSAGE_FILE.read()
MESSAGE_FILE.close()
MESSAGE=re.sub(r"^#(?:\n|.)*", "", ORIGINAL_MESSAGE, flags=re.M)
LINES=MESSAGE.splitlines()
# If the commit message is empty git itself will dissmiss it.
ifnotLINES:
sys.exit(0)
# The subject is the first line of the commit message
ensure_subject_line_non_empty(LINES)
LINES[0] =ensure_capitalization(LINES[0])
LINES[0] =ensure_punctuation(LINES[0])
assert_subject_length(LINES[0])
# Check the body of the message
iflen(LINES) >1:
assert_body_line_length(LINES)
ensure_subject_body_seperate(LINES)
# Done with the asserts!
# Did we fail? We want to fail as early as possible.
ifFAIL_REASON:
# Save the message to be used in the next try.
save(ORIGINAL_MESSAGE)
print"COMMIT ABORTED!"
print"\n".join(FAIL_REASON)
print""
print"Please do try again, or add '--no-verify' to skip"
sys.exit(1) # Aborts the commit
# Spell check and check for bad moods.
do_language_checks(MESSAGE)
# Did we do any fixups to the message?
ifFIXUPSandconfig.DO_MESSAGE_FIXUP:
NEW_MESSAGE="\n".join(LINES)
MSG_FILE=open(COMMIT_MSG_PATH, 'w')
MSG_FILE.write(NEW_MESSAGE)
MSG_FILE.close()
print""
print"Did some fixups on the message for you:"
print"\n".join(FIXUPS)
print""
ifWARNINGSandconfig.PRINT_WARNINGS:
print"Friendly reminders:"
print"\n".join(WARNINGS)
print""