77 import pathlib2 as pathlib
88import sys
99
10-
11- from openapi_spec_validator import validate_spec_url , validate_v2_spec_url
10+ from openapi_spec_validator import (
11+ openapi_v2_spec_validator , openapi_v3_spec_validator , all_urls_handler ,
12+ file_object_handler ,
13+ )
1214from openapi_spec_validator .exceptions import ValidationError
1315
1416logger = logging .getLogger (__name__ )
1820)
1921
2022
23+ def read_from_stdin (filename ):
24+ return file_object_handler (sys .stdin ), ''
25+
26+
27+ def read_from_filename (filename ):
28+ if not os .path .isfile (filename ):
29+ raise SystemError ("No such file {0}" .format (filename ))
30+
31+ filename = os .path .abspath (filename )
32+ uri = pathlib .Path (filename ).as_uri ()
33+ return all_urls_handler (uri ), uri
34+
35+
2136def main (args = None ):
2237 parser = argparse .ArgumentParser ()
2338 parser .add_argument ('filename' , help = "Absolute or relative path to file" )
@@ -29,21 +44,34 @@ def main(args=None):
2944 default = '3.0.0'
3045 )
3146 args = parser .parse_args (args )
32- filename = args .filename
33- filename = os .path .abspath (filename )
47+
48+ # choose source
49+ reader = read_from_filename
50+ if args .filename == '-' :
51+ reader = read_from_stdin
52+
53+ # read source
54+ try :
55+ spec , spec_url = reader (args .filename )
56+ except Exception as exc :
57+ print (exc )
58+ sys .exit (1 )
59+
3460 # choose the validator
35- if args .schema == '2.0' :
36- validate_url = validate_v2_spec_url
37- elif args .schema == '3.0.0' :
38- validate_url = validate_spec_url
61+ validators = {
62+ '2.0' : openapi_v2_spec_validator ,
63+ '3.0.0' : openapi_v3_spec_validator ,
64+ }
65+ validator = validators [args .schema ]
66+
3967 # validate
4068 try :
41- validate_url ( pathlib . Path ( filename ). as_uri () )
42- except ValidationError as e :
43- print (e )
69+ validator . validate ( spec , spec_url = spec_url )
70+ except ValidationError as exc :
71+ print (exc )
4472 sys .exit (1 )
45- except Exception as e :
46- print (e )
73+ except Exception as exc :
74+ print (exc )
4775 sys .exit (2 )
4876 else :
4977 print ('OK' )
0 commit comments