summaryrefslogtreecommitdiff
path: root/jsonschema/cli.py
blob: 0126564f463e21acc06f5534366b3b1d82ba1650 (plain)
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
72
from __future__ import absolute_import
import argparse
import json
import sys

from jsonschema._reflect import namedAny
from jsonschema.validators import validator_for


def _namedAnyWithDefault(name):
    if "." not in name:
        name = "jsonschema." + name
    return namedAny(name)


def _json_file(path):
    with open(path) as file:
        return json.load(file)


parser = argparse.ArgumentParser(
    description="JSON Schema Validation CLI",
)
parser.add_argument(
    "-i", "--instance",
    action="append",
    dest="instances",
    type=_json_file,
    help="a path to a JSON instance to validate "
         "(may be specified multiple times)",
)
parser.add_argument(
    "-F", "--error-format",
    default="{error.instance}: {error.message}\n",
    help="the format to use for each error output message, specified in "
         "a form suitable for passing to str.format, which will be called "
         "with 'error' for each error",
)
parser.add_argument(
    "-V", "--validator",
    type=_namedAnyWithDefault,
    help="the fully qualified object name of a validator to use, or, for "
         "validators that are registered with jsonschema, simply the name "
         "of the class.",
)
parser.add_argument(
    "schema",
    help="the JSON Schema to validate with",
    type=_json_file,
)


def parse_args(args):
    arguments = vars(parser.parse_args(args=args or ["--help"]))
    if arguments["validator"] is None:
        arguments["validator"] = validator_for(arguments["schema"])
    return arguments


def main(args=sys.argv[1:]):
    sys.exit(run(arguments=parse_args(args=args)))


def run(arguments, stdout=sys.stdout, stderr=sys.stderr):
    error_format = arguments["error_format"]
    validator = arguments["validator"](schema=arguments["schema"])
    errored = False
    for instance in arguments["instances"] or ():
        for error in validator.iter_errors(instance):
            stderr.write(error_format.format(error=error))
            errored = True
    return errored