#!/usr/bin/env python

import re
import sys
from argparse import ArgumentParser

sys.tracebacklimit = 0


TYPES = {
    "build": "changes that affect the build system or dependancies.",
    "ci": "changes to CI configuration files and scripts.",
    "docs": "changes to documentation.",
    "feat": "introduces a new feature.",
    "fix": "fixes a bug.",
    "perf": "changes that improve performance.",
    "refactor": "changes that neither fix bugs nor add features.",
    "revert": "changes that revert another commit.",
    "style": "changes that do not affect the meaning of the code.",
    "test": "changes to the test suite.",
}

PATTERN = re.compile(
    r"^(?P<type>{})(\([a-z ]+\))?: \w+.*$".format("|".join(TYPES.keys())),
    re.M,
)

EXCEPTION_MSG = """Non-conventional commit.

Commit message format:

    <type>[optional scope]: <description>

    [optional body]

    [optional footer]

Available types are:
{}
""".format(
    "\n".join([f"\t{k: <10}: {v}" for k, v in TYPES.items()]),
)


def parse_args():
    parser = ArgumentParser()
    parser.add_argument("commit")
    return parser.parse_args()


def main():
    args = parse_args()
    with open(args.commit) as f:
        msg = f.read()

    if not re.match(PATTERN, msg):
        raise Exception(EXCEPTION_MSG)


if __name__ == "__main__":
    main()
