#!/usr/bin/python import os.path import re import sys import tempfile def main(): # pragma: no cover commit_file_name = sys.argv[1] if CommitFileIsValid(commit_file_name): sys.exit(0) tmp_dir = tempfile.mkdtemp() rejected_file_name = os.path.join(tmp_dir, 'commit_msg') with open(commit_file_name, 'rb') as src, open(rejected_file_name, 'wb') as dst: while True: buffer_size = 2**20 copy_buffer = src.read(buffer_size) if not copy_buffer: break dst.write(copy_buffer) print("Commit message saved in {}".format(rejected_file_name)) print("Fix the commit and try again with:") print("git commit -F {}".format(rejected_file_name)) print("Aborting Commit.") sys.exit(1) def CommitFileIsValid(commit_file_name): with open(commit_file_name) as commit_file: subject_line = commit_file.readline() if not SubjectIsValid(subject_line): print("Subject: '" + subject_line.strip() + "'") print("Subject is not formatted correctly. See .gitmessage.") return False label = LabelFromSubject(subject_line) if not LabelIsValid(label): print("Label for subject ({}) is not valid See .gitmessage.".format( label)) return False blank_line = commit_file.readline() if not LineIsBlank(blank_line): print("'{}'".format(blank_line)) print("Separate the subject from the body with a blank line. " + "See .gitmessage.") return False for line in commit_file: if not LineLengthIsValid(line): print( "'{}'".format(line) + "Lines in body text should be 72 characters or less. " + "See .gitmessage") return False return True def SubjectIsValid(subject): subject = subject.strip() if SubjectIsBlank(subject): return False if SubjectIsMerge(subject): return True if not SubjectHasLabel(subject): return False if not SubjectLengthIsValid(subject): return False return True def SubjectIsBlank(subject): if not subject: print('Subject line is empty.') return True return False def SubjectIsMerge(subject): if ( subject.startswith('Merge pull') or subject.startswith('Merge branch') ): return True return False def SubjectHasLabel(subject): label_format = re.compile(r"[a-zA-Z][a-z]*:") if not label_format.match(subject): print('Subject should be in the form of "