treegenerator.treegenerator

  1from pathlib import Path
  2
  3from printbuddies import ProgBar, clear, print_in_place
  4
  5
  6class TreeGenerator:
  7    """Generates a nested dictionary of arbitrary depth
  8    representing the subdirectories of a given directory."""
  9
 10    def __init__(self, starting_directory: str | Path):
 11        self.starting_dir = Path(starting_directory)
 12        self.paths = [self.starting_dir]
 13        self._pipe = "|"
 14        self._tee = "|-"
 15        self._elbow = "|_"
 16        self.generate()
 17
 18    def generate(self):
 19        self.paths.extend(self._crawl(self.starting_dir))
 20        clear()
 21        self._drop_parents()
 22        self._generate_tree()
 23        self._generate_tree_string()
 24
 25    def _drop_parents(self):
 26        self.paths = [
 27            Path(str(path)[str(path).find(self.starting_dir.stem) :])
 28            for path in self.paths
 29        ]
 30
 31    def __str__(self):
 32        return f"{self.tree_string}"
 33
 34    def _crawl(self, start_dir: Path) -> list[Path]:
 35        """Generate recursive list of paths by crawling
 36        down every branch from the starting_dir."""
 37        paths = []
 38        print_in_place(f"Crawling {start_dir}...")
 39        for item in start_dir.iterdir():
 40            if item.is_file():
 41                paths.append(item)
 42            elif item.is_dir():
 43                paths.extend(self._crawl(item))
 44                print_in_place(f"Crawling {start_dir}...")
 45        return paths
 46
 47    def _generate_tree(self):
 48        """Generate nested dictionary of subdirectories."""
 49        self.tree = {}
 50        prog_bar = ProgBar(len(self.paths))
 51        prog_bar.display()
 52        for path in sorted(self.paths):
 53            if path.parts[0] not in self.tree:
 54                self.tree[path.parts[0]] = {}
 55            current_layer = self.tree[path.parts[0]]
 56            branches = path.parts[1:]
 57            for branch in branches:
 58                if branch not in current_layer:
 59                    current_layer[branch] = {}
 60                current_layer = current_layer[branch]
 61            prog_bar.display()
 62
 63    def _format_branch_name(self, branch_name: str, index: int) -> str:
 64        if index == 0:
 65            return f"{branch_name}\n"
 66        elif index == 1:
 67            return f'{self._pipe}{"  "*index}{self._tee}{branch_name}\n'
 68        else:
 69            return (
 70                f'{self._pipe}{("  "+self._pipe)*(index-1)}  {self._tee}{branch_name}\n'
 71            )
 72
 73    def _convert_branch_to_string(
 74        self, branch: dict, branch_name: str, index: int
 75    ) -> str:
 76        """Iterates through a nested dictionary and returns a string representation."""
 77        output = self._format_branch_name(branch_name, index)
 78        for i, leaf in enumerate(branch.keys()):
 79            if branch[leaf] == {}:
 80                output += f'{self._pipe}{("  "+self._pipe)*index}  '
 81                if i == len(branch.keys()) - 1:
 82                    output += f"{self._elbow}{leaf}\n"
 83                    output += f'{self._pipe}{("  "+self._pipe)*index}\n'
 84                else:
 85                    output += f"{self._tee}{leaf}\n"
 86            else:
 87                output += self._convert_branch_to_string(branch[leaf], leaf, index + 1)
 88        return output
 89
 90    def _trim_tree(self):
 91        tree = self.tree_string.splitlines()
 92        self.tree_string = ""
 93        for i, line in enumerate(tree[:-1]):
 94            if (
 95                all(ch in f"{self._pipe} " for ch in line)
 96                and i < len(tree) - 2
 97                and self._tee in tree[i + 1]
 98            ):
 99                self.tree_string += f"{line[:tree[i+1].find(self._tee)+1]}\n"
