find_default_config_files.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  3. import configparser
  4. import os
  5. from typing import Iterator, Optional
  6. import toml
  7. from toml import TomlDecodeError
  8. def _toml_has_config(path):
  9. with open(path, encoding="utf-8") as toml_handle:
  10. try:
  11. content = toml.load(toml_handle)
  12. except TomlDecodeError as error:
  13. print(f"Failed to load '{path}': {error}")
  14. return False
  15. try:
  16. content["tool"]["pylint"]
  17. except KeyError:
  18. return False
  19. return True
  20. def _cfg_has_config(path):
  21. parser = configparser.ConfigParser()
  22. parser.read(path, encoding="utf-8")
  23. return any(section.startswith("pylint.") for section in parser.sections())
  24. def find_default_config_files() -> Iterator[str]:
  25. """Find all possible config files."""
  26. rc_names = ("pylintrc", ".pylintrc")
  27. config_names = rc_names + ("pyproject.toml", "setup.cfg")
  28. for config_name in config_names:
  29. if os.path.isfile(config_name):
  30. if config_name.endswith(".toml") and not _toml_has_config(config_name):
  31. continue
  32. if config_name.endswith(".cfg") and not _cfg_has_config(config_name):
  33. continue
  34. yield os.path.abspath(config_name)
  35. if os.path.isfile("__init__.py"):
  36. curdir = os.path.abspath(os.getcwd())
  37. while os.path.isfile(os.path.join(curdir, "__init__.py")):
  38. curdir = os.path.abspath(os.path.join(curdir, ".."))
  39. for rc_name in rc_names:
  40. rc_path = os.path.join(curdir, rc_name)
  41. if os.path.isfile(rc_path):
  42. yield rc_path
  43. if "PYLINTRC" in os.environ and os.path.exists(os.environ["PYLINTRC"]):
  44. if os.path.isfile(os.environ["PYLINTRC"]):
  45. yield os.environ["PYLINTRC"]
  46. else:
  47. user_home = os.path.expanduser("~")
  48. if user_home not in ("~", "/root"):
  49. home_rc = os.path.join(user_home, ".pylintrc")
  50. if os.path.isfile(home_rc):
  51. yield home_rc
  52. home_rc = os.path.join(user_home, ".config", "pylintrc")
  53. if os.path.isfile(home_rc):
  54. yield home_rc
  55. if os.path.isfile("/etc/pylintrc"):
  56. yield "/etc/pylintrc"
  57. def find_pylintrc() -> Optional[str]:
  58. """search the pylint rc file and return its path if it find it, else None"""
  59. for config_file in find_default_config_files():
  60. if config_file.endswith("pylintrc"):
  61. return config_file
  62. return None