From c620c1b19bf6907888923612507876e19f35dca2 Mon Sep 17 00:00:00 2001 From: EKNr1 Date: Fri, 10 Jan 2025 18:03:22 +0100 Subject: [PATCH] Added a module that generates file tree views. --- wobbl_tools/text/tree_view.py | 70 +++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 wobbl_tools/text/tree_view.py diff --git a/wobbl_tools/text/tree_view.py b/wobbl_tools/text/tree_view.py new file mode 100644 index 0000000..a9d4811 --- /dev/null +++ b/wobbl_tools/text/tree_view.py @@ -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__"]))