Coverage for /opt/conda/envs/apienv/lib/python3.10/site-packages/daiquiri/core/exceptions.py: 32%
37 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-14 02:13 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-14 02:13 +0000
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3from io import StringIO
4from abc import ABC, abstractmethod
6import ruamel.yaml
9class PrettyException(Exception, ABC):
10 @abstractmethod
11 def pretty(self):
12 pass
15class SyntaxErrorYAML(PrettyException):
16 """YAML Syntax Error
18 Args:
19 error (obj): The YAMLError instance
21 """
23 def pretty(self):
24 arg = self.args[0]
25 message = "Invalid YAML Syntax\n"
26 for line in str(arg["error"]).split("\n"):
27 message += f" {line}\n"
28 return message
31def indent(text, spaces=2):
32 return "\n".join([f"{' ' * spaces}{line}" for line in text.split("\n")])
35class InvalidYAML(PrettyException):
36 """InvalidYAML Exception
38 Args:
39 message (str): Error message
40 file (str): The yaml file name
41 obj (dict): Parsed yaml dict
42 errors (dict, optional): Error dict
43 """
45 def dump(self, obj):
46 """Long discussion about dumping to stream using ruamel:
47 https://stackoverflow.com/questions/47614862/best-way-to-use-ruamel-yaml-to-dump-yaml-to-string-not-to-stream
48 """
49 yaml = ruamel.yaml.YAML()
50 string_stream = StringIO()
51 yaml.dump(obj, string_stream)
52 output_str = string_stream.getvalue()
53 string_stream.close()
54 return output_str
56 def pretty(self):
57 arg = self.args[0]
58 message = f"Invalid YAML Definition in {arg['file']}\n"
59 message += f" {arg['message']}\n"
60 message += indent(self.dump(dict(arg["obj"])), 4)
62 if "errors" in arg:
63 message += " Errors were:"
64 for k, v in arg["errors"].items():
65 message += f" {k}:\n"
66 if isinstance(v, list):
67 message += indent(self.dump(v), 6)
68 else:
69 message += indent(self.dump(dict(v)), 6)
71 return message