Skip to content

Commit c50f40d

Browse files
committed
fix issue_669
1 parent 506cea3 commit c50f40d

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

jsonschema/cli.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
"""
22
The ``jsonschema`` command line.
33
"""
4-
54
from json import JSONDecodeError
65
from textwrap import dedent
76
import argparse
87
import errno
98
import json
9+
import os
1010
import sys
1111
import traceback
1212

@@ -15,7 +15,7 @@
1515
from jsonschema import __version__
1616
from jsonschema._reflect import namedAny
1717
from jsonschema.exceptions import SchemaError
18-
from jsonschema.validators import validator_for
18+
from jsonschema.validators import validator_for, RefResolver
1919

2020

2121
class _CannotLoadFile(Exception):
@@ -178,6 +178,15 @@ def _namedAnyWithDefault(name):
178178
of the class.
179179
""",
180180
)
181+
parser.add_argument(
182+
"-r", "--local-ref",
183+
action="store_true",
184+
help="""
185+
use this option to indicate that the schema contains some references
186+
to some local files. With this option, the validator will try to
187+
resolve those references as paths relative to the given schema.
188+
""",
189+
)
181190
parser.add_argument(
182191
"--version",
183192
action="version",
@@ -251,7 +260,16 @@ def load(_):
251260
raise _CannotLoadFile()
252261
instances = ["<stdin>"]
253262

254-
validator = arguments["validator"](schema)
263+
if arguments["local_ref"]:
264+
file_prefix = "file:///{}/" if "nt" == os.name else "file://{}/"
265+
schema_dirname = os.path.dirname(arguments["schema"])
266+
resolver = RefResolver(
267+
base_uri=file_prefix.format(os.path.abspath(schema_dirname)),
268+
referrer=schema,
269+
)
270+
else:
271+
resolver = None
272+
validator = arguments["validator"](schema, resolver=resolver)
255273
exit_code = 0
256274
for each in instances:
257275
try:

jsonschema/tests/test_cli.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -683,6 +683,23 @@ def test_successful_validation__of_just_the_schema_pretty_output(self):
683683
stderr="",
684684
)
685685

686+
def test_successful_validation_with_specifying_base_uri(self):
687+
schema = """\
688+
{"type": "object", "properties": {"KEY1":
689+
{"$ref": "schema.json#definitions/schemas"}},
690+
"definitions": {"schemas": {"type": "string"}}}
691+
"""
692+
fp = open("schema.json", "w+")
693+
fp.write(schema)
694+
fp.close()
695+
self.assertOutputs(
696+
files=dict(some_schema=schema, some_instance='{"KEY1": "1"}'),
697+
argv=["-i", "some_instance", "-r", "some_schema"],
698+
stdout="",
699+
stderr="",
700+
)
701+
os.remove("schema.json")
702+
686703
def test_real_validator(self):
687704
self.assertOutputs(
688705
files=dict(some_schema='{"minimum": 30}', some_instance="37"),

0 commit comments

Comments
 (0)