summaryrefslogtreecommitdiff
path: root/tools/orderedtree.py
blob: def8928d998614dc4db535e48c1e871674a00742 (plain)
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
#!/usr/bin/env python

# Copyright (c) 2017, NORDUnet A/S.
# See LICENSE for licensing information.

class OrderDict(dict):
    def __init__(self):
        self._order = []
        dict.__init__({})
    def __setitem__(self, key, value):
        if key not in self:
            self._order.append(key)
        super(OrderDict, self).__setitem__(key, value)
    def iterkeys(self):
        return iter(self._order)

class TreeNode():
    def __init__(self):
        self.entry = None
        self._children = OrderDict()
    def add(self, k, e, subtree=None):
        if subtree != None:
            self._children[k] = subtree
        else:
            self._children[k] = TreeNode()
        self._children[k].entry = e
    def __getitem__(self, key):
        return self._children[key]
    def iterkeys(self):
        return self._children.iterkeys()
    def __contains__(self, key):
        return key in self._children
    def walk(self, keys):
        node = self
        for k in keys:
            node = node[k]
        return node
    def __str__(self):
        s = str(self.entry) + "\n"
        for k in self.iterkeys():
            s += str(k) + ":\n"
            for row in str(self._children[k]).split("\n"):
                if row:
                    s += "    " + row + "\n"
        return s