93 lines
1.8 KiB
Python
93 lines
1.8 KiB
Python
# Bryan Schumaker (11/06/2010)
|
|
|
|
from libsaria.path import sep
|
|
|
|
class Tree(dict):
|
|
def __init__(self):
|
|
dict.__init__(self)
|
|
|
|
def __len__(self):
|
|
count = 0;
|
|
for path in self.walk():
|
|
count += 1
|
|
return count
|
|
|
|
def __disp__(self, child, level):
|
|
return "%s", child
|
|
|
|
def disp(self, level = 0):
|
|
for child in self:
|
|
space = " " * level
|
|
fmt, vals = self.__disp__(child, 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 DLTree(Tree):
|
|
def __init__(self):
|
|
Tree.__init__(self)
|
|
self.parent = None
|
|
|
|
def walk_backwards(self, child = None):
|
|
key = None
|
|
if child != None:
|
|
key = [item[0] for item in self.items() if id(item[1]) == id(child)]
|
|
if self.parent == None:
|
|
return key
|
|
ret = self.parent.walk_backwards(self)
|
|
if key:
|
|
return ret + key
|
|
else:
|
|
return ret
|
|
|
|
def insert(self, path):
|
|
child = self.__insert__(path)
|
|
child.parent = self
|
|
if len(path) > 1:
|
|
return child.insert(path[1:])
|
|
return child
|
|
|
|
|
|
class FSTree(Tree):
|
|
def __init__(self):
|
|
Tree.__init__(self)
|
|
|
|
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):
|
|
if file == None:
|
|
self.insert(base)
|
|
else:
|
|
self.insert(base + [file])
|
|
|