forked from vhosakot/yang_to_xml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyanggen
310 lines (277 loc) · 11.3 KB
/
pyanggen
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
#!/usr/bin/env python
import sys
import os
import optparse
import re
import pyang
from pyang import plugin
from pyang import error
from pyang import util
from pyang import hello
def run():
usage = """%prog [options] [<filename>...]
Validates the YANG module in <filename> (or stdin), and all its dependencies."""
plugindirs = []
# check for --plugindir
idx = 1
while '--plugindir' in sys.argv[idx:]:
idx = idx + sys.argv[idx:].index('--plugindir')
plugindirs.append(sys.argv[idx+1])
idx = idx + 1
plugin.init(plugindirs)
fmts = {}
for p in plugin.plugins:
p.add_output_format(fmts)
optlist = [
# use capitalized versions of std options help and version
optparse.make_option("-h", "--help",
action="help",
help="Show this help message and exit"),
optparse.make_option("-v", "--version",
action="version",
help="Show version number and exit"),
optparse.make_option("-e", "--list-errors",
dest="list_errors",
action="store_true",
help="Print a listing of all error and warning " \
"codes and exit."),
optparse.make_option("--print-error-code",
dest="print_error_code",
action="store_true",
help="On errors, print the error code instead " \
"of the error message."),
optparse.make_option("-W",
dest="warnings",
action="append",
default=[],
metavar="WARNING",
help="If WARNING is 'error', treat all warnings " \
"as errors, except any listed WARNING. " \
"If WARNING is 'none', do not report any " \
"warnings."),
optparse.make_option("-E",
dest="errors",
action="append",
default=[],
metavar="WARNING",
help="Treat each WARNING as an error. For a " \
"list of warnings, use --list-errors."),
optparse.make_option("--canonical",
dest="canonical",
action="store_true",
help="Validate the module(s) according to the " \
"canonical YANG order."),
optparse.make_option("--max-line-length",
type="int",
dest="max_line_len"),
optparse.make_option("--max-identifier-length",
type="int",
dest="max_identifier_len"),
optparse.make_option("-f", "--format",
dest="format",
help="Convert to FORMAT. Supported formats " \
"are: " + ', '.join(list(fmts.keys()))),
optparse.make_option("-o", "--output",
dest="outfile",
help="Write the output to OUTFILE instead " \
"of stdout."),
optparse.make_option("-p", "--path",
dest="path",
default=[],
action="append",
help=os.pathsep + "-separated search path for yin"
" and yang modules"),
optparse.make_option("--plugindir",
dest="plugindir",
help="Load pyang plugins from PLUGINDIR"),
optparse.make_option("--strict",
dest="strict",
action="store_true",
help="Force strict YANG compliance."),
optparse.make_option("--trim-yin",
dest="trim_yin",
action="store_true",
help="In YIN input modules, trim whitespace "
"in textual arguments."),
optparse.make_option("-L", "--hello",
dest="hello",
action="store_true",
help="Filename of a server's hello message is "
"given instead of module filename(s)."),
]
optparser = optparse.OptionParser(usage, add_help_option = False)
optparser.version = '%prog ' + pyang.__version__
optparser.add_options(optlist)
for p in plugin.plugins:
p.add_opts(optparser)
(o, args) = optparser.parse_args()
if o.list_errors == True:
for tag in error.error_codes:
(level, fmt) = error.error_codes[tag]
if error.is_warning(level):
print("Warning: %s" % tag)
else:
print("Error: %s" % tag)
print("Message: %s" % fmt)
print("")
sys.exit(0)
if o.outfile != None and o.format == None:
sys.stderr.write("no format specified\n")
sys.exit(1)
filenames = args
path = ":".join(o.path)
repos = pyang.FileRepository(path)
ctx = pyang.Context(repos)
ctx.opts = o
ctx.canonical = o.canonical
ctx.max_line_len = o.max_line_len
ctx.max_identifier_len = o.max_identifier_len
ctx.trim_yin = o.trim_yin
ctx.hello = False # data model from hello?
for p in plugin.plugins:
p.setup_ctx(ctx)
if o.format != None:
if o.format not in fmts:
sys.stderr.write("unsupported format '%s'\n" % o.format)
sys.exit(1)
emit_obj = fmts[o.format]
emit_obj.setup_fmt(ctx)
else:
emit_obj = None
exit_code = 0
modules = []
if o.hello:
if len(filenames) > 1:
sys.stderr.write("multiple hello files given\n")
sys.exit(1)
if filenames:
try:
fd = open(filenames[0], "rb")
except IOError as ex:
sys.stderr.write("error %s: %s\n" % (filenames[0], str(ex)))
sys.exit(1)
elif sys.version < "3":
fd = sys.stdin
else:
fd = sys.stdin.buffer
hel = hello.HelloParser().parse(fd)
ctx.capabilities = hel.registered_capabilities()
ctx.hello = True
for (mn,rev) in hel.yang_modules():
mod = ctx.search_module(0, mn, rev)
if mod is None:
emarg = mn
if rev: emarg += "@" + rev
sys.stderr.write(
"module '%s' specified in hello not found.\n" % emarg)
sys.exit(1)
# Get all features declared in mod
mod.i_active_features=[]
for fea in hel.get_features(mn):
if fea in mod.i_features:
mod.i_active_features.append(fea)
else:
sys.stderr.write(
"feature '%s' specified in hello not "
"declared in module '%s'.\n" % (fea,mn))
sys.exit(1)
modules.append(mod)
else:
if len(filenames) == 0:
text = sys.stdin.read()
module = ctx.add_module('<stdin>', text)
if module is None:
exit_code = 1
else:
modules.append(module)
if (len(filenames) > 1 and
emit_obj is not None and
not emit_obj.multiple_modules):
sys.stderr.write("too many files to convert\n")
sys.exit(1)
r = re.compile(r"^(.*?)(\@(\d{4}-\d{2}-\d{2}))?\.(yang|yin)$")
for filename in filenames:
try:
fd = open(filename)
text = fd.read()
except IOError as ex:
sys.stderr.write("error %s: %s\n" % (filename, str(ex)))
sys.exit(1)
m = r.search(filename)
if m is not None:
(name, _dummy, rev, format) = m.groups()
name = os.path.basename(name)
module = ctx.add_module(filename, text, format, name, rev,
expect_failure_error=False)
else:
module = ctx.add_module(filename, text)
if module is None:
exit_code = 1
else:
modules.append(module)
modulenames = []
for m in modules:
modulenames.append(m.arg)
for s in m.search('include'):
modulenames.append(s.arg)
if emit_obj is not None and len(modules) > 0:
emit_obj.pre_validate(ctx, modules)
ctx.validate()
if emit_obj is not None and len(modules) > 0:
emit_obj.post_validate(ctx, modules)
def keyfun(e):
if e[0].ref == filenames[0]:
return 0
else:
return 1
ctx.errors.sort(key=lambda e: (e[0].ref, e[0].line))
if len(filenames) > 0:
# first print error for the first filename given
ctx.errors.sort(key=keyfun)
for (epos, etag, eargs) in ctx.errors:
if (ctx.implicit_errors == False and
hasattr(epos.top, 'i_modulename') and
epos.top.arg not in modulenames and
epos.top.i_modulename not in modulenames and
epos.ref not in filenames):
# this module was added implicitly (by import); skip this error
# the code includes submodules
continue
elevel = error.err_level(etag)
if error.is_warning(elevel) and etag not in o.errors:
kind = "warning"
if 'error' in o.warnings and etag not in o.warnings:
kind = "error"
exit_code = 1
elif 'none' in o.warnings:
continue
else:
kind = "error"
exit_code = 1
if o.print_error_code == True:
sys.stderr.write(str(epos) + ': %s: %s\n' % (kind, etag))
else:
sys.stderr.write(str(epos) + ': %s: ' % kind + \
error.err_to_str(etag, eargs) + '\n')
if emit_obj is not None and len(modules) > 0:
tmpfile = None
if o.outfile == None:
fd = sys.stdout
else:
tmpfile = o.outfile + ".tmp"
fd = open(tmpfile, "w+")
try:
emit_obj.emit(ctx, modules, fd)
except error.EmitError as e:
if e.msg != "":
sys.stderr.write(e.msg + '\n')
if tmpfile != None:
fd.close()
os.remove(tmpfile)
sys.exit(e.exit_code)
if tmpfile != None:
fd.close()
os.rename(tmpfile, o.outfile)
sys.exit(exit_code)
if __name__ == '__main__':
run()