summaryrefslogtreecommitdiffstats
path: root/examples/recursive_dirtree_generator.py
blob: 986cd1ac0587b233d2858705ddeba55f6fe70b86 (plain)
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
#!/usr/bin/env python

"""
Example of treelib usage to generate recursive tree of directories.
It could be useful to implement Directory Tree data structure

2016 samuelsh
"""

import treelib
import random
import hashlib
from string import digits, letters
import sys


MAX_FILES_PER_DIR = 10


def range2(stop):
    if sys.version_info[0] < 3:
        return xrange(stop)  # noqa: F821
    else:
        return range(stop)


def get_random_string(length):
    return "".join(random.choice(digits + letters) for _ in range2(length))


def build_recursive_tree(tree, base, depth, width):
    """
    Args:
        tree: Tree
        base: Node
        depth: int
        width: int

    Returns:

    """
    if depth >= 0:
        depth -= 1
        for i in range2(width):
            directory = Directory()
            tree.create_node(
                "{0}".format(directory.name),
                "{0}".format(hashlib.md5(directory.name)),
                parent=base.identifier,
                data=directory,
            )  # node identifier is md5 hash of it's name
        dirs_nodes = tree.children(base.identifier)
        for dir in dirs_nodes:
            newbase = tree.get_node(dir.identifier)
            build_recursive_tree(tree, newbase, depth, width)
    else:
        return


class Directory(object):
    def __init__(self):
        self._name = get_random_string(64)
        self._files = [
            File() for _ in range2(MAX_FILES_PER_DIR)
        ]  # Each directory contains 1000 files

    @property
    def name(self):
        return self._name

    @property
    def files(self):
        return self._files


class File(object):
    def __init__(self):
        self._name = get_random_string(64)

    @property
    def name(self):
        return self._name


tree = treelib.Tree()
base = tree.create_node("Root", "root")
build_recursive_tree(tree, base, 2, 10)

tree.show()