-
-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path__init__.py
More file actions
96 lines (73 loc) · 2.94 KB
/
__init__.py
File metadata and controls
96 lines (73 loc) · 2.94 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# encoding: utf-8
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
from abc import ABC, abstractmethod
from importlib import import_module
from typing import TYPE_CHECKING, Any, Optional, Protocol, Type
from ..schema import OutputFormat
if TYPE_CHECKING:
from ..schema import SchemaVersion
class ValidationError:
"""Validation failed with this specific error.
Use :attr:`~data` to access the content.
"""
data: Any
def __init__(self, data: Any) -> None:
self.data = data
def __repr__(self) -> str:
return repr(self.data)
def __str__(self) -> str:
return str(self.data)
class Validator(Protocol):
"""Validator protocol"""
def validate_str(self, data: str) -> Optional[ValidationError]:
"""Validate a string
:param data: the data string to validate
:return: validation error
:retval None: if `data` is valid
:retval ValidationError: if `data` is invalid
"""
...
class BaseValidator(ABC, Validator):
"""BaseValidator"""
def __init__(self, schema_version: 'SchemaVersion') -> None:
self.__schema_version = schema_version
if not self._schema_file:
raise ValueError(f'unsupported schema_version: {schema_version}')
@property
def schema_version(self) -> 'SchemaVersion':
"""get the schema version."""
return self.__schema_version
@property
@abstractmethod
def output_format(self) -> OutputFormat:
"""get the format."""
...
@property
@abstractmethod
def _schema_file(self) -> Optional[str]:
"""get the schema file according to schema version."""
...
def get_instance(output_format: OutputFormat, schema_version: 'SchemaVersion') -> BaseValidator:
"""get the default validator for a certain `OutputFormat`"""
if not isinstance(output_format, OutputFormat):
raise TypeError(f"unexpected output_format: {output_format!r}")
try:
module = import_module(f'.{output_format.name.lower()}', __package__)
except ImportError as error: # pragma: no cover
raise ValueError(f'Unknown output_format: {output_format.name}') from error
klass: Optional[Type[BaseValidator]] = getattr(module, f'{output_format.name.capitalize()}Validator', None)
if klass is None: # pragma: no cover
raise ValueError(f'Missing Validator for {output_format.name}')
return klass(schema_version)