100            else:
101                self.tree_string += f"{line}\n"
102
103    def _generate_tree_string(self):
104        """Generates formatted string representation of
105        the directory tree."""
106        self.tree_string = ""
107        for root in self.tree.keys():
108            self.tree_string += self._convert_branch_to_string(self.tree[root], root, 0)
109        self._trim_tree()
110
111
112class UrlTreeGenerator(TreeGenerator):
113    """Generates a tree representation of a given list of urls."""
114
115    def __init__(self, urls: list[str]):
116        self.paths = [Path(url) for url in urls]
117        self._pipe = "|"
118        self._tee = "|-"
119        self._elbow = "|_"
120
121    def generate(self):
122        self._generate_tree()
123        self._generate_tree_string()
class TreeGenerator:
  7class TreeGenerator:
  8    """Generates a nested dictionary of arbitrary depth
  9    representing the subdirectories of a given directory."""
 10
 11    def __init__(self, starting_directory: str | Path):
 12        self.starting_dir = Path(starting_directory)
 13        self.paths = [self.starting_dir]
 14        self._pipe = "|"
 15        self._tee = "|-"
 16        self._elbow = "|_"
 17        self.generate()
 18
 19    def generate(self):
 20        self.paths.extend(self._crawl(self.starting_dir))
 21        clear()
 22        self._drop_parents()
 23        self._generate_tree()
 24        self._generate_tree_string()
 25
 26    def _drop_parents(self):
 27        self.paths = [
 28            Path(str(path)[str(path).find(self.starting_dir.stem) :])
 29            for path in self.paths
 30        ]
 31
 32    def __str__(self):
 33        return f"{self.tree_string}"
 34
 35    def _crawl(self, start_dir: Path) -> list[Path]:
 36        """Generate recursive list of paths by crawling
 37        down every branch from the starting_dir."""
 38        paths = []
 39        print_in_place(f"Crawling {start_dir}...")
 40        for item in start_dir.iterdir():
 41            if item.is_file():
 42                paths.append(item)
 43            elif item.is_dir():
 44                paths.extend(self._crawl(item))
 45                print_in_place(f"Crawling {start_dir}...")
 46        return paths
 47
 48    def _generate_tree(self):
 49        """Generate nested dictionary of subdirectories."""
 50        self.tree = {}
 51        prog_bar = ProgBar(len(self.paths))
 52        prog_bar.display()
 53        for path in sorted(self.paths):
 54            if path.parts[0] not in self.tree:
 55                self.tree[path.parts[0]] = {}
 56            current_layer = self.tree[path.parts[0]]
 57            branches = path.parts[1:]
 58            for branch in branches:
 59                if branch not in current_layer:
 60                    current_layer[branch] = {}
 61                current_layer = current_layer[branch]
 62            prog_bar.display()
 63
 64    def _format_branch_name(self, branch_name: str, index: int) -> str:
 65        if index == 0:
 66            return f"{branch_name}\n"
 67        elif index == 1:
 68            return f'{self._pipe}{"  "*index}{self._tee}{branch_name}\n'
 69        else:
 70            return (
 71                f'{self._pipe}{("  "+self._pipe)*(index-1)}  {self._tee}{branch_name}\n'
 72            )
 73
 74    def _convert_branch_to_string(
 75        self, branch: dict, branch_name: str, index: int
 76    ) -> str:
 77        """Iterates through a nested dictionary and returns a string representation."""
 78        output = self._format_branch_name(branch_name, index)
 79        for i, leaf in enumerate(branch.keys()):
 80            if branch[leaf] == {}:
 81                output += f'{self._pipe}{("  "+self._pipe)*index}  '
 82                if i == len(branch.keys()) - 1:
 83                    output += f"{self._elbow}{leaf}\n"
 84                    output += f'{self._pipe}{("  "+self._pipe)*index}\n'
 85                else:
 86                    output += f"{self._tee}{leaf}\n"
 87            else:
 88                output += self._convert_branch_to_string(branch[leaf], leaf, index + 1)
 89        return output
 90
 91    def _trim_tree(self):
 92        tree = self.tree_string.splitlines()
 93        self.tree_string = ""
 94        for i, line in enumerate(tree[:-1]):
 95            if (
 96                all(ch in f"{self._pipe} " for ch in line)
 97                and i < len(tree) - 2
 98                and self._tee in tree[i + 1]
 99            ):
100                self.tree_string += f"{line[:tree[i+1].find(self._tee)+1]}\n"
101            else:
102                self.tree_string += f"{line}\n"
103
104    def _generate_tree_string(self):
105        """Generates formatted string representation of
106        the directory tree."""
107        self.tree_string = ""
108        for root in self.tree.keys():
109            self.tree_string += self._convert_branch_to_string(self.tree[root], root, 0)
110        self._trim_tree()

Generates a nested dictionary of arbitrary depth representing the subdirectories of a given directory.

TreeGenerator(starting_directory: str | pathlib.Path)
11    def __init__(self, starting_directory: str | Path):
12        self.starting_dir = Path(starting_directory)
13        self.paths = [self.starting_dir]
14        self._pipe = "|"
15        self._tee = "|-"
16        self._elbow = "|_"
17        self.generate()
def generate(self):
19    def generate(self):
20        self.paths.extend(self._crawl(self.starting_dir))
21        clear()
22        self._drop_parents()
23        self._generate_tree()
24        self._generate_tree_string()
class UrlTreeGenerator(TreeGenerator):
113class UrlTreeGenerator(TreeGenerator):
114    """Generates a tree representation of a given list of urls."""
115
116    def __init__(self, urls: list[str]):
117        self.paths = [Path(url) for url in urls]
118        self._pipe = "|"
119        self._tee = "|-"
120        self._elbow = "|_"
121
122    def generate(self):
123        self._generate_tree()
124        self._generate_tree_string()

Generates a tree representation of a given list of urls.

UrlTreeGenerator(urls: list[str])
116    def __init__(self, urls: list[str]):
117        self.paths = [Path(url) for url in urls]
118        self._pipe = "|"
119        self._tee = "|-"
120        self._elbow = "|_"
def generate(self):
122    def generate(self):
123        self._generate_tree()
124        self._generate_tree_string()