Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion commitizen/config/base_config.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down
19 changes: 8 additions & 11 deletions commitizen/config/json_config.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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

```
Expand All @@ -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"]
22 changes: 9 additions & 13 deletions commitizen/config/toml_config.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -51,20 +52,15 @@ 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

```
[tool.commitizen]
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"]
21 changes: 9 additions & 12 deletions commitizen/config/yaml_config.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -37,23 +39,18 @@ 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

```
commitizen:
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:
Expand Down
Loading