core.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Pylama's core functionality.
  2. Prepare params, check a modeline and run the checkers.
  3. """
  4. import os.path as op
  5. from pathlib import Path
  6. from typing import List
  7. from pylama.config import CURDIR, LOGGER, Namespace
  8. from pylama.context import RunContext
  9. from pylama.errors import Error, default_sorter, remove_duplicates
  10. from pylama.lint import LINTERS, LinterV2
  11. def run(
  12. path: str, code: str = None, rootdir: Path = CURDIR, options: Namespace = None
  13. ) -> List[Error]:
  14. """Run code checkers with the given params.
  15. :param path: (str) A file's path.
  16. """
  17. path = op.relpath(path, rootdir)
  18. with RunContext(path, code, options) as ctx:
  19. if ctx.skip:
  20. LOGGER.info("Skip checking for path: %s", path)
  21. else:
  22. for lname in ctx.linters or LINTERS:
  23. linter_cls = LINTERS.get(lname)
  24. if not linter_cls:
  25. continue
  26. linter = linter_cls()
  27. LOGGER.info("Run [%s] %s", lname, path)
  28. if isinstance(linter, LinterV2):
  29. linter.run_check(ctx)
  30. else:
  31. for err_info in linter.run(
  32. ctx.temp_filename, code=ctx.source, params=ctx.get_params(lname)
  33. ):
  34. ctx.push(source=lname, **err_info)
  35. if not ctx.errors:
  36. return ctx.errors
  37. errors = list(remove_duplicates(ctx.errors))
  38. sorter = default_sorter
  39. if options and options.sort:
  40. sort = options.sort
  41. sorter = lambda err: (sort.get(err.etype, 999), err.lnum) # pylint: disable=C3001
  42. return sorted(errors, key=sorter)
  43. # pylama:ignore=R0912,D210,F0001,C3001