#!/usr/bin/env python
##
# @author Oscar de Felice
# @email oscar.defelice@gmail.com
# @title Git hook for enforcing conventional commit spec
#
# @todo Create folder ~/.git-templates and set that value to init.templatedir git config key globally.
# @todo Copy this script to ~/.git-templates/hooks/ and rename it to commit-msg.
# @todo (Linux): Make the script executable.
import re
import argparse

examples = """+ 61c8ca9 fix: Solve navbar not responsive on mobile
+ 479c48b test: Prepare test cases for user authentication
+ a992020 chore: Move to semantic versioning
+ b818120 fix: Fix button click event handler firing twice
+ c6e9a97 fix: Add login page css
+ dfdc715 feat(auth): Add social login using twitter
"""

parser = argparse.ArgumentParser(
	description="Enforces conventional git commit messages.\nRead more at https://www.conventionalcommits.org/en/v1.0.0/")
parser.add_argument("filename", help="name of the file", type=str, )
args = parser.parse_args()

pattern = r'(build|ci|docs|feat|fix|perf|refactor|style|test|test-fix|chore|revert)(\([\w\-]+\))?:\s([A-Z].*)'

def main():
	
	with open(args.filename, 'r') as fp:
		commit_message = fp.read()
	
	result = re.match(pattern, commit_message)

	if not result:
		print("\nCOMMIT FAILED!")
		print("\nPlease enter commit message in the conventional format and try to commit again. Examples:")
		print("\n" + examples)
		print("\n" + "Note that the commit message must start with a capital letter.")

		raise Exception("Conventional commit validation failed")

if __name__ == "__main__":
	main()