-
Notifications
You must be signed in to change notification settings - Fork 22
/
generate_dir_structure.py
99 lines (81 loc) · 2.76 KB
/
generate_dir_structure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
from pathlib import Path
class DisplayablePath(object):
display_filename_prefix_middle = "├──"
display_filename_prefix_last = "└──"
display_parent_prefix_middle = " "
display_parent_prefix_last = "│ "
def __init__(self, path, parent_path, is_last):
self.path = Path(str(path))
self.parent = parent_path
self.is_last = is_last
if self.parent:
self.depth = self.parent.depth + 1
else:
self.depth = 0
@classmethod
def make_tree(cls, root, parent=None, is_last=False, criteria=None):
root = Path(str(root))
criteria = criteria or cls._default_criteria
displayable_root = cls(root, parent, is_last)
yield displayable_root
children = sorted(
list(path for path in root.iterdir() if criteria(path)),
key=lambda s: str(s).lower(),
)
count = 1
for path in children:
is_last = count == len(children)
if path.is_dir():
yield from cls.make_tree(
path,
parent=displayable_root,
is_last=is_last,
criteria=criteria,
)
else:
yield cls(path, displayable_root, is_last)
count += 1
@classmethod
def _default_criteria(cls, path):
return True
@property
def displayname(self):
if self.path.is_dir():
return self.path.name + "/"
return self.path.name
def displayable(self):
if self.parent is None:
return self.displayname
_filename_prefix = (
self.display_filename_prefix_last
if self.is_last
else self.display_filename_prefix_middle
)
parts = ["{!s} {!s}".format(_filename_prefix, self.displayname)]
parent = self.parent
while parent and parent.parent is not None:
parts.append(
self.display_parent_prefix_middle
if parent.is_last
else self.display_parent_prefix_last
)
parent = parent.parent
return "".join(reversed(parts))
if __name__ == "__main__":
from argparse import ArgumentParser
parser = ArgumentParser("Utility for displaying directory structure")
parser.add_argument(
"--dir",
type=str,
required=True,
help="Name of the directory whose structure is to be generated",
)
args = parser.parse_args()
paths = DisplayablePath.make_tree(
Path(args.dir),
criteria=lambda path: True
if path.name not in (".git", "__pycache__", "__init__.py")
else False,
)
for path in paths:
print(path.displayable())