Skip to content

Instantly share code, notes, and snippets.

@DusanMadar
Last active September 7, 2018 11:06
Show Gist options
  • Save DusanMadar/e894239efc0847796162f3a791972d82 to your computer and use it in GitHub Desktop.
Save DusanMadar/e894239efc0847796162f3a791972d82 to your computer and use it in GitHub Desktop.
Git hook to auto prefix commit message with story/feature ID/name.
#!/usr/bin/env python
"""
Copy-paste this to `.git/hooks/prepare-commit-msg` and make the file executable.
Then just write your commit message as `git commit -m "message"`.
"""
from subprocess import check_output
import sys
# Set your feature branch prefix here.
FEATURE_BRANCH_PREFIX = 'feature/'
def get_branch_name():
# Credits: https://stackoverflow.com/a/11868440/4183498.
return check_output('git symbolic-ref --short HEAD'.split()).strip()
def get_commit_prefix():
branch_name = get_branch_name()
if FEATURE_BRANCH_PREFIX not in branch_name:
return ''
# Assuming feature branch name format `<prefix>myfeature-123-description`.
branch_name_parts = branch_name.split(FEATURE_BRANCH_PREFIX)
# Will extract `myfeature-123`.
feature_id = '-'.join(branch_name_parts[-1].split('-', 2)[:2])
return feature_id + ': '
def prefix_commit_message(commit_message_file):
commit_prefix = get_commit_prefix()
if not commit_prefix:
return
with open(commit_message_file, 'r') as commit_message:
lines = commit_message.readlines()
lines[0] = commit_prefix + lines[0]
with open(commit_message_file, 'w') as commit_message:
commit_message.write(''.join(lines))
if __name__ == '__main__':
prefix_commit_message(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment