Skip to content

Apache DataFusion SQL Query Engine

ARROW-8846: [Dev][Python] Autoformat Python files with archery

Antoine Pitrou85804eb2bd32
diff --git a/dev/archery/archery/cli.py b/dev/archery/archery/cli.py
index 7227af7e0d..15c05a4039 100644
--- a/dev/archery/archery/cli.py
+++ b/dev/archery/archery/cli.py
@@ -258,7 +258,8 @@ lint_checks = [
LintCheck('clang-tidy', "Lint C++ files with clang-tidy."),
LintCheck('cpplint', "Lint C++ files with cpplint."),
LintCheck('iwyu', "Lint changed C++ files with Include-What-You-Use."),
- LintCheck('flake8', "Lint Python files with flake8."),
+ LintCheck('python',
+ "Format and lint Python files with autopep8 and flake8."),
LintCheck('numpydoc', "Lint Python files with numpydoc."),
LintCheck('cmake-format', "Format CMake files with cmake-format.py."),
LintCheck('rat',
diff --git a/dev/archery/archery/lang/python.py b/dev/archery/archery/lang/python.py
index 223354ec57..9b79971203 100644
--- a/dev/archery/archery/lang/python.py
+++ b/dev/archery/archery/lang/python.py
@@ -26,7 +26,7 @@ except ImportError:
else:
have_numpydoc = True
-from ..utils.command import Command, default_bin
+from ..utils.command import Command, capture_stdout, default_bin
class Flake8(Command):
@@ -34,6 +34,15 @@ class Flake8(Command):
self.bin = default_bin(flake8_bin, "flake8")
+class Autopep8(Command):
+ def __init__(self, autopep8_bin=None):
+ self.bin = default_bin(autopep8_bin, "autopep8")
+
+ @capture_stdout()
+ def run_captured(self, *args, **kwargs):
+ return self.run(*args, **kwargs)
+
+
def _tokenize_signature(s):
lines = s.encode('ascii').splitlines()
generator = iter(lines).__next__
diff --git a/dev/archery/archery/utils/command.py b/dev/archery/archery/utils/command.py
index 3ef6abe0bc..2e27f08667 100644
--- a/dev/archery/archery/utils/command.py
+++ b/dev/archery/archery/utils/command.py
@@ -25,7 +25,7 @@ from .logger import logger, ctx
def default_bin(name, default):
assert(default)
- env_name = "ARCHERY_%s_BIN".format(default.upper())
+ env_name = "ARCHERY_{0}_BIN".format(default.upper())
return name if name else os.environ.get(env_name, default)
diff --git a/dev/archery/archery/utils/lint.py b/dev/archery/archery/utils/lint.py
index d24f55b1a3..0101147b1d 100644
--- a/dev/archery/archery/utils/lint.py
+++ b/dev/archery/archery/utils/lint.py
@@ -17,6 +17,7 @@
import gzip
import os
+from pathlib import Path
import click
@@ -26,7 +27,7 @@ from .git import git
from .logger import logger
from ..lang.cpp import CppCMakeDefinition, CppConfiguration
from ..lang.rust import Cargo
-from ..lang.python import Flake8, NumpyDoc
+from ..lang.python import Autopep8, Flake8, NumpyDoc
from .rat import Rat, exclusion_from_globs
from .tmpdir import tmpdir
@@ -106,16 +107,61 @@ def cmake_linter(src, fix=False):
yield LintResult.from_cmd(cmake_format("--check"))
-def python_linter(src):
- """Run flake8 linter on python/pyarrow, and dev/. """
- logger.info("Running Python linters")
- flake8 = Flake8()
+def python_linter(src, fix=False):
+ """Run Python linters on python/pyarrow, python/examples, setup.py
+ and dev/. """
+ setup_py = os.path.join(src.python, "setup.py")
+ setup_cfg = os.path.join(src.python, "setup.cfg")
+
+ logger.info("Running Python formatter (autopep8)")
+
+ autopep8 = Autopep8()
+ if not autopep8.available:
+ logger.error(
+ "Python formatter requested but autopep8 binary not found. "
+ "Please run `pip install -r dev/archery/requirements-lint.txt`")
+ return
+ # Gather files for autopep8
+ patterns = ["python/pyarrow/**/*.py",
+ "python/pyarrow/**/*.pyx",
+ "python/pyarrow/**/*.pxd",
+ "python/pyarrow/**/*.pxi",
+ "python/examples/**/*.py",
+ "dev/archery/**/*.py",
+ ]
+ files = [setup_py]
+ for pattern in patterns:
+ files += list(map(str, Path(src.path).glob(pattern)))
+
+ args = ['--global-config', setup_cfg, '--ignore-local-config']
+ if fix:
+ args += ['-j0', '--in-place']
+ args += sorted(files)
+ yield LintResult.from_cmd(autopep8(*args))
+ else:
+ # XXX `-j0` doesn't work well with `--exit-code`, so instead
+ # we capture the diff and check whether it's empty
+ # (https://github.com/hhatto/autopep8/issues/543)
+ args += ['-j0', '--diff']
+ args += sorted(files)
+ diff = autopep8.run_captured(*args)
+ if diff:
+ print(diff.decode('utf8'))
+ yield LintResult(success=False)
+ else:
+ yield LintResult(success=True)
+
+ # Run flake8 after autopep8 (the latter may have modified some files)
+ logger.info("Running Python linter (flake8)")
+
+ flake8 = Flake8()
if not flake8.available:
- logger.error("Python linter requested but flake8 binary not found.")
+ logger.error(
+ "Python linter requested but flake8 binary not found. "
+ "Please run `pip install -r dev/archery/requirements-lint.txt`")
return
- setup_py = os.path.join(src.python, "setup.py")
yield LintResult.from_cmd(flake8(setup_py, src.pyarrow,
os.path.join(src.python, "examples"),
src.dev, check=False))
@@ -291,7 +337,7 @@ def docker_linter(src):
def linter(src, fix=False, *, clang_format=False, cpplint=False,
clang_tidy=False, iwyu=False, iwyu_all=False,
- flake8=False, numpydoc=False, cmake_format=False, rat=False,
+ python=False, numpydoc=False, cmake_format=False, rat=False,
r=False, rust=False, docker=False):
"""Run all linters."""
with tmpdir(prefix="arrow-lint-") as root:
@@ -311,8 +357,8 @@ def linter(src, fix=False, *, clang_format=False, cpplint=False,
iwyu_all=iwyu_all,
fix=fix))
- if flake8:
- results.extend(python_linter(src))
+ if python:
+ results.extend(python_linter(src, fix=fix))
if numpydoc:
results.extend(python_numpydoc())
diff --git a/dev/archery/archery/utils/rat.py b/dev/archery/archery/utils/rat.py
index ce78f9f8ed..e7fe19a7ea 100644
--- a/dev/archery/archery/utils/rat.py
+++ b/dev/archery/archery/utils/rat.py
@@ -36,7 +36,7 @@ class Rat(Jar):
@capture_stdout(strip=False)
def run_report(self, archive_path, **kwargs):
- return self.run("--xml", archive_path, **kwargs)
+ return self.run("--xml", archive_path, **kwargs)
def report(self, archive_path, **kwargs):
return RatReport(self.run_report(archive_path, **kwargs))
diff --git a/dev/archery/requirements-lint.txt b/dev/archery/requirements-lint.txt
index b1c02f6d99..fc7f339ed4 100644
--- a/dev/archery/requirements-lint.txt
+++ b/dev/archery/requirements-lint.txt
@@ -1,2 +1,3 @@
+autopep8
flake8
-cmake_format==0.5.2
\ No newline at end of file
+cmake_format==0.5.2