Coverage for birdplan/yaml/ruamel.py: 100%
21 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-23 03:27 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-23 03:27 +0000
1#
2# SPDX-License-Identifier: GPL-3.0-or-later
3#
4# Copyright (C) 2019-2024, AllWorldIT.
5#
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program. If not, see <https://www.gnu.org/licenses/>.
19"""BirdPlan YAML handling."""
21import io
22import pathlib
23from typing import Any, Optional, Union
25import ruamel.yaml as ryaml
26from ruamel.yaml import __with_libyaml__
27from ruamel.yaml.error import YAMLError
29from .base import YAMLBase
31__all__ = ["YAML", "YAMLError", "__with_libyaml__"]
34class YAML(YAMLBase):
35 """YAML class."""
37 _ryaml: ryaml.YAML
39 def __init__(self) -> None:
40 """Initialize our parser YAML."""
42 # Create a YAML object
43 self._yaml = ryaml.YAML(typ="safe")
45 # Don't use flow style as its harder to diff
46 self._yaml.default_flow_style = False
48 # Register the custom ctag 'tag:yaml.org,2002:python/tuple' to handle tuples
49 self._yaml.constructor.add_constructor(
50 "tag:yaml.org,2002:python/tuple", lambda loader, node: tuple(loader.construct_sequence(node))
51 )
52 self._yaml.representer.add_representer(
53 tuple, lambda dumper, data: dumper.represent_sequence("tag:yaml.org,2002:python/tuple", data, flow_style=True)
54 )
56 def load(self, yaml: Union[str, pathlib.Path, io.IOBase]) -> Any:
57 """Load YAML string."""
58 return self._yaml.load(yaml)
60 def dump(self, data: Any, stream: Optional[Union[pathlib.Path, io.IOBase]] = None) -> Any:
61 """Dump to YAML."""
62 if stream:
63 return self._yaml.dump(
64 data,
65 stream,
66 )
68 # Create a string IO object and dump the YAML data to it
69 dumpstr = io.StringIO() # pragma: no cover
70 with dumpstr: # pragma: no cover
71 self._yaml.dump(data, dumpstr)
72 return dumpstr.getvalue()