From 9e89283b193287960f76a3d0cd997c808524120f Mon Sep 17 00:00:00 2001 From: Bryan Schumaker Date: Sat, 6 Nov 2010 21:38:17 -0400 Subject: [PATCH] Libsaria trees libsaria.path.make_tree(path) will return a tree rooted at path --- libsaria/path.py | 23 +++++++++++++++++++++++ libsaria/trees.py | 40 ++++++++++++++++++++++++++++++++++++++++ tests/trees.py | 17 +++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 libsaria/trees.py create mode 100644 tests/trees.py diff --git a/libsaria/path.py b/libsaria/path.py index 286de825..e6288a64 100644 --- a/libsaria/path.py +++ b/libsaria/path.py @@ -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 diff --git a/libsaria/trees.py b/libsaria/trees.py new file mode 100644 index 00000000..a93e8aa9 --- /dev/null +++ b/libsaria/trees.py @@ -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) + diff --git a/tests/trees.py b/tests/trees.py new file mode 100644 index 00000000..935d040e --- /dev/null +++ b/tests/trees.py @@ -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