Skip to content

Instantly share code, notes, and snippets.

@alexander-arce
Last active April 20, 2020 17:07
Show Gist options
  • Save alexander-arce/7a36960cb83813caded026c55c8f4036 to your computer and use it in GitHub Desktop.
Save alexander-arce/7a36960cb83813caded026c55c8f4036 to your computer and use it in GitHub Desktop.
Prefix commit message
#!/usr/bin/env python
# Original code https://andy-carter.com/blog/automating-git-commit-messages-with-git-hooks
# Create hooks directory mkdir -p ~/.git/hooks
# Config global hook path git config --global core.hooksPath ~/.git/hooks/
# save as prepare-commit-msg
__author__ = "Alex Arce"
__email__ = "alexander.arce@pm.me"
__license__ = "GPL"
__version__ = "1.0"
__credits__ = "Frank Hofmann "
__status__ = "Production"
import re
import sys
from subprocess import check_output
# Calling hook
# ex. ['/home/user/.git/hooks/prepare-commit-msg', '.git/COMMIT_EDITMSG', 'message']
# path to file with commit description, ex. .git/COMMIT_EDITMSG
# Uncomment next lines for testing
# sys.argv = ['/home/alex/.git/hooks/prepare-commit-msg',
# '.git/COMMIT_EDITMSG', 'message']
commit_msg_filepath = sys.argv[1]
# Get branch, ex. feature/issue_100
branch = check_output(['git', 'symbolic-ref', '--short',
'HEAD']).strip().decode('utf-8')
regex = '(?P<issue_name>feature|hotfix|bugfix|support)\/(?P<issue_branch>\w+(_|-)(?P<issue_number>\d+))'
match = re.match(regex, branch)
if match:
issue_number = match.group('issue_number')
issue_branch = match.group('issue_branch')
with open(commit_msg_filepath, 'r+') as fh:
commit_msg = fh.read()
fh.seek(0, 0)
output = F"[{issue_branch}] {commit_msg} refs #{issue_number}"
# print(output)
fh.write(output)
elif branch != 'master' and branch != 'develop':
print('Incorrect branch name, are you run `git flow init`?')
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment