Skip to content

Commit c085fd0

Browse files
bearomorphismLee-W
authored andcommitted
refactor(TomlConfig): minor cleanups for DX
1 parent 835ccb4 commit c085fd0

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

commitizen/config/toml_config.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
import os
44
from pathlib import Path
5-
from typing import TYPE_CHECKING, Any
5+
from typing import TYPE_CHECKING
66

7-
from tomlkit import exceptions, parse, table
7+
from tomlkit import TOMLDocument, exceptions, parse, table
88

99
from commitizen.exceptions import InvalidConfigurationError
1010

@@ -27,32 +27,33 @@ def __init__(self, *, data: bytes | str, path: Path) -> None:
2727
self._parse_setting(data)
2828

2929
def init_empty_config_content(self) -> None:
30+
config_doc = TOMLDocument()
3031
if os.path.isfile(self.path):
3132
with open(self.path, "rb") as input_toml_file:
32-
parser = parse(input_toml_file.read())
33-
else:
34-
parser = parse("")
33+
config_doc = parse(input_toml_file.read())
34+
35+
if config_doc.get("tool") is None:
36+
config_doc["tool"] = table()
37+
config_doc["tool"]["commitizen"] = table() # type: ignore[index]
3538

3639
with open(self.path, "wb") as output_toml_file:
37-
if parser.get("tool") is None:
38-
parser["tool"] = table()
39-
parser["tool"]["commitizen"] = table() # type: ignore[index]
4040
output_toml_file.write(
41-
parser.as_string().encode(self._settings["encoding"])
41+
config_doc.as_string().encode(self._settings["encoding"])
4242
)
4343

44-
def set_key(self, key: str, value: Any) -> Self:
44+
def set_key(self, key: str, value: object) -> Self:
4545
"""Set or update a key in the conf.
4646
4747
For now only strings are supported.
4848
We use to update the version number.
4949
"""
5050
with open(self.path, "rb") as f:
51-
parser = parse(f.read())
51+
config_doc = parse(f.read())
5252

53-
parser["tool"]["commitizen"][key] = value # type: ignore[index]
53+
config_doc["tool"]["commitizen"][key] = value # type: ignore[index]
5454
with open(self.path, "wb") as f:
55-
f.write(parser.as_string().encode(self._settings["encoding"]))
55+
f.write(config_doc.as_string().encode(self._settings["encoding"]))
56+
5657
return self
5758

5859
def _parse_setting(self, data: bytes | str) -> None:

0 commit comments

Comments
 (0)