From 20cece20bfb9937358e8c25668c33197ad0fa6e4 Mon Sep 17 00:00:00 2001 From: Daryl Bubune Date: Wed, 25 Nov 2026 11:09:27 -0400 Subject: [PATCH] refactor(config): pull up _parse_setting into BaseConfig JsonConfig, TomlConfig and YAMLConfig repeated the same parse steps. BaseConfig now runs these steps. Each subclass gives only its parser, its parse errors and the path to its commitizen section. --- commitizen/config/base_config.py | 32 +++++++++++++++++++++++++++++++- commitizen/config/json_config.py | 19 ++++++++----------- commitizen/config/toml_config.py | 22 +++++++++------------- commitizen/config/yaml_config.py | 21 +++++++++------------ 4 files changed, 57 insertions(+), 37 deletions(-) diff --git a/commitizen/config/base_config.py b/commitizen/config/base_config.py index f100cf9953..be128c0c29 100644 --- a/commitizen/config/base_config.py +++ b/commitizen/config/base_config.py @@ -1,9 +1,10 @@ from __future__ import annotations from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from commitizen.defaults import DEFAULT_SETTINGS, Settings +from commitizen.exceptions import InvalidConfigurationError if TYPE_CHECKING: import sys @@ -16,6 +17,9 @@ class BaseConfig: + _parse_errors: tuple[type[Exception], ...] = () + _missing_section_errors: tuple[type[Exception], ...] = () + def __init__(self) -> None: self._settings: Settings = DEFAULT_SETTINGS.copy() self._path: Path | None = None @@ -50,6 +54,32 @@ def update(self, data: Settings) -> None: self._settings.update(data) def _parse_setting(self, data: bytes | str) -> None: + """Parse the config file and apply its commitizen section. + + A missing commitizen section is valid, the default settings stay. + """ + try: + doc = self._load_document(data) + except self._parse_errors as e: + raise InvalidConfigurationError(f"Failed to parse {self.path}: {e}") + + try: + self.settings.update(self._get_commitizen_section(doc)) + except self._missing_section_errors: + pass + + def _load_document(self, data: bytes | str) -> Any: + """Parse the raw file content. + + The implementation is different for each config file type. + """ + raise NotImplementedError() + + def _get_commitizen_section(self, doc: Any) -> Any: + """Return the commitizen section of the parsed document. + + The implementation is different for each config file type. + """ raise NotImplementedError() def init_empty_config_content(self) -> None: diff --git a/commitizen/config/json_config.py b/commitizen/config/json_config.py index 688a6b9fec..8f901b24e0 100644 --- a/commitizen/config/json_config.py +++ b/commitizen/config/json_config.py @@ -1,9 +1,8 @@ from __future__ import annotations import json -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any -from commitizen.exceptions import InvalidConfigurationError from commitizen.git import smart_open from .base_config import BaseConfig @@ -20,6 +19,9 @@ class JsonConfig(BaseConfig): + _parse_errors = (json.JSONDecodeError,) + _missing_section_errors = (KeyError,) + def __init__(self, *, data: bytes | str, path: Path) -> None: super().__init__() self.path = path @@ -48,7 +50,7 @@ def set_key(self, key: str, value: object) -> Self: json.dump(config_doc, f, indent=2) return self - def _parse_setting(self, data: bytes | str) -> None: + def _load_document(self, data: bytes | str) -> Any: """We expect to have a section in .cz.json looking like ``` @@ -59,12 +61,7 @@ def _parse_setting(self, data: bytes | str) -> None: } ``` """ - try: - doc = json.loads(data) - except json.JSONDecodeError as e: - raise InvalidConfigurationError(f"Failed to parse {self.path}: {e}") + return json.loads(data) - try: - self.settings.update(doc["commitizen"]) - except KeyError: - pass + def _get_commitizen_section(self, doc: Any) -> Any: + return doc["commitizen"] diff --git a/commitizen/config/toml_config.py b/commitizen/config/toml_config.py index 28c05aaa52..3a3bedfca4 100644 --- a/commitizen/config/toml_config.py +++ b/commitizen/config/toml_config.py @@ -1,11 +1,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from tomlkit import TOMLDocument, exceptions, parse, table -from commitizen.exceptions import InvalidConfigurationError - from .base_config import BaseConfig if TYPE_CHECKING: @@ -20,6 +18,9 @@ class TomlConfig(BaseConfig): + _parse_errors = (exceptions.ParseError,) + _missing_section_errors = (exceptions.NonExistentKey,) + def __init__(self, *, data: bytes | str, path: Path) -> None: super().__init__() self.path = path @@ -51,7 +52,7 @@ def set_key(self, key: str, value: object) -> Self: return self - def _parse_setting(self, data: bytes | str) -> None: + def _load_document(self, data: bytes | str) -> Any: """We expect to have a section in pyproject looking like ``` @@ -59,12 +60,7 @@ def _parse_setting(self, data: bytes | str) -> None: name = "cz_conventional_commits" ``` """ - try: - doc = parse(data) - except exceptions.ParseError as e: - raise InvalidConfigurationError(f"Failed to parse {self.path}: {e}") - - try: - self.settings.update(doc["tool"]["commitizen"]) # type: ignore[index,typeddict-item] # TODO: fix this - except exceptions.NonExistentKey: - pass + return parse(data) + + def _get_commitizen_section(self, doc: Any) -> Any: + return doc["tool"]["commitizen"] diff --git a/commitizen/config/yaml_config.py b/commitizen/config/yaml_config.py index 1e9610e17a..1ed86a89cd 100644 --- a/commitizen/config/yaml_config.py +++ b/commitizen/config/yaml_config.py @@ -1,10 +1,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import yaml -from commitizen.exceptions import InvalidConfigurationError from commitizen.git import smart_open from .base_config import BaseConfig @@ -21,6 +20,9 @@ class YAMLConfig(BaseConfig): + _parse_errors = (yaml.YAMLError,) + _missing_section_errors = (KeyError, TypeError) + def __init__(self, *, data: bytes | str, path: Path) -> None: super().__init__() self.path = path @@ -37,7 +39,7 @@ def contains_commitizen_section(self) -> bool: config_doc = yaml.load(yaml_file, Loader=yaml.FullLoader) return config_doc is not None and config_doc.get("commitizen") is not None - def _parse_setting(self, data: bytes | str) -> None: + def _load_document(self, data: bytes | str) -> Any: """We expect to have a section in cz.yaml looking like ``` @@ -45,15 +47,10 @@ def _parse_setting(self, data: bytes | str) -> None: name: cz_conventional_commits ``` """ - try: - doc = yaml.safe_load(data) - except yaml.YAMLError as e: - raise InvalidConfigurationError(f"Failed to parse {self.path}: {e}") - - try: - self.settings.update(doc["commitizen"]) - except (KeyError, TypeError): - pass + return yaml.safe_load(data) + + def _get_commitizen_section(self, doc: Any) -> Any: + return doc["commitizen"] def set_key(self, key: str, value: object) -> Self: with self.path.open("rb") as yaml_file: