config_file_parser.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. import warnings
  10. from pathlib import Path
  11. from typing import TYPE_CHECKING
  12. from pylint.config.utils import _parse_rich_type_value
  13. if sys.version_info >= (3, 11):
  14. import tomllib
  15. else:
  16. import tomli as tomllib
  17. if TYPE_CHECKING:
  18. from pylint.lint import PyLinter
  19. class _ConfigurationFileParser:
  20. """Class to parse various formats of configuration files."""
  21. def __init__(self, verbose: bool, linter: PyLinter) -> None:
  22. self.verbose_mode = verbose
  23. self.linter = linter
  24. def _parse_ini_file(self, file_path: Path) -> tuple[dict[str, str], list[str]]:
  25. """Parse and handle errors of a ini configuration file."""
  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. for section in parser.sections():
  33. if self._ini_file_with_sections(file_path) and not section.startswith(
  34. "pylint"
  35. ):
  36. if section.lower() == "master":
  37. # TODO: 3.0: Remove deprecated handling of master, only allow 'pylint.' sections
  38. warnings.warn(
  39. "The use of 'MASTER' or 'master' as configuration section for pylint "
  40. "has been deprecated, as it's bad practice to not start sections titles "
  41. "with the tool name. Please use 'pylint.main' instead.",
  42. UserWarning,
  43. )
  44. else:
  45. continue
  46. for opt, value in parser[section].items():
  47. config_content[opt] = value
  48. options += [f"--{opt}", value]
  49. return config_content, options
  50. @staticmethod
  51. def _ini_file_with_sections(file_path: Path) -> bool:
  52. """Return whether the file uses sections."""
  53. if "setup.cfg" in file_path.parts:
  54. return True
  55. if "tox.ini" in file_path.parts:
  56. return True
  57. return False
  58. def _parse_toml_file(self, file_path: Path) -> tuple[dict[str, str], list[str]]:
  59. """Parse and handle errors of a toml configuration file."""
  60. try:
  61. with open(file_path, mode="rb") as fp:
  62. content = tomllib.load(fp)
  63. except tomllib.TOMLDecodeError as e:
  64. self.linter.add_message("config-parse-error", line=0, args=str(e))
  65. return {}, []
  66. try:
  67. sections_values = content["tool"]["pylint"]
  68. except KeyError:
  69. return {}, []
  70. config_content: dict[str, str] = {}
  71. options: list[str] = []
  72. for opt, values in sections_values.items():
  73. if isinstance(values, dict):
  74. for config, value in values.items():
  75. value = _parse_rich_type_value(value)
  76. config_content[config] = value
  77. options += [f"--{config}", value]
  78. else:
  79. values = _parse_rich_type_value(values)
  80. config_content[opt] = values
  81. options += [f"--{opt}", values]
  82. return config_content, options
  83. def parse_config_file(
  84. self, file_path: Path | None
  85. ) -> tuple[dict[str, str], list[str]]:
  86. """Parse a config file and return str-str pairs."""
  87. if file_path is None:
  88. if self.verbose_mode:
  89. print(
  90. "No config file found, using default configuration", file=sys.stderr
  91. )
  92. return {}, []
  93. file_path = Path(os.path.expandvars(file_path)).expanduser()
  94. if not file_path.exists():
  95. raise OSError(f"The config file {file_path} doesn't exist!")
  96. if self.verbose_mode:
  97. print(f"Using config file {file_path}", file=sys.stderr)
  98. try:
  99. if file_path.suffix == ".toml":
  100. return self._parse_toml_file(file_path)
  101. return self._parse_ini_file(file_path)
  102. except (configparser.Error, tomllib.TOMLDecodeError) as e:
  103. self.linter.add_message("config-parse-error", line=0, args=str(e))
  104. return {}, []