Skip to content

Instantly share code, notes, and snippets.

@mjuarez
Last active March 23, 2022 22:15
Show Gist options
  • Save mjuarez/a11bfdc4033378c86c15abe1f7e67114 to your computer and use it in GitHub Desktop.
Save mjuarez/a11bfdc4033378c86c15abe1f7e67114 to your computer and use it in GitHub Desktop.
A git hook for prefixing commit messages with local branch names that are prefixed with Jira issue IDs. To be used as `prepare-commit-msg`
#!/usr/bin/env python3
import sys
import subprocess
import re
jira_pattern = re.compile(r'^\w+-\d+')
result = subprocess.run(['git', 'symbolic-ref', '--short', 'HEAD'], stdout=subprocess.PIPE)
if result.returncode == 0:
git_output = result.stdout.decode('utf-8')
discovered_branch_issue = jira_pattern.match(git_output)
if len(sys.argv) > 0:
with open(sys.argv[1], 'r+') as commit_file:
commit_msg = commit_file.read()
discovered_commit_issue = jira_pattern.match(commit_msg)
new_commit_msg = None
if discovered_branch_issue:
if discovered_commit_issue:
if discovered_branch_issue.group(0) != discovered_commit_issue.group(0):
sys.stderr.write("Rewriting commit message...\n")
new_commit_msg = jira_pattern.sub(discovered_branch_issue.group(0), commit_msg)
else:
new_commit_msg = "%s %s" % (discovered_branch_issue.group(0), commit_msg)
if new_commit_msg:
commit_file.seek(0)
commit_file.write(new_commit_msg)
commit_file.truncate()
@mjuarez
Copy link
Author

mjuarez commented Apr 2, 2021

Installation

  1. Create a hooks directory
$ mkdir -vp ${HOME}/.config/git/hooks
  1. Configure global git config to point to hookspath
$ git config --global core.hookspath ${HOME}/.config/git/hooks
  1. Place the above gist in the hooks directory you created above and name it as prepare-commit-msg

  2. Make sure the hook is executable

$ chmod u+x ${HOME}/.config/git/hooks/prepare-commit-msg

Usage

  1. In your local working copy, create a new branch prefixed with a Jira issue ID.
$ git checkout -b FOO-123/my-feature
  1. Try committing a message without the Jira ID
$ git commit -m "Some helpful new widget"
  1. Confirm that your commit message was rewritten to FOO-123 Some helpful new widget
$ git log -1

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