]>
Commit | Line | Data |
---|---|---|
e0edde6f | 1 | # Copyright (c) 2009, 2010 Nicira, Inc. |
26bb0f31 | 2 | # |
99155935 BP |
3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
4 | # you may not use this file except in compliance with the License. | |
5 | # You may obtain a copy of the License at: | |
26bb0f31 | 6 | # |
99155935 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
26bb0f31 | 8 | # |
99155935 BP |
9 | # Unless required by applicable law or agreed to in writing, software |
10 | # distributed under the License is distributed on an "AS IS" BASIS, | |
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
12 | # See the License for the specific language governing permissions and | |
13 | # limitations under the License. | |
14 | ||
99155935 BP |
15 | import getopt |
16 | import sys | |
17 | ||
18 | import ovs.json | |
6c7050b5 | 19 | |
26bb0f31 | 20 | |
99155935 | 21 | def print_json(json): |
0c4d144a | 22 | if isinstance(json, str): |
8ea171ab | 23 | print("error: %s" % json) |
99155935 BP |
24 | return False |
25 | else: | |
26 | ovs.json.to_stream(json, sys.stdout) | |
27 | sys.stdout.write("\n") | |
28 | return True | |
29 | ||
26bb0f31 | 30 | |
99155935 BP |
31 | def parse_multiple(stream): |
32 | buf = stream.read(4096) | |
33 | ok = True | |
34 | parser = None | |
35 | while len(buf): | |
36 | if parser is None and buf[0] in " \t\r\n": | |
37 | buf = buf[1:] | |
38 | else: | |
39 | if parser is None: | |
40 | parser = ovs.json.Parser() | |
41 | n = parser.feed(buf) | |
42 | buf = buf[n:] | |
43 | if len(buf): | |
44 | if not print_json(parser.finish()): | |
45 | ok = False | |
46 | parser = None | |
47 | if len(buf) == 0: | |
48 | buf = stream.read(4096) | |
49 | if parser and not print_json(parser.finish()): | |
50 | ok = False | |
51 | return ok | |
52 | ||
26bb0f31 | 53 | |
99155935 BP |
54 | def main(argv): |
55 | argv0 = argv[0] | |
56 | ||
99155935 | 57 | try: |
e6703555 | 58 | options, args = getopt.gnu_getopt(argv[1:], '', ['multiple']) |
f3068bff | 59 | except getopt.GetoptError as geo: |
99155935 BP |
60 | sys.stderr.write("%s: %s\n" % (argv0, geo.msg)) |
61 | sys.exit(1) | |
62 | ||
63 | multiple = False | |
64 | for key, value in options: | |
65 | if key == '--multiple': | |
66 | multiple = True | |
67 | else: | |
68 | sys.stderr.write("%s: unhandled option %s\n" % (argv0, key)) | |
69 | sys.exit(1) | |
70 | ||
71 | if len(args) != 1: | |
72 | sys.stderr.write("usage: %s [--multiple] INPUT.json\n" % argv0) | |
73 | sys.exit(1) | |
74 | ||
75 | input_file = args[0] | |
76 | if input_file == "-": | |
77 | stream = sys.stdin | |
78 | else: | |
79 | stream = open(input_file, "r") | |
80 | ||
81 | if multiple: | |
82 | ok = parse_multiple(stream) | |
83 | else: | |
84 | ok = print_json(ovs.json.from_stream(stream)) | |
85 | ||
86 | if not ok: | |
87 | sys.exit(1) | |
88 | ||
26bb0f31 | 89 | |
99155935 BP |
90 | if __name__ == '__main__': |
91 | main(sys.argv) |