84 lines
2.8 KiB
Python
84 lines
2.8 KiB
Python
# core/commands/ls.py
|
|
from core.connection import BuzzerError
|
|
|
|
def get_file_tree(conn, target_path="/", recursive=False) -> list:
|
|
"""
|
|
Liest das Dateisystem aus und gibt eine hierarchische Baumstruktur zurück.
|
|
"""
|
|
if not target_path.endswith('/'):
|
|
target_path += '/'
|
|
|
|
cmd_path = target_path.rstrip('/') if target_path != '/' else '/'
|
|
|
|
try:
|
|
lines = conn.send_command(f"ls {cmd_path}")
|
|
except BuzzerError as e:
|
|
return [{"type": "E", "name": f"Fehler beim Lesen: {e}", "path": target_path}]
|
|
|
|
nodes = []
|
|
if not lines:
|
|
return nodes
|
|
|
|
for line in lines:
|
|
parts = line.split(',', 2)
|
|
if len(parts) != 3:
|
|
continue
|
|
|
|
entry_type, entry_size, entry_name = parts
|
|
node = {
|
|
"type": entry_type,
|
|
"name": entry_name,
|
|
"path": f"{target_path}{entry_name}"
|
|
}
|
|
|
|
if entry_type == 'D':
|
|
if recursive:
|
|
# Rekursiver Aufruf auf dem Host für Unterverzeichnisse
|
|
node["children"] = get_file_tree(conn, f"{target_path}{entry_name}/", recursive=True)
|
|
else:
|
|
node["children"] = []
|
|
elif entry_type == 'F':
|
|
node["size"] = int(entry_size)
|
|
|
|
nodes.append(node)
|
|
|
|
return nodes
|
|
|
|
def print_tree(nodes, prefix="", path=""):
|
|
"""
|
|
Gibt die Baumstruktur optisch formatiert auf der Konsole aus.
|
|
"""
|
|
if path:
|
|
if path == "/":
|
|
display_path = "💾 "+"/ (Root)"
|
|
else:
|
|
display_path = "📁 " + path
|
|
print(f"{prefix}{display_path}")
|
|
for i, node in enumerate(nodes):
|
|
is_last = (i == len(nodes) - 1)
|
|
connector = " └─" if is_last else " ├─"
|
|
|
|
if node["type"] == 'D':
|
|
print(f"{prefix}{connector}📁 {node['name']}")
|
|
extension = " " if is_last else " │ "
|
|
if "children" in node and node["children"]:
|
|
print_tree(node["children"], prefix + extension)
|
|
elif node["type"] == 'F':
|
|
size_kb = node["size"] / 1024
|
|
# \033[90m macht den Text dunkelgrau, \033[0m setzt die Farbe zurück
|
|
print(f"{prefix}{connector}📄 {node['name']} \033[90m({size_kb:.1f} KB)\033[0m")
|
|
elif node["type"] == 'E':
|
|
print(f"{prefix}{connector}❌ \033[31m{node['name']}\033[0m")
|
|
|
|
def get_flat_file_list(nodes) -> list:
|
|
"""
|
|
Wandelt die Baumstruktur in eine flache Liste von Dateipfaden um.
|
|
Wird von 'rm -r' benötigt, um nacheinander alle Dateien zu löschen.
|
|
"""
|
|
flat_list = []
|
|
for node in nodes:
|
|
if node["type"] == 'F':
|
|
flat_list.append(node)
|
|
elif node["type"] == 'D' and "children" in node:
|
|
flat_list.extend(get_flat_file_list(node["children"]))
|
|
return flat_list |