example-bazel-monorepo icon indicating copy to clipboard operation
example-bazel-monorepo copied to clipboard

Setup Flake8 for Python code

Open thundergolfer opened this issue 5 years ago β€’ 1 comments

Description

black (which this project is already using) is only a code formatter and doesn't catch a bunch of issues that crop up in Python code (eg. unused vars).

I'd like to continue using https://github.com/thundergolfer/bazel-linting-system but it might require modifications to enable support for more than 1 'linter' to be registered for 1 language.

thundergolfer avatar Mar 18 '20 06:03 thundergolfer

I was able to get this working with a shim. Interested in cleaner approaches.

BUILD.bazel

py_source_files = glob([
  "*.py",
  "tests/*.py",
])

py_test(
  name = "flake",
  srcs = [
    "flake.py",
  ],
  main = "flake.py",
  args = py_source_files,
  data = [
    ".flake8",
  ] + py_source_files,
  legacy_create_init = 0,
  deps = [
    requirement("flake8"),
  ],
)

flake.py

# Shim used to run flake from a Bazel py_test

import os
import sys
from flake8.api import legacy as flake8

if __name__ == "__main__":
    root = os.path.dirname(sys.argv[0])
    os.chdir(root)

    style_guide = flake8.get_style_guide()

    input_files = sys.argv[1:]

    report = style_guide.check_files(input_files)

    assert report.get_statistics('E') == [], 'Flake8 found violations'

    print("All good :)")

njlr avatar Nov 16 '22 17:11 njlr