Libsaria trees

libsaria.path.make_tree(path) will return a tree rooted at path
This commit is contained in:
Bryan Schumaker 2010-11-06 21:38:17 -04:00
parent 0157d2bcf3
commit 9e89283b19
3 changed files with 80 additions and 0 deletions

View File

@ -17,8 +17,10 @@ sep = os.sep
cp = None
saria_dir = None
plugin_dir = None
make_tree = None
shutil = None
Tree = None
s_dir = None
p_dir = None
@ -67,3 +69,24 @@ cp = cp_once
def mkdir(path):
if not exists(path):
makedir(path)
def make_tree_once(path):
global Tree
from trees import Tree
global make_tree
make_tree = make_tree_rest
return make_tree(path)
def make_tree_rest(path):
global Tree
tree = Tree()
count = 0
for root,dirs,files in walk(path):
stripped_root = root.strip(sep)
split_root = root.split(sep)
for file in files:
tree.insert(split_root + [file])
count += 1
tree.value = count
return tree
make_tree = make_tree_once

40
libsaria/trees.py Normal file
View File

@ -0,0 +1,40 @@
# Bryan Schumaker (11/06/2010)
class Tree(dict):
def __init__(self, value = None):
#self.children = dict()
self.value = value
def disp(self, level = 0):
#children = self.children
for child in self:
space = " " * level
print space, "%s (%s)" % (child, self[child].value)
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, values=[]):
path_part = path[0]
value = path_part
if len(values) > 0:
value = values[0]
values = values[1:]
child = self.get(path_part, None)
if child == None:
child = self.__class__(value)
self[path_part] = child
if len(path) > 1:
child.insert(path[1:], values)

17
tests/trees.py Normal file
View File

@ -0,0 +1,17 @@
# Bryan Schumaker (11/06/2010)
from libsaria import trees
#tree = trees.Tree()
#tree.insert(["home", "bjschuma", "Music"])
#tree.insert(["home", "bjschuma", "Videos"])
#tree.insert(["home", "other", "Music"])
from libsaria import path
tree = path.make_tree("/home/bjschuma/Music")
#print tree
print tree.value
#tree.disp()
for path in tree.walk():
print path