You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.1 KiB

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