config_file_parser.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
  4. """Configuration file parser class."""
  5. from __future__ import annotations
  6. import configparser
  7. import os
  8. import sys
  9. from pathlib import Path
  10. from typing import TYPE_CHECKING
  11. from pylint.config.utils import _parse_rich_type_value
  12. if sys.version_info >= (3, 11):
  13. import tomllib
  14. else:
  15. import tomli as tomllib
  16. if TYPE_CHECKING:
  17. from pylint.lint import PyLinter
  18. PylintConfigFileData = tuple[dict[str, str], list[str]]
  19. class _RawConfParser:
  20. """Class to parse various formats of configuration files."""
  21. @staticmethod
  22. def parse_ini_file(file_path: Path) -> PylintConfigFileData:
  23. """Parse and handle errors of an ini configuration file.
  24. Raises ``configparser.Error``.
  25. """
  26. parser = configparser.ConfigParser(inline_comment_prefixes=("#", ";"))
  27. # Use this encoding in order to strip the BOM marker, if any.
  28. with open(file_path, encoding="utf_8_sig") as fp:
  29. parser.read_file(fp)
  30. config_content: dict[str, str] = {}
  31. options: list[str] = []
  32. ini_file_with_sections = _RawConfParser._ini_file_with_sections(file_path)
  33. for section in parser.sections():
  34. if ini_file_with_sections and not section.startswith("pylint"):
  35. continue
  36. for option, value in parser[section].items():
  37. config_content[option] = value
  38. options += [f"--{option}", value]
  39. return config_content, options
  40. @staticmethod
  41. def _ini_file_with_sections(file_path: Path) -> bool:
  42. """Return whether the file uses sections."""
  43. if "setup.cfg" in file_path.parts:
  44. return True
  45. if "tox.ini" in file_path.parts:
  46. return True
  47. return False
  48. @staticmethod
  49. def parse_toml_file(file_path: Path) -> PylintConfigFileData:
  50. """Parse and handle errors of a toml configuration file.
  51. Raises ``tomllib.TOMLDecodeError``.
  52. """
  53. with open(file_path, mode="rb") as fp:
  54. content = tomllib.load(fp)
  55. try:
  56. sections_values = content["tool"]["pylint"]
  57. except KeyError:
  58. return {}, []
  59. config_content: dict[str, str] = {}
  60. options: list[str] = []
  61. for opt, values in sections_values.items():
  62. if isinstance(values, dict):
  63. for config, value in values.items():
  64. value = _parse_rich_type_value(value)
  65. config_content[config] = value
  66. options += [f"--{config}", value]
  67. else:
  68. values = _parse_rich_type_value(values)
  69. config_content[opt] = values
  70. options += [f"--{opt}", values]
  71. return config_content, options
  72. @staticmethod
  73. def parse_config_file(
  74. file_path: Path | None, verbose: bool
  75. ) -> PylintConfigFileData:
  76. """Parse a config file and return str-str pairs.
  77. Raises ``tomllib.TOMLDecodeError``, ``configparser.Error``.
  78. """
  79. if file_path is None:
  80. if verbose:
  81. print(
  82. "No config file found, using default configuration", file=sys.stderr
  83. )
  84. return {}, []
  85. file_path = Path(os.path.expandvars(file_path)).expanduser()
  86. if not file_path.exists():
  87. raise OSError(f"The config file {file_path} doesn't exist!")
  88. if verbose:
  89. print(f"Using config file {file_path}", file=sys.stderr)
  90. if file_path.suffix == ".toml":
  91. return _RawConfParser.parse_toml_file(file_path)
  92. return _RawConfParser.parse_ini_file(file_path)
  93. class _ConfigurationFileParser:
  94. """Class to parse various formats of configuration files."""
  95. def __init__(self, verbose: bool, linter: PyLinter) -> None:
  96. self.verbose_mode = verbose
  97. self.linter = linter
  98. def parse_config_file(self, file_path: Path | None) -> PylintConfigFileData:
  99. """Parse a config file and return str-str pairs."""
  100. try:
  101. return _RawConfParser.parse_config_file(file_path, self.verbose_mode)
  102. except (configparser.Error, tomllib.TOMLDecodeError) as e:
  103. self.linter.add_message("config-parse-error", line=0, args=str(e))
  104. return {}, []