Skip to content

Instantly share code, notes, and snippets.

@kevindb
Last active June 13, 2025 16:57
Show Gist options
  • Select an option

  • Save kevindb/a360c8e90bcdf6364f1523a5787c8d89 to your computer and use it in GitHub Desktop.

Select an option

Save kevindb/a360c8e90bcdf6364f1523a5787c8d89 to your computer and use it in GitHub Desktop.
Prepend commit message with ticket number from branch name
#!/usr/bin/env python3
# https://gist.github.com/kevindb/a360c8e90bcdf6364f1523a5787c8d89
import sys, re
from subprocess import check_output
commit_msg_filepath = sys.argv[1]
branch = check_output(['git', 'branch', '--show-current']).decode('utf-8').strip()
# Branch name is empty if in detached HEAD state (e.g. rebase)
if len(branch) > 0:
# Regex breakdown:
# ^ # Start of string
# (?:(feature|hotfix|bugfix|epic)/)? # Optional group for prefix and slash
# (\w+-\d+) # JIRA-style issue key (e.g. ENG-1000)
regex = r'^(?:(feature|hotfix|bugfix|epic)/)?(\w+-\d+)'
match = re.match(regex, branch)
if match:
issue = match.group(2)
with open(commit_msg_filepath, 'r+') as fh:
commit_msg = fh.read()
fh.seek(0, 0)
fh.write(f"[{issue}] {commit_msg}")
else:
print("Incorrect branch name.")
print("Please use the format <feature|epic|hotfix|bugfix>/<ticket number> [-additional-description] or <ticket number>")
print("e.g. 'feature/ENG-1000', 'hotfix/ENG-2500-this-is-the-fix', or just 'ENG-1000'")
sys.exit(1)
@xorspark
Copy link

Python3 version in case you don't have v2 installed or python is pointing to python3 in your environment.

import sys, re
from subprocess import check_output

commit_msg_filepath = sys.argv[1]

branch = check_output(['git', 'branch', '--show-current']).decode('utf-8')

# Branch name is empty if in detached HEAD state (e.g. rebase)
if len(branch) > 0 : 
    regex = '(feature|hotfix|bugfix|epic)\/(\w+-\d+)'

    if re.match(regex, branch):
        issue = re.match(regex, branch).group(2)
        with open(commit_msg_filepath, 'r+') as fh: 
            commit_msg = fh.read()
            fh.seek(0, 0)
            fh.write(f'[{issue}] {commit_msg}')
    else:
        print('Incorrect branch name.')
        print('Please use the format <feature|epic|hotfix|bugfix>/<ticket number> [-additional-description]')
        print("e.g. 'feature/CP-1000' or 'hotfix/CP-2500-this-is-the-fix'")
        sys.exit(1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment