cli.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """
  2. The ``jsonschema`` command line.
  3. """
  4. from __future__ import absolute_import
  5. import argparse
  6. import json
  7. import sys
  8. from jsonschema import __version__
  9. from jsonschema._reflect import namedAny
  10. from jsonschema.validators import validator_for
  11. def _namedAnyWithDefault(name):
  12. if "." not in name:
  13. name = "jsonschema." + name
  14. return namedAny(name)
  15. def _json_file(path):
  16. with open(path) as file:
  17. return json.load(file)
  18. parser = argparse.ArgumentParser(
  19. description="JSON Schema Validation CLI",
  20. )
  21. parser.add_argument(
  22. "-i", "--instance",
  23. action="append",
  24. dest="instances",
  25. type=_json_file,
  26. help=(
  27. "a path to a JSON instance (i.e. filename.json) "
  28. "to validate (may be specified multiple times)"
  29. ),
  30. )
  31. parser.add_argument(
  32. "-F", "--error-format",
  33. default="{error.instance}: {error.message}\n",
  34. help=(
  35. "the format to use for each error output message, specified in "
  36. "a form suitable for passing to str.format, which will be called "
  37. "with 'error' for each error"
  38. ),
  39. )
  40. parser.add_argument(
  41. "-V", "--validator",
  42. type=_namedAnyWithDefault,
  43. help=(
  44. "the fully qualified object name of a validator to use, or, for "
  45. "validators that are registered with jsonschema, simply the name "
  46. "of the class."
  47. ),
  48. )
  49. parser.add_argument(
  50. "--version",
  51. action="version",
  52. version=__version__,
  53. )
  54. parser.add_argument(
  55. "schema",
  56. help="the JSON Schema to validate with (i.e. schema.json)",
  57. type=_json_file,
  58. )
  59. def parse_args(args):
  60. arguments = vars(parser.parse_args(args=args or ["--help"]))
  61. if arguments["validator"] is None:
  62. arguments["validator"] = validator_for(arguments["schema"])
  63. return arguments
  64. def main(args=sys.argv[1:]):
  65. sys.exit(run(arguments=parse_args(args=args)))
  66. def run(arguments, stdout=sys.stdout, stderr=sys.stderr):
  67. error_format = arguments["error_format"]
  68. validator = arguments["validator"](schema=arguments["schema"])
  69. validator.check_schema(arguments["schema"])
  70. errored = False
  71. for instance in arguments["instances"] or ():
  72. for error in validator.iter_errors(instance):
  73. stderr.write(error_format.format(error=error))
  74. errored = True
  75. return errored