Skip to content

Instantly share code, notes, and snippets.

@Foair
Last active July 28, 2022 12:05
Show Gist options
  • Save Foair/e92de825c2d12d2e4c40e6d8a2ca8955 to your computer and use it in GitHub Desktop.
Save Foair/e92de825c2d12d2e4c40e6d8a2ca8955 to your computer and use it in GitHub Desktop.

PowerShell:

git init; ni -ItemType SymbolicLink -Target "prepare-commit-msg" .git\hooks\prepare-commit-msg

Bash:

curl -Lo .git/hooks/prepare-commit-msg https://gist.github.com/
chmod +x .git/hooks/prepare-commit-msg
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Automatically Prefixing Git Commit Messages with an Issue Number From the Current Branch Name
https://andy-carter.com/blog/automating-git-commit-messages-with-git-hooks
"""
import sys, re
from subprocess import check_output
emoji_map = {
'build': '๐Ÿ“ฆ',
'ci': '๐Ÿฌ',
'docs': '๐Ÿ“ƒ',
'feat': '๐Ÿ”ฎ',
'fix': '๐Ÿฉบ',
'perf': '๐Ÿฆพ',
'refactor': '๐Ÿงน',
'style': '๐Ÿ’…',
'test': '๐Ÿงช',
'new': '๐ŸŽ€'
}
commit_msg_filepath = sys.argv[1]
# branch = check_output(['git', 'symbolic-ref', '--short', 'HEAD']).strip()
# regex = '(feature|hotfix)/(\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))
# elif branch != 'master' and branch != 'dev':
# print 'Incorrect branch name'
# sys.exit(1)
with open(commit_msg_filepath, 'r+', encoding='utf-8') as f:
commit_msg = f.read()
prefix = commit_msg.split(' ')[0].strip()
if prefix in emoji_map.values():
sys.exit(0)
if not prefix in emoji_map:
print('Prefix must be in:', ', '.join(list(emoji_map.keys())))
sys.exit(1)
emoji = emoji_map[prefix]
commit_msg = commit_msg.replace(prefix, emoji)
if prefix == 'new':
commit_msg = emoji + ' hello world'
commit_msg = commit_msg.strip()
commit_msg += '\n'
with open(commit_msg_filepath, 'wb') as f:
f.write(commit_msg.encode('utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment