Skip to content

Instantly share code, notes, and snippets.

@StefanoChiodino
Last active January 5, 2023 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StefanoChiodino/e28a7709a462fc4393bf5c687b9fcba1 to your computer and use it in GitHub Desktop.
Save StefanoChiodino/e28a7709a462fc4393bf5c687b9fcba1 to your computer and use it in GitHub Desktop.
Prefix commit messages with Jira ticket ID
#!/usr/bin/env python3
""" Finds a Jira ticket ID from the branch name and prefixes the commit message with it.
It won't add it if it was already found in the message.
Warns if it can't find the ticket ID.
TO INSTALL
Copy this file into your .git/hooks folder for each local repository.
Make sure to make it executable with: chmod +x .git/hooks/prepare-commit-msg.
Test with an empty commit: git commit --allow-empty -m "test"
Reset this test commit moving back to its parent: git reset HEAD^
"""
import re
import subprocess
import sys
# Black on yellow 🐝.
TERMINAL_START_WARNING_COLOUR = "\x1b[6;30;43m"
TERMINAL_RESET_COLOUR = "\x1b[0m"
def main() -> None:
message_file_path = sys.argv[1]
branch_name = subprocess.check_output(
['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf-8').strip()
try:
ticket_id = re.search(r"(\w{3,}-\d+)", branch_name).group(1)
except AttributeError:
print(
f"{TERMINAL_START_WARNING_COLOUR}[WARNING]: Branch name '{branch_name}' does not contain a ticket ID in the form of \\w+-\\d+. "
f"See https://regex101.com/r/s29wJE/1 .{TERMINAL_RESET_COLOUR}")
sys.exit(0)
# Prefix the message with the ticket_id it not already there.
with open(message_file_path, 'r+') as f:
message = f.read()
if not re.search(ticket_id, message, re.IGNORECASE):
f.seek(0)
f.write(f"{ticket_id.upper()}: {message}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment