Skip to content

Commit 20cece2

Browse files
committed
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.
1 parent 0839f9a commit 20cece2

4 files changed

Lines changed: 57 additions & 37 deletions

File tree

‎commitizen/config/base_config.py‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
from __future__ import annotations
22

33
from pathlib import Path
4-
from typing import TYPE_CHECKING
4+
from typing import TYPE_CHECKING, Any
55

66
from commitizen.defaults import DEFAULT_SETTINGS, Settings
7+
from commitizen.exceptions import InvalidConfigurationError
78

89
if TYPE_CHECKING:
910
import sys
@@ -16,6 +17,9 @@
1617

1718

1819
class BaseConfig:
20+
_parse_errors: tuple[type[Exception], ...] = ()
21+
_missing_section_errors: tuple[type[Exception], ...] = ()
22+
1923
def __init__(self) -> None:
2024
self._settings: Settings = DEFAULT_SETTINGS.copy()
2125
self._path: Path | None = None
@@ -50,6 +54,32 @@ def update(self, data: Settings) -> None:
5054
self._settings.update(data)
5155

5256
def _parse_setting(self, data: bytes | str) -> None:
57+
"""Parse the config file and apply its commitizen section.
58+
59+
A missing commitizen section is valid, the default settings stay.
60+
"""
61+
try:
62+
doc = self._load_document(data)
63+
except self._parse_errors as e:
64+
raise InvalidConfigurationError(f"Failed to parse {self.path}: {e}")
65+
66+
try:
67+
self.settings.update(self._get_commitizen_section(doc))
68+
except self._missing_section_errors:
69+
pass
70+
71+
def _load_document(self, data: bytes | str) -> Any:
72+
"""Parse the raw file content.
73+
74+
The implementation is different for each config file type.
75+
"""
76+
raise NotImplementedError()
77+
78+
def _get_commitizen_section(self, doc: Any) -> Any:
79+
"""Return the commitizen section of the parsed document.
80+
81+
The implementation is different for each config file type.
82+
"""
5383
raise NotImplementedError()
5484

5585
def init_empty_config_content(self) -> None:

‎commitizen/config/json_config.py‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
from __future__ import annotations
22

33
import json
4-
from typing import TYPE_CHECKING
4+
from typing import TYPE_CHECKING, Any
55

6-
from commitizen.exceptions import InvalidConfigurationError
76
from commitizen.git import smart_open
87

98
from .base_config import BaseConfig
@@ -20,6 +19,9 @@
2019

2120

2221
class JsonConfig(BaseConfig):
22+
_parse_errors = (json.JSONDecodeError,)
23+
_missing_section_errors = (KeyError,)
24+
2325
def __init__(self, *, data: bytes | str, path: Path) -> None:
2426
super().__init__()
2527
self.path = path
@@ -48,7 +50,7 @@ def set_key(self, key: str, value: object) -> Self:
4850
json.dump(config_doc, f, indent=2)
4951
return self
5052

51-
def _parse_setting(self, data: bytes | str) -> None:
53+
def _load_document(self, data: bytes | str) -> Any:
5254
"""We expect to have a section in .cz.json looking like
5355
5456
```
@@ -59,12 +61,7 @@ def _parse_setting(self, data: bytes | str) -> None:
5961
}
6062
```
6163
"""
62-
try:
63-
doc = json.loads(data)
64-
except json.JSONDecodeError as e:
65-
raise InvalidConfigurationError(f"Failed to parse {self.path}: {e}")
64+
return json.loads(data)
6665

67-
try:
68-
self.settings.update(doc["commitizen"])
69-
except KeyError:
70-
pass
66+
def _get_commitizen_section(self, doc: Any) -> Any:
67+
return doc["commitizen"]

‎commitizen/config/toml_config.py‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
from __future__ import annotations
22

3-
from typing import TYPE_CHECKING
3+
from typing import TYPE_CHECKING, Any
44

55
from tomlkit import TOMLDocument, exceptions, parse, table
66

7-
from commitizen.exceptions import InvalidConfigurationError
8-
97
from .base_config import BaseConfig
108

119
if TYPE_CHECKING:
@@ -20,6 +18,9 @@
2018

2119

2220
class TomlConfig(BaseConfig):
21+
_parse_errors = (exceptions.ParseError,)
22+
_missing_section_errors = (exceptions.NonExistentKey,)
23+
2324
def __init__(self, *, data: bytes | str, path: Path) -> None:
2425
super().__init__()
2526
self.path = path
@@ -51,20 +52,15 @@ def set_key(self, key: str, value: object) -> Self:
5152

5253
return self
5354

54-
def _parse_setting(self, data: bytes | str) -> None:
55+
def _load_document(self, data: bytes | str) -> Any:
5556
"""We expect to have a section in pyproject looking like
5657
5758
```
5859
[tool.commitizen]
5960
name = "cz_conventional_commits"
6061
```
6162
"""
62-
try:
63-
doc = parse(data)
64-
except exceptions.ParseError as e:
65-
raise InvalidConfigurationError(f"Failed to parse {self.path}: {e}")
66-
67-
try:
68-
self.settings.update(doc["tool"]["commitizen"]) # type: ignore[index,typeddict-item] # TODO: fix this
69-
except exceptions.NonExistentKey:
70-
pass
63+
return parse(data)
64+
65+
def _get_commitizen_section(self, doc: Any) -> Any:
66+
return doc["tool"]["commitizen"]

‎commitizen/config/yaml_config.py‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
from __future__ import annotations
22

3-
from typing import TYPE_CHECKING
3+
from typing import TYPE_CHECKING, Any
44

55
import yaml
66

7-
from commitizen.exceptions import InvalidConfigurationError
87
from commitizen.git import smart_open
98

109
from .base_config import BaseConfig
@@ -21,6 +20,9 @@
2120

2221

2322
class YAMLConfig(BaseConfig):
23+
_parse_errors = (yaml.YAMLError,)
24+
_missing_section_errors = (KeyError, TypeError)
25+
2426
def __init__(self, *, data: bytes | str, path: Path) -> None:
2527
super().__init__()
2628
self.path = path
@@ -37,23 +39,18 @@ def contains_commitizen_section(self) -> bool:
3739
config_doc = yaml.load(yaml_file, Loader=yaml.FullLoader)
3840
return config_doc is not None and config_doc.get("commitizen") is not None
3941

40-
def _parse_setting(self, data: bytes | str) -> None:
42+
def _load_document(self, data: bytes | str) -> Any:
4143
"""We expect to have a section in cz.yaml looking like
4244
4345
```
4446
commitizen:
4547
name: cz_conventional_commits
4648
```
4749
"""
48-
try:
49-
doc = yaml.safe_load(data)
50-
except yaml.YAMLError as e:
51-
raise InvalidConfigurationError(f"Failed to parse {self.path}: {e}")
52-
53-
try:
54-
self.settings.update(doc["commitizen"])
55-
except (KeyError, TypeError):
56-
pass
50+
return yaml.safe_load(data)
51+
52+
def _get_commitizen_section(self, doc: Any) -> Any:
53+
return doc["commitizen"]
5754

5855
def set_key(self, key: str, value: object) -> Self:
5956
with self.path.open("rb") as yaml_file:

0 commit comments

Comments
 (0)