summaryrefslogtreecommitdiff
path: root/pycco/generate_index.py
blob: 7652466b0396d496123cad508cee573404612c3d (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
"""
This is the module responsible for automatically generating an HTML index of
all documentation files generated by Pycco.
"""
import re
from os import path

from pycco.compat import compat_items
from pycco_resources import pycco_template


__all__ = ('generate_index',)


def build_tree(file_paths, outdir):
    tree = {}
    for file_path in file_paths:
        entry = {
            'path': file_path,
            'relpath': path.relpath(file_path, outdir)
        }
        path_steps = entry['relpath'].split(path.sep)
        add_file(entry, path_steps, tree)

    return tree


def add_file(entry, path_steps, tree):
    """
    :param entry: A dictionary containing a path to a documentation file, and a
    relative path to the same file.
    :param path_steps: A list of steps in a file path to look within.
    """
    node, subpath = path_steps[0], path_steps[1:]
    if node not in tree:
        tree[node] = {}

    if subpath:
        add_file(entry, subpath, tree[node])

    else:
        tree[node]['entry'] = entry


def generate_tree_html(tree):
    """
    Given a tree representing HTML file paths, return an HTML table plotting
    those paths.
    """
    items = []
    for node, subtree in sorted(compat_items(tree)):
        if 'entry' in subtree:
            html = u'<li><a href="{}">{}</a></li>'.format(subtree['entry']['relpath'], node)
        else:
            html = u'<dl><dt>{}</dt><dd><ul>{}</ul></dd></dl>'.format(
                node, generate_tree_html(subtree)
            )

        items.append(html)

    return ''.join(items)


def generate_index(files, outdir):
    """
    Given a list of generated documentation files, generate HTML to display
    index of all files.
    """
    tree = build_tree(files, outdir)

    rendered = pycco_template({
        "title": 'Index',
        "stylesheet": 'pycco.css',
        "sections": {'docs_html': generate_tree_html(tree)},
        "source": '',
    })

    return re.sub(r"__DOUBLE_OPEN_STACHE__", "{{", rendered).encode("utf-8")