-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprepare-commit-msg
75 lines (58 loc) · 2.54 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python
#
# Python script that implements a Git Hook of type Prepare Commit Message
# Author: Alexandre Pardo
# Date: 06/26/2019
#
from subprocess import check_output, Popen
import os, re, subprocess, sys
# First, we check if this is a NPM project
package_json_file_name = 'package.json'
is_npm_project = os.path.isfile(package_json_file_name)
if not is_npm_project: # Nothing to do
sys.exit(0)
# If this is a NPM project, we can move on
branch = 'master' # default
try:
# git symbolic-ref --short HEAD
branch = check_output(['git', 'symbolic-ref', '--short', 'HEAD']).strip()
except:
# if HEAD is not a symbolic ref, then we might be in a dettached state (not sure).
# As an error is thrown if we run this this during the rebase process, so we simply skip it.
# Also, if we couldn't safely read the branch name, this hook can't continue
print 'If you are running rebase or merge, you may ignore the message: fatal: ref HEAD is not a symbolic ref'
print 'Otherwise, you better check what is going on'
sys.exit(0)
# matches for branch names like:
# feature/issue-123
# feature/issue123
# hotfix/issue-123
# hotfix/issue123
regex = '(feature|hotfix)\/(\w+-\d+|\w+\d+)'
branch_match = re.match(regex, branch)
not_allowed_branches = ['master', 'dev', 'develop', 'staging', 'release']
merge_head_file_path = '.git/MERGE_HEAD'
is_merging = os.path.isfile(merge_head_file_path)
# First we check if we're not taking shortcuts ;)
if branch in not_allowed_branches and not is_merging:
print '======================WARNING====================='
print ' Direct commit to', branch, 'branch is not allowed'
print '=================================================='
sys.exit(1)
# If we're using the right branch name pattern,
# append the issue # in the beginning of the commit message
if branch_match <> None:
issue = branch_match.group(2)
commit_msg_filepath = sys.argv[1]
with open(commit_msg_filepath, 'r+') as fh:
commit_msg = fh.read()
formatted_issue = '[' + issue + ']'
starts_with_ticket = commit_msg.strip().startswith(formatted_issue)
if not starts_with_ticket:
fh.seek(0, 0)
fh.write('[%s] %s' % (issue, commit_msg))
else:
print '================================FRIENDLY REMINDER================================'
print '=Observe the branch pattern. Its prefix should be either "feature/" or "hotfix/"='
print '================================================================================='
print ':-)'