Last active
March 23, 2022 22:15
-
-
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`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Installation
$ mkdir -vp ${HOME}/.config/git/hooks
$ git config --global core.hookspath ${HOME}/.config/git/hooks
Place the above gist in the hooks directory you created above and name it as
prepare-commit-msg
Make sure the hook is executable
$ chmod u+x ${HOME}/.config/git/hooks/prepare-commit-msg
Usage
$ git commit -m "Some helpful new widget"
FOO-123 Some helpful new widget