-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprepare-commit-msg
executable file
·55 lines (45 loc) · 1.72 KB
/
prepare-commit-msg
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
#!/usr/bin/env python3
import sys
import subprocess
import hooks_cfg as cfg
pcm_cfg = cfg.checks_cfg['prepare-commit-message']
def get_branchname():
"""Get current branch name."""
# print('before')
try:
branchname = subprocess.check_output(
# -q suppress error message for non-symbolic (detached) ref.
['/usr/bin/git', 'symbolic-ref', '-q', '--short', 'HEAD'])
except subprocess.CalledProcessError as e:
# When `fatal: ref HEAD is not a symbolic ref`. It would return
# code 128 indicating this, but because we are using `-q`
# it does return generic error code 1.
if e.returncode == 1:
return False
else:
raise
# Convert to string.
branchname = branchname.decode('utf-8')
return branchname.strip()
def prepend_commit_msg(text, prefix='', suffix=''):
"""Prepend commit message with text."""
with open(sys.argv[1], 'r+') as f:
msg = f.read()
# Prepend only if message is empty or message does not contain
# same text already and start of message is either new line or
# comment.
if not msg or (text not in msg and msg[0] in ('\n', '#')):
# Point to start of file.
f.seek(0)
f.write(prefix+text+suffix+msg)
# Truncate to overwrite file.
f.truncate()
# We prefix with two empty lines to have commit message look like this
# (when initially message is empty):
#
#
# [BRANCH] BRANCH_NAME
# Check if branch should be excluded to not update its commit message.
branchname = get_branchname()
if branchname and branchname not in pcm_cfg['exclude_branches']:
prepend_commit_msg('[BRANCH] %s' % branchname, prefix='\n\n')