Skip to content

Commit

Permalink
fix(conf): handle parse error when init (#856)
Browse files Browse the repository at this point in the history
* test(conf): invalid contents already exist in file

handle parse error so that the error message looks better.

* fix(conf): handle parse error when init

* refactor(json_config): add parse error message from json lib

---------

Co-authored-by: Santiago Fraire Willemoes <[email protected]>
  • Loading branch information
Bogay and woile authored Sep 22, 2023
1 parent a378c2a commit 7ffb895
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 6 deletions.
4 changes: 2 additions & 2 deletions commitizen/config/json_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ def _parse_setting(self, data: bytes | str) -> None:
"""
try:
doc = json.loads(data)
except json.JSONDecodeError:
raise InvalidConfigurationError(f"Failed to parse {self.path}")
except json.JSONDecodeError as e:
raise InvalidConfigurationError(f"Failed to parse {self.path}: {e}")

try:
self.settings.update(doc["commitizen"])
Expand Down
9 changes: 7 additions & 2 deletions commitizen/config/toml_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@

from tomlkit import exceptions, parse, table

from commitizen.exceptions import InvalidConfigurationError
from .base_config import BaseConfig


class TomlConfig(BaseConfig):
def __init__(self, *, data: bytes | str, path: Path | str):
super(TomlConfig, self).__init__()
self.is_empty_config = False
self._parse_setting(data)
self.add_path(path)
self._parse_setting(data)

def init_empty_config_content(self):
if os.path.isfile(self.path):
Expand Down Expand Up @@ -50,7 +51,11 @@ def _parse_setting(self, data: bytes | str) -> None:
name = "cz_conventional_commits"
```
"""
doc = parse(data)
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
except exceptions.NonExistentKey:
Expand Down
11 changes: 9 additions & 2 deletions commitizen/config/yaml_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import yaml

from commitizen.git import smart_open
from commitizen.exceptions import InvalidConfigurationError

from .base_config import BaseConfig

Expand All @@ -13,8 +14,8 @@ class YAMLConfig(BaseConfig):
def __init__(self, *, data: bytes | str, path: Path | str):
super(YAMLConfig, self).__init__()
self.is_empty_config = False
self._parse_setting(data)
self.add_path(path)
self._parse_setting(data)

def init_empty_config_content(self):
with smart_open(self.path, "a", encoding=self.encoding) as json_file:
Expand All @@ -28,7 +29,13 @@ def _parse_setting(self, data: bytes | str) -> None:
name: cz_conventional_commits
```
"""
doc = yaml.safe_load(data)
import yaml.scanner

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):
Expand Down
22 changes: 22 additions & 0 deletions tests/test_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import yaml

from commitizen import config, defaults, git
from commitizen.exceptions import InvalidConfigurationError

PYPROJECT = """
[tool.commitizen]
Expand Down Expand Up @@ -177,6 +178,13 @@ def test_init_empty_config_content_with_existing_content(self, tmpdir):
with open(path, "r", encoding="utf-8") as toml_file:
assert toml_file.read() == existing_content + "\n[tool.commitizen]\n"

def test_init_with_invalid_config_content(self, tmpdir):
existing_content = "invalid toml content"
path = tmpdir.mkdir("commitizen").join(".cz.toml")

with pytest.raises(InvalidConfigurationError, match=r"\.cz\.toml"):
config.TomlConfig(data=existing_content, path=path)


class TestJsonConfig:
def test_init_empty_config_content(self, tmpdir):
Expand All @@ -187,6 +195,13 @@ def test_init_empty_config_content(self, tmpdir):
with open(path, "r", encoding="utf-8") as json_file:
assert json.load(json_file) == {"commitizen": {}}

def test_init_with_invalid_config_content(self, tmpdir):
existing_content = "invalid json content"
path = tmpdir.mkdir("commitizen").join(".cz.json")

with pytest.raises(InvalidConfigurationError, match=r"\.cz\.json"):
config.JsonConfig(data=existing_content, path=path)


class TestYamlConfig:
def test_init_empty_config_content(self, tmpdir):
Expand All @@ -196,3 +211,10 @@ def test_init_empty_config_content(self, tmpdir):

with open(path, "r") as yaml_file:
assert yaml.safe_load(yaml_file) == {"commitizen": {}}

def test_init_with_invalid_content(self, tmpdir):
existing_content = "invalid: .cz.yaml: content: maybe?"
path = tmpdir.mkdir("commitizen").join(".cz.yaml")

with pytest.raises(InvalidConfigurationError, match=r"\.cz\.yaml"):
config.YAMLConfig(data=existing_content, path=path)

0 comments on commit 7ffb895

Please sign in to comment.