tree_repr

This commit is contained in:
Amber 2024-01-25 16:43:20 +01:00
parent 4c0ee4e244
commit ec6796ce1e
2 changed files with 85 additions and 4 deletions

View File

@ -155,9 +155,17 @@ def nerd_tree_struct(startpath, path=[]):
# path_copy = path[:]
# path_copy.append(rootnode)
if path:
path.append(rootnode)
path.append({
'name' : rootnode,
'type' : 'd',
'abs_path' : startpath,
})
else:
path = ['./']
path = [{
'name' : './',
'type' : 'd',
'abs_path' : startpath,
}]
d = {
'name' : rootnode,
@ -178,7 +186,11 @@ def nerd_tree_struct(startpath, path=[]):
d['children'].append(nerd_tree_struct(startpath+item, path=path[:]))
else:
path_copy = path[:]
path_copy.append(item)
path_copy.append({
'name' : item,
'type' : 'f',
'abs_path' : startpath + item
})
d['children'].append({
'name' : item,
@ -203,7 +215,11 @@ def find_subtree(node, node_name, results=[]):
if item_child['name'] == node_name:
results.append(item_child)
def find_tree(startpath, item_name):
def find_node(startpath, item_name):
'''
search item_name in subtree starting from startpath
Note: it finds all occurrencies
'''
rnode = nerd_tree_struct(startpath)
results = []
@ -211,7 +227,72 @@ def find_tree(startpath, item_name):
return results
def find_children(tree, item_abs_path):
'''
It returns a tuple, first value is if father of node with item_name is found,
second value represents the children of parent node
'''
if tree['abs_path'] == item_abs_path:
if not tree.get('children'):
tree['children'] = []
return (True, tree['children'])
children = tree.get('children') or []
if not children:
return (False, [])
for child in children:
found, fchildren = find_children(child, item_abs_path)
if found:
return (True, fchildren)
return (False, [])
def find_tree_struct(startpath, item_name):
'''
Bad!!!
'''
results = find_node(startpath, item_name)
if not results:
return {}
tree_struct = {}
for node in results:
path = node['path']
for n,p in enumerate(path):
pcopy = p.copy()
pname = p['name']
if pname == './':
if tree_struct: continue
tree_struct = pcopy
tree_struct['children'] = []
continue
parent = path[n-1]
found, children = find_children(tree_struct, parent['abs_path'])
if not found:
raise Exception('Bug!!!')
islastpath = True if (n== len(path)-1) else False
if not islastpath: children.append(pcopy)
else : children.append(node)
return tree_struct
def nerd_tree(startpath):
tree_struct = nerd_tree_struct(startpath)
tree_txt = nerd_tree_from_struct(tree_struct)
print(tree_txt)
def find_nerd_tree(startpath, item_name):
tree_struct = find_tree_struct(startpath, item_name)
if not tree_struct:
print('No results')
return
tree_txt = nerd_tree_from_struct(tree_struct)
print(tree_txt)