1
0
Fork 0
mirror of https://github.com/yavook/kiwi-scp.git synced 2024-11-27 22:53:00 +00:00
kiwi-scp/kiwi_scp/yaml.py

38 lines
1.1 KiB
Python
Raw Normal View History

import re
2021-11-03 16:58:18 +00:00
from typing import Optional
2021-10-20 12:32:45 +00:00
2021-10-27 11:33:26 +00:00
import ruamel.yaml
2021-10-28 11:54:02 +00:00
import ruamel.yaml.compat
from ._constants import HEADER_KIWI_CONF_NAME
2021-10-27 11:33:26 +00:00
class YAML(ruamel.yaml.YAML):
2021-12-02 16:17:42 +00:00
def __init__(self, *args, **kwargs) -> None:
2021-10-27 11:33:26 +00:00
super().__init__(*args, **kwargs)
2022-02-21 21:46:50 +00:00
self.indent(sequence=4, offset=2)
2021-10-27 11:33:26 +00:00
2021-10-28 11:54:02 +00:00
def dump(self, data, stream=None, **kwargs) -> Optional[str]:
into_str: bool = False
if stream is None:
into_str = True
stream = ruamel.yaml.compat.StringIO()
2021-10-27 11:33:26 +00:00
2021-10-28 11:54:02 +00:00
super().dump(data, stream=stream, **kwargs)
if into_str:
return stream.getvalue()
2021-10-28 11:54:02 +00:00
@staticmethod
2021-11-27 15:21:54 +00:00
def _format_kiwi_yml(yml_string: str) -> str:
2021-10-28 11:54:02 +00:00
# insert newline before every main key
2022-01-27 16:57:35 +00:00
yml_string = re.sub(r"^(\S)", r"\n\1", yml_string, flags=re.MULTILINE)
2021-10-28 11:54:02 +00:00
# load header comment from file
with open(HEADER_KIWI_CONF_NAME, 'r') as stream:
yml_string = stream.read() + yml_string
return yml_string
def dump_kiwi_yml(self, data, **kwargs) -> Optional[str]:
return self.dump(data, transform=YAML._format_kiwi_yml, **kwargs)