Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/Tools/gittools/pre-commit.py
Views: 1798
#!/usr/bin/env python12'''3A script suitable for use as a git pre-commit hook to ensure your4files are flake8-compliant before committing them.56Use this by copying it to a file called $ARDUPILOT_ROOT/.git/hooks/pre-commit78AP_FLAKE8_CLEAN9'''1011import os12import re13import sys14import subprocess151617class AP_PreCommit(object):1819@staticmethod20def progress(message):21print(f"***** {message}")2223@staticmethod24def has_flake8_tag(filepath):25with open(filepath) as fp:26return "AP_FLAKE8_CLEAN" in fp.read()2728def files_are_flake8_clean(self, files_to_check):29if files_to_check:30for path in files_to_check:31self.progress("Checking (%s)" % path)32try:33subprocess.check_output(["flake8"] + files_to_check, stderr=subprocess.STDOUT)34except subprocess.CalledProcessError as e:35self.progress(f"Flake8 check failed: ({e.output})")36return False37return True3839@staticmethod40def split_git_diff_output(output):41'''split output from git-diff into a list of (status, filepath) tuples'''42ret = []43if isinstance(output, bytes):44output = output.decode('utf-8')45for line in output.split("\n"):46if len(line) == 0:47continue48ret.append(re.split(r"\s+", line))49return ret5051def run(self):52# generate a list of files which have changes not marked for commit53output = subprocess.check_output([54"git", "diff", "--name-status"])55dirty_list = self.split_git_diff_output(output)56dirty = set()57for (status, dirty_filepath) in dirty_list:58dirty.add(dirty_filepath)5960# check files marked for commit:61output = subprocess.check_output([62"git", "diff", "--cached", "--name-status"])63output_tuples = self.split_git_diff_output(output)64files_to_check_flake8 = []65for output_tuple in output_tuples:66if len(output_tuple) > 2:67if output_tuple[0].startswith('R'):68# rename, check destination69(status, filepath) = (output_tuple[0], output_tuple[2])70else:71raise ValueError(f"Unknown status {output_tuple[0]}")72else:73(status, filepath) = output_tuple74if filepath in dirty:75self.progress("WARNING: (%s) has unstaged changes" % filepath)76if status == 'D':77# don't check deleted files78continue79(base, extension) = os.path.splitext(filepath)80if extension == ".py" and self.has_flake8_tag(filepath):81files_to_check_flake8.append(filepath)82if not self.files_are_flake8_clean(files_to_check_flake8):83return 184return 0858687if __name__ == '__main__':88precommit = AP_PreCommit()89sys.exit(precommit.run())909192