Skip to content

Instantly share code, notes, and snippets.

@dsteinberger
Last active May 26, 2021 12:48
Show Gist options
  • Save dsteinberger/f11068e27f83ade0038a4a2bbb297443 to your computer and use it in GitHub Desktop.
Save dsteinberger/f11068e27f83ade0038a4a2bbb297443 to your computer and use it in GitHub Desktop.
Prefill the commit message by the branch name
#!/usr/bin/env python3
# Prefill the commit message + create changelog file by the branch name
# eg.:
# branch-name = PRO-<num ticket>-<type ticket>-<main subject>-<message>
# Type ticket: can be bugfix, tech, enhancement, other
# Eg.: PRO-1234-tech-document-split-size
# --> commit message: Refs #PRO-1234 - document: split size
# --> create file: PRO-1234-tech-document-split-size.tech
# Document: split size (#PRO-1234)
# Global Setup
# - create a `~/.git/hooks` folder
# - create the `prepare-commit-msg` hook file in this folder and paste this
# script
# - chmod +x ~/.git/hooks/prepare-commit-msg
# - make git use this folder `git config --global core.hooksPath ~/.git/hooks`
# - allow for emtpy commit message: git commit --allow-empty-message (you can
# create an alias)
import re
import sys
import subprocess
if __name__ == '__main__':
try:
branch_name = subprocess.check_output(
["git", "symbolic-ref", "--short", "HEAD"]).decode()
except subprocess.CalledProcessError:
branch_name = None
if not branch_name:
sys.exit()
branch_name = branch_name.replace('\n', ' ')
list_type = ["bugfix", "tech", "enhancement", "other"]
result = re.match(
"(?P<pro>PRO)-(?P<num>\d*)-(?P<type>({}))-(?P<app>\w*)-(?P<message>.*)".format("|".join(list_type)),
branch_name)
if result:
num_commit = result.group("num")
app = result.group("app")
message = result.group("message").replace('-', ' ')
type = result.group("type")
# Set changelog message
changelog_message = "{}: {} (#PRO-{})".format(
app.title(), message, num_commit)
# Create changelog file
try:
subprocess.Popen(
["bin/changelog", "add", type, changelog_message])
except subprocess.CalledProcessError:
print("Error create changelog")
sys.exit()
# Create commit message
commit_messsage = "Refs #PRO-{} - {}: {}".format(
num_commit, app, message)
# Open, check and writte commit message
commit_filepath = sys.argv[1]
with open(commit_filepath, 'r+') as cf:
# If first line has no message: exit program (avoid `git commit
# --amend)
if not cf.readline().strip():
cfr = cf.read()
cf.seek(0)
cf.write('{}\n\n'.format(commit_messsage) + cfr)
@dsteinberger
Copy link
Author

Error message when rebase, we check HEAD and we are in detached HEAD... remove the message if possible

fatal: ref HEAD is not a symbolic ref

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