-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathreaders.py
More file actions
71 lines (54 loc) · 1.95 KB
/
readers.py
File metadata and controls
71 lines (54 loc) · 1.95 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
from __future__ import annotations
import json
import types
import typing as t
import ruamel.yaml
from ..cachedownloader import CacheDownloader
from ..parsers import ParserSet
from ..utils import filename2path
from .errors import SchemaParseError
yaml = ruamel.yaml.YAML(typ="safe")
def _run_load_callback(schema_location: str, callback: t.Callable) -> dict:
try:
schema = callback()
# only local loads can raise the YAMLError, but catch for both cases for simplicity
except (ValueError, ruamel.yaml.error.YAMLError) as e:
raise SchemaParseError(schema_location) from e
if isinstance(schema, types.GeneratorType):
schema = list(schema)
if not isinstance(schema, dict) and not isinstance(schema, list):
raise SchemaParseError(schema_location)
return schema
class LocalSchemaReader:
FORMATS = ("json", "json5", "yaml")
def __init__(self, filename: str) -> None:
self.path = filename2path(filename)
self.filename = str(self.path)
self.parsers = ParserSet(supported_formats=self.FORMATS)
def get_ref_base(self) -> str:
return self.path.as_uri()
def _read_impl(self) -> t.Any:
return self.parsers.parse_file(self.path, default_filetype="json")
def read_schema(self) -> dict:
return _run_load_callback(self.filename, self._read_impl)
class HttpSchemaReader:
def __init__(
self,
url: str,
cache_filename: str | None,
disable_cache: bool,
) -> None:
self.url = url
self.downloader = CacheDownloader(
url,
cache_filename,
disable_cache=disable_cache,
validation_callback=json.loads,
)
def get_ref_base(self) -> str:
return self.url
def _read_impl(self) -> t.Any:
with self.downloader.open() as fp:
return json.load(fp)
def read_schema(self) -> dict:
return _run_load_callback(self.url, self._read_impl)