Skip to content

Instantly share code, notes, and snippets.

@jbruchanov
Last active July 22, 2022 12:38
Show Gist options
  • Save jbruchanov/36fdc3ee99d479947f365caeec1095d5 to your computer and use it in GitHub Desktop.
Save jbruchanov/36fdc3ee99d479947f365caeec1095d5 to your computer and use it in GitHub Desktop.
Windows git prepare-commit-msg hook starting python script
//be sure your hook folder is correct
//`git config core.hooksPath`
//or set it `git config core.hooksPath .git/hooks`
//be sure the sh.exe exists and it's correct
//file:prepare-commit-msg
#!C:/Program\ Files/Git/usr/bin/sh.exe
python ".git/hooks/prepare-commit-msg.py" "$1"
exit 0
//endfile:prepare-commit-msg
//script takes for example branch name `task/TKT-123_abc_deef` -> changes 'commit message' to 'TKT-123: commit message'
//file:prepare-commit-msg.py
import sys
import subprocess
import re
# Ignore if it's not a simple commit: rebase, merge and so on
# We only need to apply this hook when "git commit" command was performed
if len(sys.argv) != 2:
exit()
path = sys.argv[1]
with open(path, "r") as file:
lines = file.readlines()
if len(lines) == 0:
exit()
branch_name = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode()
branch_name_parts = branch_name.split("/")
if len(branch_name_parts) != 2:
exit()
re_result = re.search(".*-\d+", branch_name_parts[1])
if re_result is None:
exit()
jira_id = re_result.group(0)
lines[0] = "{0}: {1}\n".format(jira_id, lines[0])
with open(path, "w") as file:
file.writelines(lines)
//endfile:prepare-commit-msg.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment