Skip to content

Commit 71accf7

Browse files
committed
Support lazy files with pyjson5
In order for pyjson5 to be satisfied, it must be passed the real file descriptor (or something satisfying `io.IOBase`). For simplicity, pass it the underlying open() result. Also improve the file close behavior using a `finally` block.
1 parent 59a7816 commit 71accf7

File tree

2 files changed

+19
-10
lines changed

2 files changed

+19
-10
lines changed

src/check_jsonschema/cli/param_types.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def convert(
109109
return t.cast(t.Type[jsonschema.protocols.Validator], result)
110110

111111

112-
class _CustomLazyFile(click.utils.LazyFile):
112+
class CustomLazyFile(click.utils.LazyFile):
113113
def __init__(
114114
self,
115115
filename: str | os.PathLike[str],
@@ -150,7 +150,7 @@ def convert(
150150

151151
value_: str | os.PathLike[str] = t.cast("str | os.PathLike[str]", value)
152152

153-
lf = _CustomLazyFile(value_, mode="rb")
153+
lf = CustomLazyFile(value_, mode="rb")
154154
if ctx is not None:
155155
ctx.call_on_close(lf.close_intelligently)
156156
return t.cast(t.IO[bytes], lf)

src/check_jsonschema/instance_loader.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import io
44
import typing as t
55

6+
from check_jsonschema.cli.param_types import CustomLazyFile
7+
68
from .parsers import ParseError, ParserSet
79
from .transforms import Transform
810

@@ -35,14 +37,21 @@ def iter_files(self) -> t.Iterator[tuple[str, ParseError | t.Any]]:
3537
name = "<stdin>"
3638
else:
3739
raise ValueError(f"File {file} has no name attribute")
40+
3841
try:
39-
data: t.Any = self._parsers.parse_data_with_path(
40-
file, name, self._default_filetype
41-
)
42-
except ParseError as err:
43-
data = err
44-
else:
45-
data = self._data_transform(data)
42+
if isinstance(file, CustomLazyFile):
43+
stream = file.open()
44+
else:
45+
stream = file
4646

47-
file.close()
47+
try:
48+
data: t.Any = self._parsers.parse_data_with_path(
49+
stream, name, self._default_filetype
50+
)
51+
except ParseError as err:
52+
data = err
53+
else:
54+
data = self._data_transform(data)
55+
finally:
56+
file.close()
4857
yield (name, data)

0 commit comments

Comments
 (0)