Skip to content

Instantly share code, notes, and snippets.

@franksteinberg
Forked from kevindb/prepare-commit-msg
Created February 10, 2021 21:19
Show Gist options
  • Save franksteinberg/402c1e5c275043f736949b6872bb732c to your computer and use it in GitHub Desktop.
Save franksteinberg/402c1e5c275043f736949b6872bb732c to your computer and use it in GitHub Desktop.
Prepend commit message with ticket number from branch name
#!/usr/bin/env python
# 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'])
# 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('[%s] %s' % (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)
@franksteinberg
Copy link
Author

Installation

Create file .git/hooks/prepare-commit-msg (no extension), paste the script and make the file executable.

Usage

For instance with branch feature/ARQ-123
$ git commit -m 'Fixed bug'
will result with commit '[ARQ-653] Fixed bug'
Branch name must be in the format: <feature|epic|hotfix|bugfix>/<ticket number> [-additional-description]
Script handles branching name which is for example used in git-flow. Eg for branch 'hotfix/ABC-399' it will extract ABC-399

Examples

Branch Name Commit Prefix
feature/ARQ-123 [ARQ-123]
epic/ARQ-123-add-login-form [ARQ-123]
hotfix/ARQ-123/fixes-the-thing [ARQ-123]
epic/ARQ-123-authentication [ARQ-123]
ARQ-123 Invalid branch name

NOTE: This enforces a branching convention used at MY company, which is that ALL commits are made to a feature branch, a hotfix branch, a bugfix branch, or an epic branch. If you do not use this convention, you may remove (or modify) the else block from lines 23-27. The result would be that nothing would be prefixed to your commit message.

Credits:

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