| 1 |
"""Rstcheck configuration functionality.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import configparser |
| 6 |
import contextlib |
| 7 |
import enum |
| 8 |
import logging |
| 9 |
import pathlib |
| 10 |
import re |
| 11 |
import typing as t |
| 12 |
|
| 13 |
import pydantic |
| 14 |
|
| 15 |
from . import _extras |
| 16 |
|
| 17 |
tomllib_imported = False |
| 18 |
try: |
| 19 |
import tomllib |
| 20 |
|
| 21 |
tomllib_imported = True |
| 22 |
except ModuleNotFoundError: |
| 23 |
if _extras.TOMLI_INSTALLED: |
| 24 |
import tomli as tomllib |
| 25 |
|
| 26 |
|
| 27 |
logger = logging.getLogger(__name__) |
| 28 |
|
| 29 |
|
| 30 |
CONFIG_FILES = [".rstcheck.cfg", "setup.cfg"] |
| 31 |
"""Supported default config files.""" |
| 32 |
if _extras.TOMLI_INSTALLED or tomllib_imported: |
| 33 |
CONFIG_FILES = [".rstcheck.cfg", "pyproject.toml", "setup.cfg"] |
| 34 |
|
| 35 |
|
| 36 |
class ReportLevel(enum.Enum): |
| 37 |
"""Report levels supported by docutils.""" |
| 38 |
|
| 39 |
INFO = 1 |
| 40 |
WARNING = 2 |
| 41 |
ERROR = 3 |
| 42 |
SEVERE = 4 |
| 43 |
NONE = 5 |
| 44 |
|
| 45 |
|
| 46 |
ReportLevelMap = { |
| 47 |
"info": 1, |
| 48 |
"warning": 2, |
| 49 |
"error": 3, |
| 50 |
"severe": 4, |
| 51 |
"none": 5, |
| 52 |
} |
| 53 |
"""Map docutils report levels in text form to numbers.""" |
| 54 |
|
| 55 |
|
| 56 |
DEFAULT_REPORT_LEVEL = ReportLevel.INFO |
| 57 |
"""Default report level.""" |
| 58 |
|
| 59 |
|
| 60 |
def _split_str_validator(value: t.Any) -> list[str] | None: |
| 61 |
"""Validate and parse strings and string-lists. |
| 62 |
|
| 63 |
Comma separated strings are split into a list. |
| 64 |
|
| 65 |
:param value: Value to validate |
| 66 |
:raises ValueError: If not a :py:class:`str` or :py:class:`list` of :py:class:`str` |
| 67 |
:return: List of strings |
| 68 |
""" |
| 69 |
if value is None: |
| 70 |
return None |
| 71 |
|
| 72 |
if isinstance(value, str): |
| 73 |
return [v.strip() for v in value.split(",") if v.strip()] |
| 74 |
|
| 75 |
if isinstance(value, list) and all(isinstance(v, str) for v in value): |
| 76 |
return [v.strip() for v in value if v.strip()] |
| 77 |
|
| 78 |
msg = "Not a string or list of strings" |
| 79 |
raise TypeError(msg) |
| 80 |
|
| 81 |
|
| 82 |
class RstcheckConfigFile(pydantic.BaseModel): |
| 83 |
"""Rstcheck config file. |
| 84 |
|
| 85 |
:raises ValueError: If setting has incorrect value or type |
| 86 |
:raises pydantic.ValidationError: If setting is not parsable into correct type |
| 87 |
""" |
| 88 |
|
| 89 |
report_level: t.Optional[ReportLevel] = None |
| 90 |
ignore_directives: t.Optional[t.List[str]] = None |
| 91 |
ignore_roles: t.Optional[t.List[str]] = None |
| 92 |
ignore_substitutions: t.Optional[t.List[str]] = None |
| 93 |
ignore_languages: t.Optional[t.List[str]] = None |
| 94 |
ignore_messages: t.Optional[t.Pattern[str]] = None |
| 95 |
|
| 96 |
@pydantic.field_validator("report_level", mode="before") |
| 97 |
@classmethod |
| 98 |
def valid_report_level(cls, value: t.Any) -> ReportLevel | None: |
| 99 |
"""Validate the report_level setting. |
| 100 |
|
| 101 |
:param value: Value to validate |
| 102 |
:raises ValueError: If ``value`` is not a valid docutils report level |
| 103 |
:return: Instance of :py:class:`ReportLevel` or None if emptry string. |
| 104 |
""" |
| 105 |
if value is None: |
| 106 |
return None |
| 107 |
|
| 108 |
if isinstance(value, ReportLevel): |
| 109 |
return value |
| 110 |
|
| 111 |
if value == "": |
| 112 |
return DEFAULT_REPORT_LEVEL |
| 113 |
|
| 114 |
if isinstance(value, bool): |
| 115 |
msg = "Invalid report level" |
| 116 |
raise TypeError(msg) |
| 117 |
|
| 118 |
if isinstance(value, str): |
| 119 |
if value.casefold() in set(ReportLevelMap): |
| 120 |
return ReportLevel(ReportLevelMap[value.casefold()]) |
| 121 |
|
| 122 |
with contextlib.suppress(ValueError): |
| 123 |
value = int(value) |
| 124 |
|
| 125 |
max_report_lvl = 5 |
| 126 |
min_report_lvl = 1 |
| 127 |
if isinstance(value, int) and min_report_lvl <= value <= max_report_lvl: |
| 128 |
return ReportLevel(value) |
| 129 |
|
| 130 |
msg = "Invalid report level" |
| 131 |
raise TypeError(msg) |
| 132 |
|
| 133 |
@pydantic.field_validator( |
| 134 |
"ignore_directives", |
| 135 |
"ignore_roles", |
| 136 |
"ignore_substitutions", |
| 137 |
"ignore_languages", |
| 138 |
mode="before", |
| 139 |
) |
| 140 |
@classmethod |
| 141 |
def split_str(cls, value: t.Any) -> list[str] | None: |
| 142 |
"""Validate and parse the following ignore_* settings. |
| 143 |
|
| 144 |
- ignore_directives |
| 145 |
- ignore_roles |
| 146 |
- ignore_substitutions |
| 147 |
- ignore_languages |
| 148 |
|
| 149 |
Comma separated strings are split into a list. |
| 150 |
|
| 151 |
:param value: Value to validate |
| 152 |
:raises ValueError: If not a :py:class:`str` or :py:class:`list` of :py:class:`str` |
| 153 |
:return: List of things to ignore in the respective category |
| 154 |
""" |
| 155 |
return _split_str_validator(value) |
| 156 |
|
| 157 |
@pydantic.field_validator("ignore_messages", mode="before") |
| 158 |
@classmethod |
| 159 |
def join_regex_str(cls, value: t.Any) -> str | t.Pattern[str] | None: |
| 160 |
"""Validate and concatenate the ignore_messages setting to a RegEx string. |
| 161 |
|
| 162 |
If a list ist given, the entries are concatenated with "|" to create an or RegEx. |
| 163 |
|
| 164 |
:param value: Value to validate |
| 165 |
:raises ValueError: If not a :py:class:`str` or :py:class:`list` of :py:class:`str` |
| 166 |
:return: A RegEx string with messages to ignore or :py:class:`typing.Pattern` if it is one |
| 167 |
already |
| 168 |
""" |
| 169 |
if value is None: |
| 170 |
return None |
| 171 |
|
| 172 |
if isinstance(value, re.Pattern): |
| 173 |
return value |
| 174 |
|
| 175 |
if isinstance(value, list) and all(isinstance(v, str) for v in value): |
| 176 |
return r"|".join(value) |
| 177 |
|
| 178 |
if isinstance(value, str): |
| 179 |
return value |
| 180 |
|
| 181 |
msg = "Not a string or list of strings" |
| 182 |
raise TypeError(msg) |
| 183 |
|
| 184 |
|
| 185 |
class RstcheckConfig(RstcheckConfigFile): |
| 186 |
"""Rstcheck config. |
| 187 |
|
| 188 |
:raises ValueError: If setting has incorrect value or type |
| 189 |
:raises pydantic.ValidationError: If setting is not parsable into correct type |
| 190 |
""" |
| 191 |
|
| 192 |
config_path: t.Optional[pathlib.Path] = None |
| 193 |
recursive: t.Optional[bool] = None |
| 194 |
warn_unknown_settings: t.Optional[bool] = None |
| 195 |
|
| 196 |
|
| 197 |
class _RstcheckConfigINIFile(pydantic.BaseModel): |
| 198 |
"""Type for [rstcheck] section in INI file. |
| 199 |
|
| 200 |
The types apply to the file's data before the parsing by :py:class:`RstcheckConfig` is done. |
| 201 |
|
| 202 |
:raises pydantic.ValidationError: If setting is not parsable into correct type |
| 203 |
""" |
| 204 |
|
| 205 |
report_level: t.Union[str, int, None] = None |
| 206 |
ignore_directives: t.Optional[str] = None |
| 207 |
ignore_roles: t.Optional[str] = None |
| 208 |
ignore_substitutions: t.Optional[str] = None |
| 209 |
ignore_languages: t.Optional[str] = None |
| 210 |
ignore_messages: t.Optional[str] = None |
| 211 |
|
| 212 |
|
| 213 |
def _load_config_from_ini_file( |
| 214 |
ini_file: pathlib.Path, |
| 215 |
*, |
| 216 |
log_missing_section_as_warning: bool = True, |
| 217 |
warn_unknown_settings: bool = False, |
| 218 |
) -> RstcheckConfigFile | None: |
| 219 |
"""Load, parse and validate rstcheck config from a ini file. |
| 220 |
|
| 221 |
:param ini_file: INI file to load config from |
| 222 |
:param log_missing_section_as_warning: If a missing [tool.rstcheck] section should be logged at |
| 223 |
WARNING (:py:obj:`True`) or ``INFO`` (:py:obj:`False`) level; |
| 224 |
defaults to :py:obj:`True` |
| 225 |
:param warn_unknown_settings: If a warning should be logged for unknown settings in config file; |
| 226 |
defaults to :py:obj:`False` |
| 227 |
:raises FileNotFoundError: If the file is not found |
| 228 |
:return: instance of :py:class:`RstcheckConfigFile` or :py:class:`None` on missing config |
| 229 |
section |
| 230 |
or ``NONE`` is passed as the config path. |
| 231 |
""" |
| 232 |
logger.debug("Try loading config from INI file: '%s'", ini_file) |
| 233 |
|
| 234 |
if ini_file.name == "NONE": |
| 235 |
logger.info("Config path is set to 'NONE'. No config file is loaded.") |
| 236 |
return None |
| 237 |
|
| 238 |
resolved_file = ini_file.resolve() |
| 239 |
|
| 240 |
if not resolved_file.is_file(): |
| 241 |
msg = f"{resolved_file}" |
| 242 |
raise FileNotFoundError(msg) |
| 243 |
|
| 244 |
parser = configparser.ConfigParser() |
| 245 |
parser.read(resolved_file) |
| 246 |
|
| 247 |
if not parser.has_section("rstcheck"): |
| 248 |
if log_missing_section_as_warning: |
| 249 |
logger.warning( |
| 250 |
"Config file has no [rstcheck] section: '%s'.", |
| 251 |
ini_file, |
| 252 |
) |
| 253 |
return None |
| 254 |
logger.info( |
| 255 |
"Config file has no [rstcheck] section: '%s'.", |
| 256 |
ini_file, |
| 257 |
) |
| 258 |
return None |
| 259 |
|
| 260 |
config_values_raw = dict(parser.items("rstcheck")) |
| 261 |
if warn_unknown_settings: |
| 262 |
known_settings = _RstcheckConfigINIFile().model_dump().keys() |
| 263 |
unknown = [s for s in config_values_raw if s not in known_settings] |
| 264 |
if unknown: |
| 265 |
logger.warning( |
| 266 |
"Unknown setting(s) %s found in file: '%s'.", |
| 267 |
unknown, |
| 268 |
ini_file, |
| 269 |
) |
| 270 |
|
| 271 |
config_values_checked = _RstcheckConfigINIFile(**config_values_raw) |
| 272 |
return RstcheckConfigFile(**config_values_checked.model_dump()) |
| 273 |
|
| 274 |
|
| 275 |
class _RstcheckConfigTOMLFile( |
| 276 |
pydantic.BaseModel, |
| 277 |
): |
| 278 |
"""Type for [tool.rstcheck] section in TOML file. |
| 279 |
|
| 280 |
The types apply to the file's data before the parsing by :py:class:`RstcheckConfig` is done. |
| 281 |
|
| 282 |
:raises pydantic.ValidationError: If setting is not parsable into correct type |
| 283 |
""" |
| 284 |
|
| 285 |
report_level: t.Union[str, int, None] = None |
| 286 |
ignore_directives: t.Optional[t.List[str]] = None |
| 287 |
ignore_roles: t.Optional[t.List[str]] = None |
| 288 |
ignore_substitutions: t.Optional[t.List[str]] = None |
| 289 |
ignore_languages: t.Optional[t.List[str]] = None |
| 290 |
ignore_messages: t.Union[t.List[str], str, None] = None |
| 291 |
|
| 292 |
|
| 293 |
def _load_config_from_toml_file( |
| 294 |
toml_file: pathlib.Path, |
| 295 |
*, |
| 296 |
log_missing_section_as_warning: bool = True, |
| 297 |
warn_unknown_settings: bool = False, |
| 298 |
) -> RstcheckConfigFile | None: |
| 299 |
"""Load, parse and validate rstcheck config from a TOML file. |
| 300 |
|
| 301 |
.. warning:: |
| 302 |
|
| 303 |
Needs tomli installed for python versions before 3.11! |
| 304 |
Use toml extra. |
| 305 |
|
| 306 |
:param toml_file: TOML file to load config from |
| 307 |
:param log_missing_section_as_warning: If a missing [tool.rstcheck] section should be logged at |
| 308 |
WARNING (:py:obj:`True`) or ``INFO`` (:py:obj:`False`) level; |
| 309 |
defaults to :py:obj:`True` |
| 310 |
:param warn_unknown_settings: If a warning should be logged for unknown settings in config file; |
| 311 |
defaults to :py:obj:`False` |
| 312 |
:raises ValueError: If the file is not a TOML file |
| 313 |
:raises FileNotFoundError: If the file is not found |
| 314 |
:return: instance of :py:class:`RstcheckConfigFile` or :py:obj:`None` on missing config section |
| 315 |
or ``NONE`` is passed as the config path. |
| 316 |
""" |
| 317 |
_extras.install_guard_tomli(tomllib_imported=tomllib_imported) |
| 318 |
logger.debug("Try loading config from TOML file: '%s'.", toml_file) |
| 319 |
|
| 320 |
if toml_file.name == "NONE": |
| 321 |
logger.info("Config path is set to 'NONE'. No config file is loaded.") |
| 322 |
return None |
| 323 |
|
| 324 |
resolved_file = toml_file.resolve() |
| 325 |
|
| 326 |
if not resolved_file.is_file(): |
| 327 |
logging.error("Config file is not a file: '%s'.", toml_file) |
| 328 |
msg = f"{resolved_file}" |
| 329 |
raise FileNotFoundError(msg) |
| 330 |
|
| 331 |
if resolved_file.suffix.casefold() != ".toml": |
| 332 |
logging.error("Config file is not a TOML file: '%s'.", toml_file) |
| 333 |
msg = "File is not a TOML file" |
| 334 |
raise ValueError(msg) |
| 335 |
|
| 336 |
with pathlib.Path(resolved_file).open("rb") as toml_file_handle: |
| 337 |
toml_dict = tomllib.load(toml_file_handle) |
| 338 |
|
| 339 |
rstcheck_section: t.Optional[dict[str, t.Any]] = toml_dict.get("tool", {}).get( |
| 340 |
"rstcheck" |
| 341 |
) |
| 342 |
|
| 343 |
if rstcheck_section is None: |
| 344 |
if log_missing_section_as_warning: |
| 345 |
logger.warning( |
| 346 |
"Config file has no [tool.rstcheck] section: '%s'.", |
| 347 |
toml_file, |
| 348 |
) |
| 349 |
return None |
| 350 |
logger.info( |
| 351 |
"Config file has no [tool.rstcheck] section: '%s'.", |
| 352 |
toml_file, |
| 353 |
) |
| 354 |
return None |
| 355 |
|
| 356 |
if warn_unknown_settings: |
| 357 |
known_settings = _RstcheckConfigTOMLFile().model_dump().keys() |
| 358 |
unknown = [s for s in rstcheck_section if s not in known_settings] |
| 359 |
if unknown: |
| 360 |
logger.warning( |
| 361 |
"Unknown setting(s) %s found in file: '%s'.", |
| 362 |
unknown, |
| 363 |
toml_file, |
| 364 |
) |
| 365 |
|
| 366 |
config_values_checked = _RstcheckConfigTOMLFile(**rstcheck_section) |
| 367 |
return RstcheckConfigFile(**config_values_checked.model_dump()) |
| 368 |
|
| 369 |
|
| 370 |
def load_config_file( |
| 371 |
file_path: pathlib.Path, |
| 372 |
*, |
| 373 |
log_missing_section_as_warning: bool = True, |
| 374 |
warn_unknown_settings: bool = False, |
| 375 |
) -> RstcheckConfigFile | None: |
| 376 |
"""Load, parse and validate rstcheck config from a file. |
| 377 |
|
| 378 |
.. caution:: |
| 379 |
|
| 380 |
If a TOML file is passed this function need tomli installed for python versions before 3.11! |
| 381 |
Use toml extra or install manually. |
| 382 |
|
| 383 |
:param file_path: File to load config from |
| 384 |
:param log_missing_section_as_warning: If a missing config section should be logged at |
| 385 |
WARNING (:py:obj:`True`) or ``INFO`` (:py:obj:`False`) level; |
| 386 |
defaults to :py:obj:`True` |
| 387 |
:param warn_unknown_settings: If a warning should be logged for unknown settings in config file; |
| 388 |
defaults to :py:obj:`False` |
| 389 |
:raises FileNotFoundError: If the file is not found |
| 390 |
:return: instance of :py:class:`RstcheckConfigFile` or :py:obj:`None` on missing config section |
| 391 |
or ``NONE`` is passed as the config path. |
| 392 |
""" |
| 393 |
logger.debug("Try loading config file.") |
| 394 |
|
| 395 |
if file_path.name == "NONE": |
| 396 |
logger.info("Config path is set to 'NONE'. No config file is loaded.") |
| 397 |
return None |
| 398 |
|
| 399 |
if file_path.suffix.casefold() == ".toml": |
| 400 |
return _load_config_from_toml_file( |
| 401 |
file_path, |
| 402 |
log_missing_section_as_warning=log_missing_section_as_warning, |
| 403 |
warn_unknown_settings=warn_unknown_settings, |
| 404 |
) |
| 405 |
return _load_config_from_ini_file( |
| 406 |
file_path, |
| 407 |
log_missing_section_as_warning=log_missing_section_as_warning, |
| 408 |
warn_unknown_settings=warn_unknown_settings, |
| 409 |
) |
| 410 |
|
| 411 |
|
| 412 |
def load_config_file_from_dir( |
| 413 |
dir_path: pathlib.Path, |
| 414 |
*, |
| 415 |
log_missing_section_as_warning: bool = False, |
| 416 |
warn_unknown_settings: bool = False, |
| 417 |
) -> RstcheckConfigFile | None: |
| 418 |
"""Search, load, parse and validate rstcheck config from a directory. |
| 419 |
|
| 420 |
Searches files from :py:data:`CONFIG_FILES` in the directory. If a file is found, try to load |
| 421 |
the config from it. If is has no config, search further. |
| 422 |
|
| 423 |
:param dir_path: Directory to search |
| 424 |
:param log_missing_section_as_warning: If a missing config section in a config file should be |
| 425 |
logged at WARNING (:py:obj:`True`) or ``INFO`` (:py:obj:`False`) level; |
| 426 |
defaults to :py:obj:`False` |
| 427 |
:param warn_unknown_settings: If a warning should be logged for unknown settings in config file; |
| 428 |
defaults to :py:obj:`False` |
| 429 |
:return: instance of :py:class:`RstcheckConfigFile` or |
| 430 |
:py:obj:`None` if no file is found or no file has a rstcheck section |
| 431 |
or ``NONE`` is passed as the config path. |
| 432 |
""" |
| 433 |
logger.debug("Try loading config file from directory: '%s'.", dir_path) |
| 434 |
|
| 435 |
if dir_path.name == "NONE": |
| 436 |
logger.info("Config path is set to 'NONE'. No config file is loaded.") |
| 437 |
return None |
| 438 |
|
| 439 |
config = None |
| 440 |
|
| 441 |
for file_name in CONFIG_FILES: |
| 442 |
file_path = (dir_path / file_name).resolve() |
| 443 |
if file_path.is_file(): |
| 444 |
config = load_config_file( |
| 445 |
file_path, |
| 446 |
log_missing_section_as_warning=( |
| 447 |
log_missing_section_as_warning or (file_name == ".rstcheck.cfg") |
| 448 |
), |
| 449 |
warn_unknown_settings=warn_unknown_settings, |
| 450 |
) |
| 451 |
if config is not None: |
| 452 |
break |
| 453 |
|
| 454 |
if config is None: |
| 455 |
logger.info( |
| 456 |
"No config section in supported config files found in directory: '%s'.", |
| 457 |
dir_path, |
| 458 |
) |
| 459 |
|
| 460 |
return config |
| 461 |
|
| 462 |
|
| 463 |
def load_config_file_from_dir_tree( |
| 464 |
dir_path: pathlib.Path, |
| 465 |
*, |
| 466 |
log_missing_section_as_warning: bool = False, |
| 467 |
warn_unknown_settings: bool = False, |
| 468 |
) -> RstcheckConfigFile | None: |
| 469 |
"""Search, load, parse and validate rstcheck config from a directory tree. |
| 470 |
|
| 471 |
Searches files from :py:data:`CONFIG_FILES` in the directory. If a file is found, try to load |
| 472 |
the config from it. If is has no config, search further. If no config is found in the directory |
| 473 |
search its parents one by one. |
| 474 |
|
| 475 |
:param dir_path: Directory to search |
| 476 |
:param log_missing_section_as_warning: If a missing config section in a config file should be |
| 477 |
logged at ``WARNING`` (:py:obj:`True`) or ``INFO`` (:py:obj:`False`) level; |
| 478 |
defaults to :py:obj:`False` |
| 479 |
:param warn_unknown_settings: If a warning should be logged for unknown settings in config file; |
| 480 |
defaults to :py:obj:`False` |
| 481 |
:return: instance of :py:class:`RstcheckConfigFile` or |
| 482 |
:py:obj:`None` if no file is found or no file has a rstcheck section |
| 483 |
or ``NONE`` is passed as the config path. |
| 484 |
""" |
| 485 |
logger.debug("Try loading config file from directory tree: '%s'.", dir_path) |
| 486 |
|
| 487 |
if dir_path.name == "NONE": |
| 488 |
logger.info("Config path is set to 'NONE'. No config file is loaded.") |
| 489 |
return None |
| 490 |
|
| 491 |
config = None |
| 492 |
|
| 493 |
search_dir = dir_path.resolve() |
| 494 |
|
| 495 |
while True: |
| 496 |
config = load_config_file_from_dir( |
| 497 |
search_dir, |
| 498 |
log_missing_section_as_warning=log_missing_section_as_warning, |
| 499 |
warn_unknown_settings=warn_unknown_settings, |
| 500 |
) |
| 501 |
|
| 502 |
if config is not None: |
| 503 |
break |
| 504 |
|
| 505 |
parent_dir = search_dir.parent.resolve() |
| 506 |
if parent_dir == search_dir: |
| 507 |
break |
| 508 |
search_dir = parent_dir |
| 509 |
|
| 510 |
if config is None: |
| 511 |
logger.info( |
| 512 |
"No config section in supported config files found in directory tree: '%s'.", |
| 513 |
dir_path, |
| 514 |
) |
| 515 |
|
| 516 |
return config |
| 517 |
|
| 518 |
|
| 519 |
def load_config_file_from_path( |
| 520 |
path: pathlib.Path, |
| 521 |
*, |
| 522 |
search_dir_tree: bool = False, |
| 523 |
log_missing_section_as_warning_for_file: bool = True, |
| 524 |
log_missing_section_as_warning_for_dir: bool = False, |
| 525 |
warn_unknown_settings: bool = False, |
| 526 |
) -> RstcheckConfigFile | None: |
| 527 |
"""Analyse the path and call the correct config file loader. |
| 528 |
|
| 529 |
:param path: Path to load config file from; can be a file or directory |
| 530 |
:param search_dir_tree: If the directory tree should be searched; |
| 531 |
only applies if ``path`` is a directory; |
| 532 |
defaults to :py:obj:`False` |
| 533 |
:param log_missing_section_as_warning_for_file: If a missing config section in a config file |
| 534 |
should be logged at WARNING (:py:obj:`True`) or ``INFO`` (:py:obj:`False`) level when the |
| 535 |
given path is a file; |
| 536 |
defaults to :py:obj:`True` |
| 537 |
:param log_missing_section_as_warning_for_dir: If a missing config section in a config file |
| 538 |
should be logged at ``WARNING`` (:py:obj:`True`) or ``INFO`` (:py:obj:`False`) level when |
| 539 |
the given file is a direcotry; |
| 540 |
defaults to :py:obj:`False` |
| 541 |
:param warn_unknown_settings: If a warning should be logged for unknown settings in config file; |
| 542 |
defaults to :py:obj:`False` |
| 543 |
:raises FileNotFoundError: When the passed path is not found. |
| 544 |
:return: instance of :py:class:`RstcheckConfigFile` or |
| 545 |
:py:obj:`None` if no file is found or no file has a rstcheck section |
| 546 |
or ``NONE`` is passed as the config path. |
| 547 |
""" |
| 548 |
logger.debug("Try loading config file from path: '%s'.", path) |
| 549 |
|
| 550 |
if path.name == "NONE": |
| 551 |
logger.info("Config path is set to 'NONE'. No config file is loaded.") |
| 552 |
return None |
| 553 |
|
| 554 |
resolved_path = path.resolve() |
| 555 |
|
| 556 |
if resolved_path.is_file(): |
| 557 |
return load_config_file( |
| 558 |
resolved_path, |
| 559 |
log_missing_section_as_warning=log_missing_section_as_warning_for_file, |
| 560 |
warn_unknown_settings=warn_unknown_settings, |
| 561 |
) |
| 562 |
|
| 563 |
if resolved_path.is_dir(): |
| 564 |
if search_dir_tree: |
| 565 |
return load_config_file_from_dir_tree( |
| 566 |
resolved_path, |
| 567 |
log_missing_section_as_warning=log_missing_section_as_warning_for_dir, |
| 568 |
warn_unknown_settings=warn_unknown_settings, |
| 569 |
) |
| 570 |
return load_config_file_from_dir( |
| 571 |
resolved_path, |
| 572 |
log_missing_section_as_warning=log_missing_section_as_warning_for_dir, |
| 573 |
warn_unknown_settings=warn_unknown_settings, |
| 574 |
) |
| 575 |
|
| 576 |
raise FileNotFoundError(2, "Passed config path not found.", path) |
| 577 |
|
| 578 |
|
| 579 |
def merge_configs( |
| 580 |
config_base: RstcheckConfig, |
| 581 |
config_add: RstcheckConfig | RstcheckConfigFile, |
| 582 |
*, |
| 583 |
config_add_is_dominant: bool = True, |
| 584 |
) -> RstcheckConfig: |
| 585 |
"""Merge two configs into a new one. |
| 586 |
|
| 587 |
:param config_base: The base config to merge into |
| 588 |
:param config_add: The config that is merged into the ``config_base`` |
| 589 |
:param config_add_is_dominant: If the ``config_add`` overwrites values of ``config_base``; |
| 590 |
defaults to :py:obj:`True` |
| 591 |
:return: New merged config |
| 592 |
""" |
| 593 |
logger.debug("Merging configs.") |
| 594 |
sub_config: RstcheckConfig | RstcheckConfigFile = config_base |
| 595 |
sub_config_dict = sub_config.model_dump() |
| 596 |
for setting in dict(sub_config_dict): |
| 597 |
if sub_config_dict[setting] is None: |
| 598 |
del sub_config_dict[setting] |
| 599 |
|
| 600 |
dom_config: RstcheckConfig | RstcheckConfigFile = config_add |
| 601 |
dom_config_dict = dom_config.model_dump() |
| 602 |
for setting in dict(dom_config_dict): |
| 603 |
if dom_config_dict[setting] is None: |
| 604 |
del dom_config_dict[setting] |
| 605 |
|
| 606 |
if config_add_is_dominant is False: |
| 607 |
sub_config_dict, dom_config_dict = dom_config_dict, sub_config_dict |
| 608 |
|
| 609 |
merged_config_dict = {**sub_config_dict, **dom_config_dict} |
| 610 |
|
| 611 |
return RstcheckConfig(**merged_config_dict) |