Spaces:
Running
Running
File size: 5,151 Bytes
9c56a9c c5ca5f9 17f4503 c5ca5f9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | """Virtual folder tree changes (explorer). The tree is stored in the database (folders table), not on disk."""
from __future__ import annotations
import copy
from typing import Any
def _norm(p: str) -> str:
return (p or "").replace("\\", "/").strip("/")
def tree_has_folder(tree: list, folder_path: str) -> bool:
"""True if folder_path exists as a folder in the tree (empty path = root)."""
fp = _norm(folder_path)
if not fp:
return True
parts = [x for x in fp.split("/") if x]
cur = tree
for part in parts:
found = None
for n in cur:
if n.get("type") == "folder" and n.get("name") == part:
found = n
break
if not found:
return False
cur = found.get("children") or []
return True
def join_rel(parent: str, name: str) -> str:
p = _norm(parent)
return f"{p}/{name}" if p else name
def ensure_folder_chain(tree: list, parent_path: str) -> list:
"""Return the children list under parent_path (create folders as needed)."""
if not _norm(parent_path):
return tree
parts = [x for x in _norm(parent_path).split("/") if x]
cur = tree
acc: list[str] = []
for part in parts:
acc.append(part)
full = "/".join(acc)
found = None
for node in cur:
if node.get("type") == "folder" and node.get("name") == part:
found = node
break
if not found:
new_f: dict[str, Any] = {"type": "folder", "name": part, "path": full, "children": []}
cur.append(new_f)
found = new_f
cur = found.setdefault("children", [])
return cur
def tree_add_folder(tree: list, parent_path: str, name: str) -> list:
t = copy.deepcopy(tree)
children = ensure_folder_chain(t, parent_path)
full = join_rel(parent_path, name)
if any(n.get("path") == full for n in children):
return t
children.append({"type": "folder", "name": name, "path": full, "children": []})
return t
def tree_add_file(tree: list, parent_path: str, filename: str) -> list:
t = copy.deepcopy(tree)
children = ensure_folder_chain(t, parent_path)
full = join_rel(parent_path, filename)
full = full.replace("\\", "/")
if any(n.get("path") == full for n in children):
return t
children.append({"type": "file", "name": filename, "path": full})
return t
def tree_remove_path(tree: list, target_path: str) -> list:
"""Remove a file, or a folder and everything under it."""
tp = _norm(target_path)
def rec(nodes: list) -> list:
out: list = []
for n in nodes:
p = _norm(n.get("path") or "")
if n.get("type") == "folder":
if p == tp or p.startswith(tp + "/"):
continue
out.append({**n, "children": rec(n.get("children") or [])})
else:
if p == tp or p.startswith(tp + "/"):
continue
out.append(n)
return out
return rec(copy.deepcopy(tree))
def tree_move_path(tree: list, from_path: str, to_folder: str, new_name: str | None = None) -> list:
"""
Move a file or folder subtree. to_folder is destination directory ("" = root).
new_name optional rename (basename of root of moved subtree).
"""
fp = _norm(from_path)
dest_parent = _norm(to_folder)
removed: dict | None = None
def extract(nodes: list) -> list:
nonlocal removed
out = []
for n in nodes:
p = _norm(n.get("path") or "")
if n.get("type") == "folder":
if p == fp:
removed = copy.deepcopy(n)
continue
out.append({**n, "children": extract(n.get("children") or [])})
else:
if p == fp:
removed = copy.deepcopy(n)
continue
out.append(n)
return out
t = extract(copy.deepcopy(tree))
if not removed:
return copy.deepcopy(tree)
old_root = _norm(removed["path"])
nm = new_name or removed["name"]
new_root = join_rel(dest_parent, nm)
def rebase(n: dict) -> dict:
n = copy.deepcopy(n)
p = _norm(n["path"])
if p == old_root:
n["path"] = new_root
elif p.startswith(old_root + "/"):
n["path"] = new_root + "/" + p[len(old_root) + 1 :]
if n.get("type") == "folder":
n["children"] = [rebase(c) for c in n.get("children") or []]
return n
rebased = rebase(removed)
rebased["name"] = nm
children = ensure_folder_chain(t, dest_parent)
children.append(rebased)
return t
def flatten_file_paths(tree: list) -> list[str]:
out: list[str] = []
def walk(nodes: list) -> None:
for n in nodes:
if n.get("type") == "folder":
walk(n.get("children") or [])
else:
p = (n.get("path") or "").replace("\\", "/")
if p:
out.append(p)
walk(tree)
return out
|