lint-python.py raw

   1  #!/usr/bin/env python3
   2  #
   3  # Copyright (c) 2022-present The Bitcoin Core developers
   4  # Distributed under the MIT software license, see the accompanying
   5  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
   6  
   7  """
   8  Check for specified mypy warnings in python files.
   9  """
  10  
  11  import os
  12  from pathlib import Path
  13  import subprocess
  14  
  15  from importlib.metadata import metadata, PackageNotFoundError
  16  
  17  # Customize mypy cache dir via environment variable
  18  cache_dir = Path(__file__).parent.parent / ".mypy_cache"
  19  os.environ["MYPY_CACHE_DIR"] = str(cache_dir)
  20  
  21  DEPS = ['lief', 'mypy', 'pyzmq']
  22  
  23  # Only .py files in test/functional and contrib/devtools have type annotations
  24  # enforced.
  25  MYPY_FILES_ARGS = ['git', 'ls-files', 'test/functional/*.py', 'contrib/devtools/*.py']
  26  
  27  
  28  def check_dependencies():
  29      for dep in DEPS:
  30          try:
  31              metadata(dep)
  32          except PackageNotFoundError:
  33              print(f"Skipping Python linting since {dep} is not installed.")
  34              exit(0)
  35  
  36  
  37  def main():
  38      check_dependencies()
  39  
  40      mypy_files = subprocess.check_output(MYPY_FILES_ARGS, text=True).splitlines()
  41      mypy_args = ['mypy', '--show-error-codes'] + mypy_files
  42  
  43      try:
  44          subprocess.check_call(mypy_args)
  45      except subprocess.CalledProcessError:
  46          exit(1)
  47  
  48  
  49  if __name__ == "__main__":
  50      main()
  51