-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathyaml_config.py
58 lines (43 loc) · 1.71 KB
/
yaml_config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from __future__ import annotations
from pathlib import Path
import yaml
from commitizen.git import smart_open
from commitizen.exceptions import InvalidConfigurationError
from .base_config import BaseConfig
class YAMLConfig(BaseConfig):
def __init__(self, *, data: bytes | str, path: Path | str):
super().__init__()
self.is_empty_config = False
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:
yaml.dump({"commitizen": {}}, json_file, explicit_start=True)
def _parse_setting(self, data: bytes | str) -> None:
"""We expect to have a section in cz.yaml looking like
```
commitizen:
name: cz_conventional_commits
```
"""
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"])
self.mutated_settings.update(doc["commitizen"])
except (KeyError, TypeError):
self.is_empty_config = True
def set_key(self, key, value):
"""Set or update a key in the conf.
For now only strings are supported.
We use to update the version number.
"""
with open(self.path, "rb") as yaml_file:
parser = yaml.load(yaml_file, Loader=yaml.FullLoader)
parser["commitizen"][key] = value
with smart_open(self.path, "w", encoding=self.encoding) as yaml_file:
yaml.dump(parser, yaml_file, explicit_start=True)
return self