Apache DataFusion SQL Query Engine
ARROW-5802: [CI][Archery] Dockerify lint utilities
François Saint-Jacquesc6b060634ab6
diff --git a/.github/workflows/linux-docker-compose.yml b/.github/workflows/linux-docker-compose.ymlindex 5834241805..4431ce5cf6 100644--- a/.github/workflows/linux-docker-compose.yml+++ b/.github/workflows/linux-docker-compose.yml@@ -27,6 +27,7 @@ jobs:label:- C++ w/ clang-7 & system packages- Rust+ - Lint, Release testsinclude:- label: C++ w/ clang-7 & system packagesimage: cpp-system-deps@@ -36,6 +37,11 @@ jobs:image: rustskip_expression: |${ARROW_CI_RUST_AFFECTED} != "1"+ - label: Lint, Release tests+ image: lint+ # Don't skip+ skip_expression: |+ "1" != "1"runs-on: ubuntu-18.04steps:- uses: actions/checkout@masterdiff --git a/ci/docker/Dockerfile.lint b/ci/docker/Dockerfile.lintnew file mode 100644index 0000000000..d24e93c14a--- /dev/null+++ b/ci/docker/Dockerfile.lint@@ -0,0 +1,57 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++FROM hadolint/hadolint:v1.17.2 AS hadolint++FROM ubuntu:18.04++SHELL ["/bin/bash", "-o", "pipefail", "-c"]++RUN apt-get update && \+ apt-get install -y -q \+ build-essential \+ clang-7 \+ clang-format-7 \+ clang-tidy-7 \+ clang-tools-7 \+ cmake \+ curl \+ git \+ libclang-7-dev \+ ninja-build \+ openjdk-11-jdk-headless \+ python3 \+ python3-dev \+ python3-pip \+ ruby \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists/*++# Use python3 by default in scripts+RUN ln -s /usr/bin/python3 /usr/local/bin/python+RUN pip3 install flake8 cmake_format==0.5.2++# Rust linter+RUN curl https://sh.rustup.rs -sSf | \+ sh -s -- --default-toolchain stable -y+ENV PATH /root/.cargo/bin:$PATH+RUN rustup component add rustfmt++# Docker linter+COPY --from=hadolint /bin/hadolint /usr/bin/hadolint++CMD ["/arrow/ci/docker/lint.sh"]diff --git a/dev/lint/run_clang_tidy.sh b/ci/docker/lint.shsimilarity index 82%rename from dev/lint/run_clang_tidy.shrename to ci/docker/lint.shindex 8068e2c1a4..18e2bb8a5d 100755--- a/dev/lint/run_clang_tidy.sh+++ b/ci/docker/lint.sh@@ -16,10 +16,15 @@# specific language governing permissions and limitations# under the License.-set -ex+set -eu-mkdir -p /build/lint-pushd /build/lint- cmake -GNinja /arrow/cpp- ninja check-clang-tidy-popd+: ${ARROW_HOME:=/arrow}++install_archery() {+ pip3 install -e ${ARROW_HOME}/dev/archery+ export LC_ALL=C.UTF-8+ export LANG=C.UTF-8+}++install_archery+archery lintdiff --git a/dev/archery/archery/benchmark/core.py b/dev/archery/archery/benchmark/core.pyindex 83bc2735dd..ddf53d5e60 100644--- a/dev/archery/archery/benchmark/core.py+++ b/dev/archery/archery/benchmark/core.py@@ -15,7 +15,15 @@# specific language governing permissions and limitations# under the License.-import pandas as pa++def median(values):+ n = len(values)+ if n == 0:+ raise ValueError("median requires at least one value")+ elif n % 2 == 0:+ return (values[(n // 2) - 1] + values[n // 2]) / 2+ else:+ return values[n // 2]class Benchmark:@@ -23,13 +31,12 @@ class Benchmark:self.name = nameself.unit = unitself.less_is_better = less_is_better- self.values = pa.Series(values)- self.statistics = self.values.describe()+ self.values = sorted(values)+ self.median = median(self.values)@propertydef value(self):- median = "50%"- return float(self.statistics[median])+ return self.mediandef __repr__(self):return f"Benchmark[name={self.name},value={self.value}]"diff --git a/dev/archery/archery/cli.py b/dev/archery/archery/cli.pyindex 316e529913..a9df88a500 100644--- a/dev/archery/archery/cli.py+++ b/dev/archery/archery/cli.py@@ -17,29 +17,51 @@# under the License.import click-from contextlib import contextmanagerimport jsonimport loggingimport sys-from tempfile import mkdtemp, TemporaryDirectoryfrom .benchmark.compare import RunnerComparator, DEFAULT_THRESHOLDfrom .benchmark.runner import BenchmarkRunnerfrom .lang.cpp import CppCMakeDefinition, CppConfigurationfrom .utils.codec import JsonEncoder+from .utils.lint import linter, LintValidationExceptionfrom .utils.logger import logger, ctx as log_ctxfrom .utils.source import ArrowSources+from .utils.tmpdir import tmpdir# Set default logging to INFO in command line.logging.basicConfig(level=logging.INFO)+class ArrowBool(click.types.BoolParamType):+ """+ ArrowBool supports the 'ON' and 'OFF' values on top of the values+ supported by BoolParamType. This is convenient to port script which exports+ CMake options variables.+ """+ name = "boolean"++ def convert(self, value, param, ctx):+ if isinstance(value, str):+ lowered = value.lower()+ if lowered == "on":+ return True+ elif lowered == "off":+ return False++ return super().convert(value, param, ctx)+++BOOL = ArrowBool()++@click.group()[email protected]("--debug", type=bool, is_flag=True, default=False,[email protected]("--debug", type=BOOL, is_flag=True, default=False,help="Increase logging with debugging output.")[email protected]("--pdb", type=bool, is_flag=True, default=False,[email protected]("--pdb", type=BOOL, is_flag=True, default=False,help="Invoke pdb on uncaught exception.")[email protected]("-q", "--quiet", type=bool, is_flag=True, default=False,[email protected]("-q", "--quiet", type=BOOL, is_flag=True, default=False,help="Silence executed commands.")@click.pass_contextdef archery(ctx, debug, pdb, quiet):@@ -107,25 +129,25 @@ def _apply_options(cmd, options):@click.option("--warn-level", default="production", type=warn_level_type,help="Controls compiler warnings -W(no-)error.")# components[email protected]("--with-tests", default=True, type=bool,[email protected]("--with-tests", default=True, type=BOOL,help="Build with tests.")[email protected]("--with-benchmarks", default=False, type=bool,[email protected]("--with-benchmarks", default=False, type=BOOL,help="Build with benchmarks.")[email protected]("--with-python", default=True, type=bool,[email protected]("--with-python", default=True, type=BOOL,help="Build with python extension.")[email protected]("--with-parquet", default=False, type=bool,[email protected]("--with-parquet", default=False, type=BOOL,help="Build with parquet file support.")[email protected]("--with-gandiva", default=False, type=bool,[email protected]("--with-gandiva", default=False, type=BOOL,help="Build with Gandiva expression compiler support.")[email protected]("--with-plasma", default=False, type=bool,[email protected]("--with-plasma", default=False, type=BOOL,help="Build with Plasma object store support.")[email protected]("--with-flight", default=False, type=bool,[email protected]("--with-flight", default=False, type=BOOL,help="Build with Flight rpc support.")@click.option("--cmake-extras", type=str, multiple=True,help="Extra flags/options to pass to cmake invocation. ""Can be stacked")# misc[email protected]("-f", "--force", type=bool, is_flag=True, default=False,[email protected]("-f", "--force", type=BOOL, is_flag=True, default=False,help="Delete existing build directory if found.")@click.option("--targets", type=str, multiple=True,help="Generator targets to run. Can be stacked.")@@ -165,13 +187,38 @@ def build(ctx, src, build_dir, force, targets, **kwargs):build.run(target)-@contextmanager-def tmpdir(preserve, prefix="arrow-bench-"):- if preserve:- yield mkdtemp(prefix=prefix)- else:- with TemporaryDirectory(prefix=prefix) as tmp:- yield tmp[email protected](short_help="Lint Arrow source directory")[email protected]("--src", metavar="<arrow_src>", default=ArrowSources.find(),+ callback=validate_arrow_sources,+ help="Specify Arrow source directory")[email protected]("--with-clang-format", default=True, type=BOOL,+ help="Ensure formatting of C++ files.")[email protected]("--with-cpplint", default=True, type=BOOL,+ help="Ensure linting of C++ files with cpplint.")[email protected]("--with-clang-tidy", default=False, type=BOOL,+ help="Lint C++ with clang-tidy.")[email protected]("--with-iwyu", default=False, type=BOOL,+ help="Lint C++ with Include-What-You-Use (iwyu).")[email protected]("--with-flake8", default=True, type=BOOL,+ help="Lint python files with flake8.")[email protected]("--with-cmake-format", default=True, type=BOOL,+ help="Lint CMakeFiles.txt files with cmake-format.py.")[email protected]("--with-rat", default=True, type=BOOL,+ help="Lint files for license violation via apache-rat.")[email protected]("--with-r", default=True, type=BOOL,+ help="Lint r files.")[email protected]("--with-rust", default=True, type=BOOL,+ help="Lint rust files.")[email protected]("--with-docker", default=True, type=BOOL,+ help="Lint docker images with hadolint.")[email protected]("--fix", type=BOOL, default=False,+ help="Toggle fixing the lint errors if the linter supports it.")[email protected]_context+def lint(ctx, src, **kwargs):+ try:+ linter(src, **kwargs)+ except LintValidationException:+ sys.exit(1)@archery.group()@@ -190,7 +237,7 @@ def benchmark_common_options(cmd):default=ArrowSources.find(),callback=validate_arrow_sources,help="Specify Arrow source directory"),- click.option("--preserve", type=bool, default=False, show_default=True,+ click.option("--preserve", type=BOOL, default=False, show_default=True,is_flag=True,help="Preserve workspace for investigation."),click.option("--output", metavar="<output>",@@ -226,7 +273,7 @@ def benchmark_list(ctx, rev_or_path, src, preserve, output, cmake_extras,**kwargs):""" List benchmark suite."""- with tmpdir(preserve) as root:+ with tmpdir(preserve=preserve) as root:logger.debug(f"Running benchmark {rev_or_path}")conf = CppConfiguration(@@ -281,7 +328,7 @@ def benchmark_run(ctx, rev_or_path, src, preserve, output, cmake_extras,\barchery benchmark run --output=run.json"""- with tmpdir(preserve) as root:+ with tmpdir(preserve=preserve) as root:logger.debug(f"Running benchmark {rev_or_path}")conf = CppConfiguration(@@ -379,7 +426,7 @@ def benchmark_diff(ctx, src, preserve, output, cmake_extras,# This should not recompute the benchmark from run.jsonarchery --quiet benchmark diff WORKSPACE run.json > result.json"""- with tmpdir(preserve) as root:+ with tmpdir(preserve=preserve) as root:logger.debug(f"Comparing {contender} (contender) with "f"{baseline} (baseline)")diff --git a/dev/archery/archery/lang/cpp.py b/dev/archery/archery/lang/cpp.pyindex 4aa21a197c..6106c9c55e 100644--- a/dev/archery/archery/lang/cpp.py+++ b/dev/archery/archery/lang/cpp.py@@ -38,7 +38,9 @@ class CppConfiguration:# componentswith_tests=True, with_benchmarks=False, with_python=True,with_parquet=False, with_gandiva=False, with_plasma=False,- with_flight=False, cmake_extras=None):+ with_flight=False,+ # extras+ cmake_extras=None):self.cc = ccself.cxx = cxxself.cxx_flags = cxx_flags@@ -56,6 +58,7 @@ class CppConfiguration:self.with_gandiva = with_gandivaself.with_plasma = with_plasmaself.with_flight = with_flight+self.cmake_extras = cmake_extrasdef _gen_defs(self):@@ -64,6 +67,7 @@ class CppConfiguration:yield ("CMAKE_EXPORT_COMPILE_COMMANDS", truthifier(True))yield ("CMAKE_BUILD_TYPE", or_else(self.build_type, "debug"))+yield ("BUILD_WARNING_LEVEL", or_else(self.warn_level, "production"))# if not ctx.quiet:diff --git a/dev/archery/archery/lang/java.py b/dev/archery/archery/lang/java.pynew file mode 100644index 0000000000..6b2bdf0cf3--- /dev/null+++ b/dev/archery/archery/lang/java.py@@ -0,0 +1,30 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++from ..utils.command import Command, CommandStackMixin, default_bin+++class Java(Command):+ def __init__(self, java_bin=None):+ self.bin = default_bin(java_bin, "JAVA", "java")+++class Jar(CommandStackMixin, Java):+ def __init__(self, jar, *args, **kwargs):+ self.jar = jar+ self.argv = ("-jar", jar)+ Java.__init__(self, *args, **kwargs)diff --git a/dev/lint/run_clang_format.sh b/dev/archery/archery/lang/rust.pyold mode 100755new mode 100644similarity index 82%rename from dev/lint/run_clang_format.shrename to dev/archery/archery/lang/rust.pyindex 1f0f28b26b..2a60a8929b--- a/dev/lint/run_clang_format.sh+++ b/dev/archery/archery/lang/rust.py@@ -1,4 +1,3 @@-#!/bin/bash# Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information@@ -16,10 +15,9 @@# specific language governing permissions and limitations# under the License.-set -ex+from ..utils.command import Command, default_bin-mkdir -p /build/lint-pushd /build/lint- cmake -GNinja /arrow/cpp- ninja format-popd++class Cargo(Command):+ def __init__(self, cargo_bin=None):+ self.bin = default_bin(cargo_bin, "CARGO", "cargo")diff --git a/dev/archery/archery/utils/cache.py b/dev/archery/archery/utils/cache.pynew file mode 100644index 0000000000..2e476bdab9--- /dev/null+++ b/dev/archery/archery/utils/cache.py@@ -0,0 +1,80 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++from pathlib import Path+import os+from urllib.request import urlopen++from .logger import logger++ARCHERY_CACHE_DIR = Path.home() / ".cache" / "archery"+++class Cache:+ """ Cache stores downloaded objects, notably apache-rat.jar. """++ def __init__(self, path=ARCHERY_CACHE_DIR):+ self.root = path++ if not path.exists():+ os.makedirs(path)++ def key_path(self, key):+ """ Return the full path of a key. """+ return self.root/key++ def get(self, key):+ """ Return the full path of a key if cached, None otherwise. """+ path = self.key_path(key)+ return path if path.exists() else None++ def delete(self, key):+ """ Remove a key (and the file) from the cache. """+ path = self.get(key)+ if path:+ path.unlink()++ def get_or_insert(self, key, create):+ """+ Get or Insert a key from the cache. If the key is not found, the+ `create` closure will be evaluated.++ The `create` closure takes a single parameter, the path where the+ object should be store. The file should only be created upon success.+ """+ path = self.key_path(key)++ if not path.exists():+ create(path)++ return path++ def get_or_insert_from_url(self, key, url):+ """+ Get or Insert a key from the cache. If the key is not found, the file+ is downloaded from `url`.+ """+ def download(path):+ """ Tiny wrapper that download a file and save as key. """+ logger.debug(f"Downloading {url} as {path}")+ conn = urlopen(url)+ # Ensure the download is completed before writing to disks.+ content = conn.read()+ with open(path, "wb") as path_fd:+ path_fd.write(content)++ return self.get_or_insert(key, download)diff --git a/dev/archery/archery/utils/cmake.py b/dev/archery/archery/utils/cmake.pyindex bc72418c92..0760e34b8d 100644--- a/dev/archery/archery/utils/cmake.py+++ b/dev/archery/archery/utils/cmake.py@@ -19,12 +19,12 @@ import osimport refrom shutil import rmtree, which-from .command import Command+from .command import Command, default_binclass CMake(Command):def __init__(self, cmake_bin=None):- self.bin = cmake_bin if cmake_bin else os.environ.get("CMAKE", "cmake")+ self.bin = default_bin(cmake_bin, "CMAKE", "cmake")@staticmethoddef default_generator():@@ -85,7 +85,7 @@ class CMakeDefinition:]return arguments- def build(self, build_dir, force=False, **kwargs):+ def build(self, build_dir, force=False, cmd_kwargs=None, **kwargs):""" Invoke cmake into a build directory.Parameters@@ -106,7 +106,8 @@ class CMakeDefinition:os.mkdir(build_dir)- cmake(*self.arguments, cwd=build_dir, env=self.env)+ cmd_kwargs = cmd_kwargs if cmd_kwargs else {}+ cmake(*self.arguments, cwd=build_dir, env=self.env, **cmd_kwargs)return CMakeBuild(build_dir, self.build_type, definition=self,**kwargs)@@ -152,8 +153,8 @@ class CMakeBuild(CMake):if verbose:extra.append("-v" if self.bin.endswith("ninja") else "VERBOSE=1")# Commands must be ran under the build directory- super().run(*cmake_args, *extra, *argv, **kwargs, cwd=self.build_dir)- return self+ return super().run(*cmake_args, *extra,+ *argv, **kwargs, cwd=self.build_dir)def all(self):return self.run("all")diff --git a/dev/archery/archery/utils/command.py b/dev/archery/archery/utils/command.pyindex 46d0066d23..53dd5c4391 100644--- a/dev/archery/archery/utils/command.py+++ b/dev/archery/archery/utils/command.py@@ -24,22 +24,35 @@ from .logger import logger, ctxdef find_exec(executable):exec_exists = os.path.exists(executable)- return executable if exec_exists else shutil.which(executable)+ executable = executable if exec_exists else shutil.which(executable)++ if executable is None:+ raise FileNotFoundError(executable)++ return executable+++def default_bin(name, env, default):+ return name if name else os.environ.get(env, default)# Decorator running a command and returning stdoutclass capture_stdout:- def __init__(self, strip=False):+ def __init__(self, strip=False, listify=False):self.strip = strip+ self.listify = listifydef __call__(self, f):def strip_it(x):return x.strip() if self.strip else x+ def list_it(x):+ return x.decode('utf-8').splitlines() if self.listify else x+def wrapper(*argv, **kwargs):# Ensure stdout is capturedkwargs["stdout"] = subprocess.PIPE- return strip_it(f(*argv, **kwargs).stdout)+ return list_it(strip_it(f(*argv, **kwargs).stdout))return wrapper@@ -68,4 +81,15 @@ class Command:return subprocess.run(invocation, **kwargs)def __call__(self, *argv, **kwargs):- self.run(*argv, **kwargs)+ return self.run(*argv, **kwargs)+++class CommandStackMixin:+ def run(self, *argv, **kwargs):+ stacked_args = self.argv + argv+ return super(CommandStackMixin, self).run(*stacked_args, **kwargs)+++class Bash(Command):+ def __init__(self, bash_bin=None):+ self.bin = default_bin(bash_bin, "BASH", "bash")diff --git a/dev/archery/archery/utils/git.py b/dev/archery/archery/utils/git.pyindex a9d69a4b64..87b894dc22 100644--- a/dev/archery/archery/utils/git.py+++ b/dev/archery/archery/utils/git.py@@ -15,9 +15,7 @@# specific language governing permissions and limitations# under the License.-import os--from .command import Command, capture_stdout+from .command import Command, capture_stdout, default_bin# Decorator prepending argv with the git sub-command found with the method@@ -33,7 +31,7 @@ def git_cmd(fn):class Git(Command):def __init__(self, git_bin=None):- self.bin = git_bin if git_bin else os.environ.get("GIT", "git")+ self.bin = default_bin(git_bin, "GIT", "git")def run_cmd(self, cmd, *argv, git_dir=None, **kwargs):""" Inject flags before sub-command in argv. """@@ -43,6 +41,11 @@ class Git(Command):return self.run(*opts, cmd, *argv, **kwargs)+ @capture_stdout(strip=False)+ @git_cmd+ def archive(self, *argv, **kwargs):+ return self.run_cmd(*argv, **kwargs)+@git_cmddef clone(self, *argv, **kwargs):return self.run_cmd(*argv, **kwargs)@@ -51,15 +54,29 @@ class Git(Command):def checkout(self, *argv, **kwargs):return self.run_cmd(*argv, **kwargs)+ def dirty(self, **kwargs):+ return len(self.status("--short", **kwargs)) > 0+@git_cmddef log(self, *argv, **kwargs):return self.run_cmd(*argv, **kwargs)+ @capture_stdout(strip=True, listify=True)+ @git_cmd+ def ls_files(self, *argv, listify=False, **kwargs):+ stdout = self.run_cmd(*argv, **kwargs)+ return stdout+@capture_stdout(strip=True)@git_cmddef rev_parse(self, *argv, **kwargs):return self.run_cmd(*argv, **kwargs)+ @capture_stdout(strip=True)+ @git_cmd+ def status(self, *argv, **kwargs):+ return self.run_cmd(*argv, **kwargs)+@capture_stdout(strip=True)def head(self, **kwargs):""" Return commit pointed by HEAD. """diff --git a/dev/archery/archery/utils/lint.py b/dev/archery/archery/utils/lint.pynew file mode 100644index 0000000000..38e8a001b1--- /dev/null+++ b/dev/archery/archery/utils/lint.py@@ -0,0 +1,214 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++import gzip+import os++from .command import Bash, Command, default_bin+from .git import git+from .logger import logger+from ..lang.cpp import CppCMakeDefinition, CppConfiguration+from ..lang.rust import Cargo+from .rat import Rat, exclusion_from_globs+from .tmpdir import tmpdir+++class LintValidationException(Exception):+ pass+++class LintResult:+ def __init__(self, success, reason=None):+ self.success = success++ def ok(self):+ if not self.success:+ raise LintValidationException++ @staticmethod+ def from_cmd(command_result):+ return LintResult(command_result.returncode == 0)+++def cpp_linter(src, build_dir, clang_format=True, cpplint=True,+ clang_tidy=False, iwyu=False, fix=False):+ """ Run clang-format, cpplint and clang-tidy on cpp/ codebase. """+ logger.info("Running C++ linters")++ # A cmake build directory is required to populate `compile_commands.json`+ # which in turn is required by clang-tidy. It also provides a convenient+ # way to hide clang-format/clang-tidy invocation via the Generate+ # (ninja/make) targets.+ cmake_args = {"with_python": False}+ cmake_def = CppCMakeDefinition(src.cpp, CppConfiguration(**cmake_args))++ build = cmake_def.build(build_dir)+ if clang_format:+ target = "format" if fix else "check-format"+ yield LintResult.from_cmd(build.run(target, check=False))++ if cpplint:+ yield LintResult.from_cmd(build.run("lint", check=False))+ yield LintResult.from_cmd(build.run("lint_cpp_cli", check=False))++ if clang_tidy:+ yield LintResult.from_cmd(build.run("check-clang-tidy", check=False))++ if iwyu:+ yield LintResult.from_cmd(build.run("iwyu", check=False))+++class CMakeFormat(Command):+ def __init__(self, cmake_format_bin):+ self.bin = cmake_format_bin+++def cmake_linter(src, fix=False):+ """ Run cmake-format.py on all CMakeFiles.txt """+ logger.info("Running cmake-format linters")+ if not fix:+ logger.warn("run-cmake-format modifies files, irregardless of --fix")+ arrow_cmake_format = os.path.join(src.path, "run-cmake-format.py")+ cmake_format = CMakeFormat(cmake_format_bin=arrow_cmake_format)+ yield LintResult.from_cmd(cmake_format("--check"))+++class Flake8(Command):+ def __init__(self, flake8_bin=None):+ self.bin = default_bin(flake8_bin, "FLAKE8", "flake8")+++def python_linter(src):+ """ Run flake8 linter on python/pyarrow, and dev/. """+ logger.info("Running python linters")+ flake8 = Flake8()++ yield LintResult.from_cmd(flake8(src.pyarrow, src.dev, check=False))+ config = os.path.join(src.pyarrow, ".flake8.cython")+ yield LintResult.from_cmd(flake8("--config=" + config, src.pyarrow,+ check=False))+++def rat_linter(src, root):+ """ Run apache-rat license linter. """+ logger.info("Running apache-rat linter")++ if src.git_dirty:+ logger.warn("Due to the usage of git-archive, uncommited files will"+ " not be checked for rat violations. ")++ exclusion = exclusion_from_globs(+ os.path.join(src.dev, "release", "rat_exclude_files.txt"))++ # Creates a git-archive of ArrowSources, apache-rat expects a gzip+ # compressed tar archive.+ archive_path = os.path.join(root, "apache-arrow.tar.gz")+ src.archive(archive_path, compressor=gzip.compress)+ report = Rat().report(archive_path)++ violations = list(report.validate(exclusion=exclusion))+ for violation in violations:+ print(f"apache-rat license violation: {violation}")++ yield LintResult(len(violations) == 0)+++def r_linter(src):+ """ Run R linter. """+ logger.info("Running r linter")+ r_lint_sh = os.path.join(src.r, "lint.sh")+ yield LintResult.from_cmd(Bash().run(r_lint_sh, check=False))+++def rust_linter(src):+ """ Run Rust linter. """+ logger.info("Running rust linter")+ yield LintResult.from_cmd(Cargo().run("+stable", "fmt", "--all", "--",+ "--check", cwd=src.rust,+ check=False))+++class Hadolint(Command):+ def __init__(self, hadolint_bin=None):+ self.bin = default_bin(hadolint_bin, "HADOLINT", "hadolint")+++def is_docker_image(path):+ dirname = os.path.dirname(path)+ filename = os.path.basename(path)++ excluded = dirname.startswith(+ "dev") or dirname.startswith("python/manylinux")++ return filename.startswith("Dockerfile") and not excluded+++def docker_linter(src):+ """ Run Hadolint docker linter. """+ logger.info("Running docker linter")++ for path in git.ls_files(git_dir=src.path):+ if is_docker_image(path):+ yield LintResult.from_cmd(Hadolint().run(path, check=False,+ cwd=src.path))+++def linter(src, with_clang_format=True, with_cpplint=True,+ with_clang_tidy=False, with_iwyu=False,+ with_flake8=True, with_cmake_format=True,+ with_rat=True, with_r=True, with_rust=True,+ with_docker=True,+ fix=False):+ """ Run all linters. """+ with tmpdir(prefix="arrow-lint-") as root:+ build_dir = os.path.join(root, "cpp-build")++ # Linters yield LintResult without raising exceptions on failure.+ # This allows running all linters in one pass and exposing all+ # errors to the user.+ results = []++ if with_clang_format or with_cpplint or with_clang_tidy or with_iwyu:+ results.extend(cpp_linter(src, build_dir,+ clang_format=with_clang_format,+ cpplint=with_cpplint,+ clang_tidy=with_clang_tidy,+ iwyu=with_iwyu,+ fix=fix))++ if with_flake8:+ results.extend(python_linter(src))++ if with_cmake_format:+ results.extend(cmake_linter(src, fix=fix))++ if with_rat:+ results.extend(rat_linter(src, root))++ if with_r:+ results.extend(r_linter(src))++ if with_rust:+ results.extend(rust_linter(src))++ if with_docker:+ results.extend(docker_linter(src))++ # Raise error if one linter failed, ensuring calling code can exit with+ # non-zero.+ for result in results:+ result.ok()diff --git a/dev/archery/archery/utils/rat.py b/dev/archery/archery/utils/rat.pynew file mode 100644index 0000000000..53f9da9a24--- /dev/null+++ b/dev/archery/archery/utils/rat.py@@ -0,0 +1,70 @@+# Licensed to the Apache Software Foundation (ASF) under one+# or more contributor license agreements. See the NOTICE file+# distributed with this work for additional information+# regarding copyright ownership. The ASF licenses this file+# to you under the Apache License, Version 2.0 (the+# "License"); you may not use this file except in compliance+# with the License. You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing,+# software distributed under the License is distributed on an+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+# KIND, either express or implied. See the License for the+# specific language governing permissions and limitations+# under the License.++import fnmatch+import re+from xml.etree import ElementTree++from ..lang.java import Jar+from .cache import Cache+from .command import capture_stdout++RAT_VERSION = 0.13+RAT_JAR_FILENAME = f"apache-rat-{RAT_VERSION}.jar"+RAT_URL_ = f"https://repo1.maven.org/maven2/org/apache/rat/apache-rat"+RAT_URL = f"{RAT_URL_}/{RAT_VERSION}/{RAT_JAR_FILENAME}"+++class Rat(Jar):+ def __init__(self):+ jar = Cache().get_or_insert_from_url(RAT_JAR_FILENAME, RAT_URL)+ Jar.__init__(self, jar)++ @capture_stdout(strip=False)+ def run_report(self, archive_path, **kwargs):+ return self.run("--xml", archive_path, **kwargs)++ def report(self, archive_path, **kwargs):+ return RatReport(self.run_report(archive_path, **kwargs))+++def exclusion_from_globs(exclusions_path):+ with open(exclusions_path, 'r') as exclusions_fd:+ exclusions = [e.strip() for e in exclusions_fd]+ return lambda path: any([fnmatch.fnmatch(path, e) for e in exclusions])+++class RatReport:+ def __init__(self, xml):+ self.xml = xml+ self.tree = ElementTree.fromstring(xml)++ def __repr__(self):+ return f"RatReport({self.xml})"++ def validate(self, exclusion=None):+ for r in self.tree.findall('resource'):+ approvals = r.findall('license-approval')+ if not approvals or approvals[0].attrib['name'] == 'true':+ continue++ clean_name = re.sub('^[^/]+/', '', r.attrib['name'])++ if exclusion and exclusion(clean_name):+ continue++ yield clean_namediff --git a/dev/archery/archery/utils/source.py b/dev/archery/archery/utils/source.pyindex 7189c6833c..913e8d7e27 100644--- a/dev/archery/archery/utils/source.py+++ b/dev/archery/archery/utils/source.py@@ -42,22 +42,68 @@ class ArrowSources:assert isinstance(path, str) and ArrowSources.valid(path)self.path = path+ @property+ def archery(self):+ """ Returns the archery directory of an Arrow sources. """+ return os.path.join(self.dev, "archery")+@propertydef cpp(self):""" Returns the cpp directory of an Arrow sources. """return os.path.join(self.path, "cpp")+ @property+ def dev(self):+ """ Returns the dev directory of an Arrow sources. """+ return os.path.join(self.path, "dev")+@propertydef python(self):""" Returns the python directory of an Arrow sources. """return os.path.join(self.path, "python")+ @property+ def pyarrow(self):+ """ Returns the python/pyarrow directory of an Arrow sources. """+ return os.path.join(self.python, "pyarrow")++ @property+ def r(self):+ """ Returns the r directory of an Arrow sources. """+ return os.path.join(self.path, "r")++ @property+ def rust(self):+ """ Returns the rust directory of an Arrow sources. """+ return os.path.join(self.path, "rust")+@propertydef git_backed(self):""" Indicate if the sources are backed by git. """git_path = os.path.join(self.path, ".git")return os.path.exists(git_path)+ @property+ def git_dirty(self):+ """ Indicate if the sources is a dirty git directory. """+ return self.git_backed and git.dirty(git_dir=self.path)++ def archive(self, path, dereference=False, compressor=None, revision=None):+ """ Saves a git archive at path. """+ if not self.git_backed:+ raise ValueError(f"{self} is not backed by git")++ rev = revision if revision else "HEAD"+ archive = git.archive("--prefix=apache-arrow/", rev, git_dir=self.path)++ # TODO(fsaintjacques): fix dereference for++ if compressor:+ archive = compressor(archive)++ with open(path, "wb") as archive_fd:+ archive_fd.write(archive)+def at_revision(self, revision, clone_dir):""" Return a copy of the current sources for a specified git revision.diff --git a/dev/lint/run_linters.sh b/dev/archery/archery/utils/tmpdir.pyold mode 100755new mode 100644similarity index 72%rename from dev/lint/run_linters.shrename to dev/archery/archery/utils/tmpdir.pyindex ba618a7ae1..07d7355c87--- a/dev/lint/run_linters.sh+++ b/dev/archery/archery/utils/tmpdir.py@@ -1,4 +1,3 @@-#!/bin/bash# Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information@@ -16,20 +15,14 @@# specific language governing permissions and limitations# under the License.-set -ex+from contextlib import contextmanager+from tempfile import mkdtemp, TemporaryDirectory-mkdir -p /build/lint-pushd /build/lint- cmake -GNinja /arrow/cpp- ninja check-format- ninja lint-popd-pushd /arrow/python- flake8 --count pyarrow- flake8 --count --config=.flake8.cython pyarrow-popd--pushd /arrow/r- ./lint.sh-popd+@contextmanager+def tmpdir(preserve=False, prefix="arrow-archery-"):+ if preserve:+ yield mkdtemp(prefix=prefix)+ else:+ with TemporaryDirectory(prefix=prefix) as tmp:+ yield tmpdiff --git a/dev/archery/setup.py b/dev/archery/setup.pyindex 2cf692c005..40263a7713 100644--- a/dev/archery/setup.py+++ b/dev/archery/setup.py@@ -32,7 +32,7 @@ setup(maintainer='Arrow Developers',maintainer_email='[email protected]',packages=['archery'],- install_requires=['click', 'pandas'],+ install_requires=['click'],entry_points='''[console_scripts]archery=archery.cli:archerydiff --git a/dev/archery/tests/test_benchmarks.py b/dev/archery/tests/test_benchmarks.pyindex d199a40a19..e6d10121b9 100644--- a/dev/archery/tests/test_benchmarks.py+++ b/dev/archery/tests/test_benchmarks.py@@ -15,7 +15,7 @@# specific language governing permissions and limitations# under the License.-from archery.benchmark.core import Benchmark+from archery.benchmark.core import Benchmark, medianfrom archery.benchmark.compare import BenchmarkComparator@@ -37,3 +37,16 @@ def test_benchmark_comparator():assert not BenchmarkComparator(Benchmark("contender", unit, False, [20]),Benchmark("baseline", unit, False, [10])).regression+++def test_benchmark_median():+ assert median([10]) == 10+ assert median([1, 2, 3]) == 2+ assert median([1, 2]) == 1.5+ assert median([1, 2, 3, 4]) == 2.5+ assert median([1, 1, 1, 1]) == 1+ try:+ median([])+ assert False+ except ValueError:+ passdiff --git a/dev/release/rat_exclude_files.txt b/dev/release/rat_exclude_files.txtindex 840533f843..0d45bc1d95 100644--- a/dev/release/rat_exclude_files.txt+++ b/dev/release/rat_exclude_files.txt@@ -21,6 +21,7 @@ cpp/build-support/iwyu/*cpp/cmake_modules/FindPythonLibsNew.cmakecpp/cmake_modules/SnappyCMakeLists.txtcpp/cmake_modules/SnappyConfig.h+cpp/examples/parquet/parquet-arrow/cmake_modules/FindArrow.cmakecpp/src/parquet/.parquetcppversioncpp/src/plasma/thirdparty/ae/ae.ccpp/src/plasma/thirdparty/ae/ae.h@@ -146,6 +147,7 @@ go/*.sjs/.npmignorejs/closure-compiler-scripts/*js/src/fb/*.ts+python/cmake_modulespython/cmake_modules/FindPythonLibsNew.cmakepython/cmake_modules/SnappyCMakeLists.txtpython/cmake_modules/SnappyConfig.hdiff --git a/docker-compose.yml b/docker-compose.ymlindex c82991883b..19ab185bab 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -432,16 +432,26 @@ services:lint:# Usage:- # export PYTHON_VERSION=3.6- # docker-compose build cpp- # docker-compose build python# docker-compose build lint# docker-compose run lintimage: arrowdev/arrow-lint:latest+ build:+ context: .+ dockerfile: ci/docker/Dockerfile.lint+ volumes: *ubuntu-volumes++ iwyu:+ # Usage:+ # export PYTHON_VERSION=3.6+ # docker-compose build cpp+ # docker-compose build python+ # docker-compose build iwyu+ # docker-compose run iwyu+ image: arrowdev/arrow-iwyu:latestbuild:context: .dockerfile: dev/lint/Dockerfile- command: arrow/dev/lint/run_linters.sh+ command: arrow/dev/lint/run_iwyu.shvolumes: *ubuntu-volumesfuzzit:@@ -494,37 +504,6 @@ services:FUZZIT_JOB_TYPE: local-regressionvolumes: *ubuntu-volumes- iwyu:- # Usage:- # export PYTHON_VERSION=3.6- # docker-compose build cpp- # docker-compose build python- # docker-compose build lint- # docker-compose run iwyu- image: arrowdev/arrow-lint:latest- command: arrow/dev/lint/run_iwyu.sh- volumes: *ubuntu-volumes-- clang-format:- # Usage:- # docker-compose build cpp- # docker-compose build python- # docker-compose build lint- # docker-compose run clang-format- image: arrowdev/arrow-lint:latest- command: arrow/dev/lint/run_clang_format.sh- volumes: *ubuntu-volumes-- clang-tidy:- # Usage:- # docker-compose build cpp- # docker-compose build python- # docker-compose build lint- # docker-compose run clang-tidy- image: arrowdev/arrow-lint:latest- command: arrow/dev/lint/run_clang_tidy.sh- volumes: *ubuntu-volumes-docs:# Usage:# docker-compose build cpp