Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kikoso/ee3084a3bc351e45bd74555fe4b05f04 to your computer and use it in GitHub Desktop.
Save kikoso/ee3084a3bc351e45bd74555fe4b05f04 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#
# Extract the ticket's id from the branch name and add it
# to the commit message. Adapted from:
# https://andy-carter.com/blog/automating-git-commit-messages-with-git-hooks
# Parameters are explained here:
# https://git-scm.com/docs/githooks#_prepare_commit_msg
import re
import sys
from subprocess import check_output
from typing import Optional
def extract_issue_from_branch_name() -> Optional[str]:
branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], text=True).strip()
match = re.match('(feature|bugfix|hotfix)/(\\w+-\\d+)', branch)
if match:
return match.group(2)
else:
return None
def conform_to_commit_template(commit_msg_filepath: str, issue_id: str):
with open(commit_msg_filepath, 'r') as fh:
commit_msg = fh.readlines()
# no modification if a line starts with the id (no position check)
if any(line.startswith(issue_id) for line in commit_msg):
return
# Add the issue id below the possibly existing commit message,
# but above the generated comment block listing the changes.
last_content_line_index = -1
for index, line in enumerate(commit_msg):
if line.strip() and not line.startswith('#'):
last_content_line_index = index
if last_content_line_index == -1:
commit_msg.insert(0, '\n')
last_content_line_index = 0
commit_msg.insert(last_content_line_index + 1, '\n')
commit_msg.insert(last_content_line_index + 2, issue_id + '\n')
# delete extra blank lines after the issue id
extra_blank_lines = 0
index_after_id = last_content_line_index + 3
for i in range(index_after_id, len(commit_msg)):
if not commit_msg[i].strip():
extra_blank_lines += 1
if extra_blank_lines > 0:
del commit_msg[index_after_id:index_after_id + extra_blank_lines]
# override the whole file
with open(commit_msg_filepath, 'w') as fh:
fh.writelines(commit_msg)
msg_filepath = sys.argv[1]
issue = extract_issue_from_branch_name()
if issue:
conform_to_commit_template(msg_filepath, issue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment