Skip to content

Commit 6f2ffef

Browse files
committed
fix issue_669
1 parent 506cea3 commit 6f2ffef

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

jsonschema/cli.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import argparse
88
import errno
99
import json
10+
import os
1011
import sys
1112
import traceback
1213

@@ -15,7 +16,7 @@
1516
from jsonschema import __version__
1617
from jsonschema._reflect import namedAny
1718
from jsonschema.exceptions import SchemaError
18-
from jsonschema.validators import validator_for
19+
from jsonschema.validators import validator_for, RefResolver
1920

2021

2122
class _CannotLoadFile(Exception):
@@ -178,6 +179,15 @@ def _namedAnyWithDefault(name):
178179
of the class.
179180
""",
180181
)
182+
parser.add_argument(
183+
"-r", "--local-ref",
184+
action="store_true",
185+
help="""
186+
use this option to indicate that the schema contains some references
187+
to some local files. With this option, the validator will try to
188+
resolve those references as paths relative to the given schema.
189+
""",
190+
)
181191
parser.add_argument(
182192
"--version",
183193
action="version",
@@ -251,7 +261,16 @@ def load(_):
251261
raise _CannotLoadFile()
252262
instances = ["<stdin>"]
253263

254-
validator = arguments["validator"](schema)
264+
if arguments["local_ref"]:
265+
file_prefix = "file:///{}/" if "nt" == os.name else "file://{}/"
266+
schema_dirname = os.path.dirname(arguments["schema"])
267+
resolver = RefResolver(
268+
base_uri=file_prefix.format(os.path.abspath(schema_dirname)),
269+
referrer=schema,
270+
)
271+
else:
272+
resolver = None
273+
validator = arguments["validator"](schema, resolver=resolver)
255274
exit_code = 0
256275
for each in instances:
257276
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)