Skip to content

Instantly share code, notes, and snippets.

@piotrgredowski
Last active September 13, 2022 20:57
Show Gist options
  • Save piotrgredowski/d5b6cd227480ebd0f693e5578261544a to your computer and use it in GitHub Desktop.
Save piotrgredowski/d5b6cd227480ebd0f693e5578261544a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# NOTE: Put it as your global prepare-commit-msg hook.
# Usually at `~/.git-templates/hooks/prepare-commit-msg`.
# REMEMBER to make it executable with `chmod +x ~/.git-templates/hooks/prepare-commit-msg`.
#
# After that all new repositories should have this hook installed.
# In existing repos you need to run `git init` to apply this hook.
import re
import sys
from subprocess import CalledProcessError, check_output
def get_branch_name():
try:
return (
check_output(["git", "symbolic-ref", "--short", "HEAD"])
.strip()
.decode("utf-8")
)
except CalledProcessError:
sys.exit(0)
def get_commit_msg(commit_msg_filepath):
return open(commit_msg_filepath).read()
def get_commit_msg_with_item_number(branch_name, commit_msg):
regex = r"(\d+)[\-\_]"
if not re.findall(regex, branch_name):
return commit_msg
try:
item_number = re.findall(regex, branch_name)[0]
except IndexError:
return commit_msg
item_text = f"Related item: #{item_number}"
text_to_add = f"\n\n{item_text}\n\n"
if item_text in commit_msg:
return commit_msg
splitter = "# "
try:
first_part, second_part = commit_msg.split(splitter, maxsplit=1)
second_part = splitter + second_part
return first_part.strip() + text_to_add + second_part.strip()
except ValueError:
pass
return f"{commit_msg}{text_to_add}"
def save_commit_msg(new_commit_msg, commit_msg_filepath):
with open(commit_msg_filepath, "r+") as f:
f.seek(0, 0)
f.write(new_commit_msg)
if __name__ == "__main__":
branch_name = get_branch_name()
commit_msg_filepath = sys.argv[1]
commit_msg = get_commit_msg(commit_msg_filepath)
new_commit_msg = get_commit_msg_with_item_number(
branch_name=branch_name, commit_msg=commit_msg
)
if new_commit_msg:
save_commit_msg(
new_commit_msg=new_commit_msg, commit_msg_filepath=commit_msg_filepath
)
@piotrgredowski
Copy link
Author

Fixed few things. Now it will work also if you commit using fx. VSCode

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