]> git.proxmox.com Git - mirror_frr.git/blob - python/clippy/__init__.py
Merge branch 'stable/3.0' into tmp-3.0-master-merge
[mirror_frr.git] / python / clippy / __init__.py
1 # FRR CLI preprocessor
2 #
3 # Copyright (C) 2017 David Lamparter for NetDEF, Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; either version 2 of the License, or (at your option)
8 # any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 # more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; see the file COPYING; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
19 import _clippy
20 from _clippy import parse, Graph, GraphNode
21
22 def graph_iterate(graph):
23 '''iterator yielding all nodes of a graph
24
25 nodes arrive in input/definition order, graph circles are avoided.
26 '''
27
28 queue = [(graph.first(), frozenset(), 0)]
29 while len(queue) > 0:
30 node, stop, depth = queue.pop(0)
31 yield node, depth
32
33 join = node.join()
34 if join is not None:
35 queue.insert(0, (join, stop.union(frozenset([node])), depth))
36 join = frozenset([join])
37
38 stop = join or stop
39 nnext = node.next()
40 for n in reversed(nnext):
41 if n not in stop and n is not node:
42 queue.insert(0, (n, stop, depth + 1))
43
44 def dump(graph):
45 '''print out clippy.Graph'''
46
47 for i, depth in graph_iterate(graph):
48 print('\t%s%s %r' % (' ' * (depth * 2), i.type, i.text))
49
50 def wrdiff(filename, buf):
51 '''write buffer to file if contents changed'''
52
53 expl = ''
54 if hasattr(buf, 'getvalue'):
55 buf = buf.getvalue()
56 old = None
57 try: old = open(filename, 'r').read()
58 except: pass
59 if old == buf:
60 # sys.stderr.write('%s unchanged, not written\n' % (filename))
61 return
62 with open('.new.' + filename, 'w') as out:
63 out.write(buf)
64 os.rename('.new.' + filename, filename)