From f9f02201cb25283039626b20a0a917f3c62f19f6 Mon Sep 17 00:00:00 2001 From: Zvonimir Sabljic Date: Thu, 27 Jul 2023 15:30:32 +0200 Subject: [PATCH] Added a function that returns a directory tree --- euclid/helpers/cli.py | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/euclid/helpers/cli.py b/euclid/helpers/cli.py index cab72cc3..5ae0e5af 100644 --- a/euclid/helpers/cli.py +++ b/euclid/helpers/cli.py @@ -38,4 +38,41 @@ def execute_command(command, timeout=5): if line: output += line - return output[-2000:] \ No newline at end of file + return output[-2000:] + +def build_directory_tree(path, prefix="", ignore=None, is_last=False): + """Build the directory tree structure in tree-like format. + + Args: + - path: The starting directory path. + - prefix: Prefix for the current item, used for recursion. + - ignore: List of directory names to ignore. + - is_last: Flag to indicate if the current item is the last in its parent directory. + + Returns: + - A string representation of the directory tree. + """ + if ignore is None: + ignore = [] + + if os.path.basename(path) in ignore: + return "" + + output = "" + indent = '| ' if not is_last else ' ' + + if os.path.isdir(path): + # It's a directory, add its name to the output and then recurse into it + output += prefix + "|-- " + os.path.basename(path) + "/\n" + + # List items in the directory + items = os.listdir(path) + for index, item in enumerate(items): + item_path = os.path.join(path, item) + output += build_directory_tree(item_path, prefix + indent, ignore, index == len(items) - 1) + + else: + # It's a file, add its name to the output + output += prefix + "|-- " + os.path.basename(path) + "\n" + + return output