Skip to content

Commit e1374db

Browse files
RomainTTRomain Taprest
authored andcommitted
[CLI] Improve stdin management and factorize more code
1 parent b2da268 commit e1374db

File tree

1 file changed

+59
-31
lines changed

1 file changed

+59
-31
lines changed

jsonschema/cli.py

Lines changed: 59 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def _namedAnyWithDefault(name):
116116
dest="instances",
117117
type=str,
118118
help=(
119-
"a path to a JSON instance (i.e. filename.json) "
119+
"A path to a JSON instance (i.e. filename.json) "
120120
"to validate (may be specified multiple times)"
121121
),
122122
)
@@ -156,7 +156,7 @@ def _namedAnyWithDefault(name):
156156
)
157157
parser.add_argument(
158158
"schema",
159-
help="the JSON Schema to validate with (i.e. schema.json)",
159+
help="Path to the JSON Schema to validate with (i.e. schema.json)",
160160
type=str,
161161
)
162162

@@ -173,34 +173,47 @@ def parse_args(args):
173173
arguments = vars(parser.parse_args(args=args or ["--help"]))
174174
if arguments["validator"] is None:
175175
arguments["validator"] = validator_for(arguments["schema"])
176+
if arguments["instances"] is None:
177+
arguments["instances"] = []
176178
return arguments
177179

178180

179-
def make_validator(schema_path, validator_class):
180-
schema_obj = _load_json_file(schema_path)
181-
validator = validator_class(schema=schema_obj)
182-
validator.check_schema(schema_obj)
181+
def make_validator(schema_path, validator_class, output_writer):
182+
try:
183+
schema_obj = _load_json_file(schema_path)
184+
except (json.JSONDecodeError, FileNotFoundError) as exc:
185+
output_writer.write_parsing_error(schema_path, exc)
186+
raise exc
187+
188+
try:
189+
validator = validator_class(schema=schema_obj)
190+
validator.check_schema(schema_obj)
191+
except SchemaError as exc:
192+
output_writer.write_valid_error(schema_path, exc)
193+
raise exc
194+
183195
return validator
184196

185197

186-
def validate_instance(instance, validator, output_writer):
187-
# Load the instance
188-
if isinstance(instance, str):
189-
instance_name = instance
190-
try:
191-
instance_obj = _load_json_file(instance)
192-
except json.JSONDecodeError as exc:
193-
output_writer.write_parsing_error(instance_name, exc)
194-
raise exc
195-
elif isinstance(instance, dict):
196-
instance_name = "stdin"
197-
instance_obj = instance
198-
else:
199-
raise ValueError(
200-
"Invalid type for instance: {}".format(type(instance))
201-
)
198+
def load_stdin(stdin, output_writer):
199+
try:
200+
instance_obj = json.load(stdin)
201+
except json.JSONDecodeError as exc:
202+
output_writer.write_parsing_error("stdin", exc)
203+
raise exc
204+
return instance_obj
205+
202206

203-
# Validate the instance
207+
def load_instance_file(instance_path, output_writer):
208+
try:
209+
instance_obj = _load_json_file(instance_path)
210+
except (json.JSONDecodeError, FileNotFoundError) as exc:
211+
output_writer.write_parsing_error(instance_path, exc)
212+
raise exc
213+
return instance_obj
214+
215+
216+
def validate_instance(instance_name, instance_obj, validator, output_writer):
204217
instance_errored = False
205218
for error in validator.iter_errors(instance_obj):
206219
instance_errored = True
@@ -225,18 +238,33 @@ def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin):
225238
)
226239

227240
try:
228-
validator = make_validator(arguments["schema"], arguments["validator"])
229-
except json.JSONDecodeError as exc:
230-
output_writer.write_parsing_error(arguments["schema"], exc)
231-
return False
232-
except SchemaError as exc:
233-
output_writer.write_valid_error(arguments["schema"], exc)
241+
validator = make_validator(
242+
arguments["schema"],
243+
arguments["validator"],
244+
output_writer,
245+
)
246+
except (FileNotFoundError, json.JSONDecodeError, SchemaError):
234247
return False
235248

236249
errored = False
237-
for instance in arguments["instances"] or [json.load(stdin)]:
250+
for instance_path in arguments["instances"]:
238251
try:
239-
validate_instance(instance, validator, output_writer)
252+
validate_instance(
253+
instance_path,
254+
load_instance_file(instance_path, output_writer),
255+
validator,
256+
output_writer,
257+
)
258+
except (json.JSONDecodeError, FileNotFoundError, ValidationError):
259+
errored = True
260+
if stdin is sys.stdin and not sys.stdin.isatty():
261+
try:
262+
validate_instance(
263+
"stdin",
264+
load_stdin(stdin, output_writer),
265+
validator,
266+
output_writer,
267+
)
240268
except (json.JSONDecodeError, ValidationError):
241269
errored = True
242270

0 commit comments

Comments
 (0)