Added a module that generates file tree views.

This commit is contained in:
The Wobbler 2025-01-10 18:03:22 +01:00
parent eaa9b87990
commit c620c1b19b

View file

@ -0,0 +1,70 @@
#!/usr/bin/python3
import os
from wobbl_tools.text.format import format_string
def tree_view(
path: str | os.PathLike,
exclude_paths: list[str | os.PathLike] = [],
exclude_names: list[str | os.PathLike] = [],
auto_exclude: bool = True
):
"""
Returns a tree view of the given path.
:param path: The path of the directory.
:param exclude_paths: A list of paths to exclude from the tree view.
:param exclude_names: A list of file names to exclude from the tree view.
:param auto_exclude: If True, every file whose name starts with a dot will be ignored.
:return: A string representing the tree view of the given path.
"""
tree = ""
if not path[-1] == "/":
path += "/"
root_folder_name = path.split("/")[-2]
for subdir, dirs, files in os.walk(path):
relative_path = subdir.replace(path, "")
folder_name = subdir.split("/")[-1]
files.sort()
if (
subdir in exclude_paths or
folder_name in exclude_names or
(auto_exclude and folder_name.startswith("."))
):
continue
indentation_level = relative_path.count("/")
folder_indentation = "" * indentation_level
file_indentation = "" * (indentation_level + 1)
if relative_path == "":
tree += format_string(f"§bold§dark_blue{root_folder_name}§rs/\n")
file_indentation = ""
else:
tree += format_string(f"{folder_indentation}├─ §bold§blue{folder_name}§rs/\n")
for file in files:
if (
f"{subdir}/{file}" in exclude_paths or
file in exclude_names or
(auto_exclude and folder_name.startswith("."))
):
continue
tree += f"{file_indentation}├─ {file}\n"
#print(folder_name + relative_path, dirs, files)
return tree
if __name__ == "__main__":
print(tree_view("/home/emil/Dokumente/python/wobbl_tools/wobbl_tools/", exclude_names=["__pycache__"]))