ocarina/libsaria/trees.py

63 lines
1.2 KiB
Python

# Bryan Schumaker (11/06/2010)
from libsaria.path import sep
class Tree(dict):
def __init__(self):
dict.__init__(self)
def __disp__(self, level):
return "%s (%s)", (child, self[child].value)
def disp(self, level = 0):
for child in self:
space = " " * level
fmt, vals = self.__disp__(level)
print space, fmt % vals
self[child].disp(level + 1)
def walk(self):
keys = self.keys()
keys.sort()
for key in keys:
child = self[key]
if len(child.keys()) == 0:
yield [key]
continue
for res in child.walk():
yield [key] + res
def __insert__(self, path):
path_part = path[0]
child = self.get(path_part, None)
if child == None:
child = self.__class__()
self[path_part] = child
return child
def insert(self, path):
child = self.__insert__(path)
if len(path) > 1:
child.insert(path[1:])
class FSTree(Tree):
def __init__(self, value = None):
Tree.__init__(self, value)
def walk_paths(self):
for path in self.walk():
yield sep.join(path)
def insert_path(self, base, file = None):
path = base.split(sep)
self.insert_path_split(path, file)
def insert_path_split(self, base, file = None):
path = base
if file != None:
path += [file]
self.insert(path)