summaryrefslogtreecommitdiff
path: root/tools/linter.py
diff options
context:
space:
mode:
authorRalf Gommers <ralf.gommers@gmail.com>2021-03-07 17:14:29 +0100
committerGitHub <noreply@github.com>2021-03-07 17:14:29 +0100
commitb88ab10e9f626d725dfd356e482b686de0bd7d17 (patch)
tree35a48632e3806c90b3d6df292b2efa65a205c9c0 /tools/linter.py
parent0bcf690951899608db2ab8aa6aebebbe6723b307 (diff)
parenteb9bc0e8e564f39c7f9167b731ed12b21f5205a7 (diff)
downloadnumpy-b88ab10e9f626d725dfd356e482b686de0bd7d17.tar.gz
Merge pull request #18423 from ganesh-k13/enh_lint
ENH: Lint checks for PR diffs
Diffstat (limited to 'tools/linter.py')
-rw-r--r--tools/linter.py71
1 files changed, 71 insertions, 0 deletions
diff --git a/tools/linter.py b/tools/linter.py
new file mode 100644
index 000000000..2952e91ed
--- /dev/null
+++ b/tools/linter.py
@@ -0,0 +1,71 @@
+import os
+import sys
+import subprocess
+from argparse import ArgumentParser
+from git import Repo, exc
+
+CONFIG = os.path.join(
+ os.path.abspath(os.path.dirname(__file__)),
+ 'lint_diff.ini',
+)
+
+
+class DiffLinter:
+ def __init__(self, branch):
+ self.branch = branch
+ self.repo = Repo('.')
+ self.head = self.repo.head.commit
+
+ def get_branch_diff(self, uncommitted = False):
+ """
+ Determine the first common ancestor commit.
+ Find diff between branch and FCA commit.
+ Note: if `uncommitted` is set, check only
+ uncommitted changes
+ """
+ try:
+ commit = self.repo.merge_base(self.branch, self.head)[0]
+ except exc.GitCommandError:
+ print(f"Branch with name `{self.branch}` does not exist")
+ sys.exit(1)
+
+ if uncommitted:
+ diff = self.repo.git.diff(self.head, '--unified=0', '***.py')
+ else:
+ diff = self.repo.git.diff(commit, self.head,
+ '--unified=0', '***.py')
+ return diff
+
+ def run_pycodestyle(self, diff):
+ """
+ Original Author: Josh Wilson (@person142)
+ Source:
+ https://github.com/scipy/scipy/blob/master/tools/lint_diff.py
+ Run pycodestyle on the given diff.
+ """
+ res = subprocess.run(
+ ['pycodestyle', '--diff', '--config', CONFIG],
+ input=diff,
+ stdout=subprocess.PIPE,
+ encoding='utf-8',
+ )
+ return res.returncode, res.stdout
+
+ def run_lint(self, uncommitted):
+ diff = self.get_branch_diff(uncommitted)
+ retcode, errors = self.run_pycodestyle(diff)
+
+ errors and print(errors)
+
+ sys.exit(retcode)
+
+
+if __name__ == '__main__':
+ parser = ArgumentParser()
+ parser.add_argument("--branch", type=str, default='main',
+ help="The branch to diff against")
+ parser.add_argument("--uncommitted", action='store_true',
+ help="Check only uncommitted changes")
+ args = parser.parse_args()
+
+ DiffLinter(args.branch).run_lint(args.uncommitted)