From 1e552ea89c9508efbbc3e3d422ce3aed89fa0141 Mon Sep 17 00:00:00 2001 From: Nick Timkovich Date: Wed, 8 Aug 2018 18:46:29 -0500 Subject: [PATCH] Add a simple CLI tool --- setup.py | 5 +++ swagger_spec_validator/cli.py | 58 +++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 swagger_spec_validator/cli.py diff --git a/setup.py b/setup.py index 7ad4566..13670c3 100644 --- a/setup.py +++ b/setup.py @@ -45,4 +45,9 @@ "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], + entry_points={ + "console_scripts": [ + "swagger-spec-validator = swagger_spec_validator.cli:main", + ], + }, ) diff --git a/swagger_spec_validator/cli.py b/swagger_spec_validator/cli.py new file mode 100644 index 0000000..5a0f88d --- /dev/null +++ b/swagger_spec_validator/cli.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +""" +Swagger spec validator. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + + +import argparse +import sys + +from swagger_spec_validator.common import SwaggerValidationError +from swagger_spec_validator.util import validate_spec_url + + +def _extract_error_message(exc): + """ + The validators return nested errors coming from common.wrap_exception, but + other errors like invalid URLs aren't nested. Try to + """ + try: + return exc.args[1].args[0] + except IndexError: + pass + + return exc.args[0] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + + parser.add_argument("url", type=str, help="URL of Swagger spec to validate") + parser.add_argument( + "-q", + "--quiet", + action="store_true", + help="No output if validation is successful", + ) + + args = parser.parse_args() + + try: + validate_spec_url(args.url) + except SwaggerValidationError as exc: + error_message = _extract_error_message(exc) + print(error_message, file=sys.stderr) + return 1 + + if not args.quiet: + print("Validation successful!", file=sys.stderr) + + return 0 + + +if __name__ == "__main__": + sys.exit(main())