summaryrefslogtreecommitdiff
path: root/repo/www/generate-index.py
blob: 3bce69d5145254b4e72a8f88b34f203ba350fef3 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/env python3

from argparse import ArgumentParser
from itertools import chain
import json
from os import path
from pathlib import Path
from subprocess import run
from tempfile import NamedTemporaryFile

from git import Repo

from helpers import deserialize_directories, generate_crumbs, pandoc


def parse_arguments():
    parser = ArgumentParser()
    parser.add_argument(
        '--template', help='Pandoc template for HTML output.'
    )
    parser.add_argument(
        '--site-title', help='Prefix to add to <title>.'
    )
    parser.add_argument(
        '--lua-filter', dest='filters', action='append',
        help='Lua filter to run the page through.'
    )
    parser.add_argument(
        '--stylesheet', dest='css', action='append',
        help='CSS stylesheet to link to.'
    )
    parser.add_argument(
        'site_tree', help='JSON file describing the page tree.'
    )
    parser.add_argument(
        'target', help='Subfolder to generate an index for.'
    )
    parser.add_argument(
        'output', help='Path to the output file.'
    )
    return parser.parse_args()


def list_files(tree_file, folder):
    with open(tree_file) as tree:
        directories = deserialize_directories(json.load(tree))
    return directories[folder].subfolders, directories[folder].files


def has_title(document_path):
    pandoc = run(
        ('pandoc', '-t', 'json', document_path),
        check=True, text=True, capture_output=True
    )
    ast = json.loads(pandoc.stdout)
    return 'title' in ast['meta']


def list_pages(files):
    readme = None
    pages = []

    for f in files:
        page = Path(f).stem

        if page == 'README':
            readme = f
        else:
            pages.append(page)

    return pages, readme


def format_toc(directories, pages):
    dir_template = '<li><a href="{d}/index.html">{d}/</a></li>'
    page_template = '<li><a href="{p}.html">{p}</a></li>'

    dir_list = (
        dir_template.format(d=d) for d in directories
    )
    page_list = (
        page_template.format(p=p) for p in pages
    )

    return '\n'.join((
        '<ul>', *chain(dir_list, page_list), '</ul>'
    ))


def main(arguments):
    target = arguments.target
    folders, files = list_files(arguments.site_tree, target)
    pages, readme = list_pages(files)

    toc_title = f'Index for {target}' if target else 'Index'
    html_toc = format_toc(folders, pages)

    path_to_top = path.relpath('.', start=target)
    stylesheets = (path.join(path_to_top, s) for s in arguments.css)

    variables = {'crumbs': generate_crumbs(Path(target)/'index')}
    metadata = {}

    if readme is not None:
        repo_top = Repo(search_parent_directories=True).working_dir
        readme_path = Path(repo_top, target, readme)

        # If the README doesn't have a title, give a default to pandoc
        # out-of-band.
        if not has_title(readme_path):
            metadata['pagetitle'] = target or 'README'

        with NamedTemporaryFile(mode='w+') as toc:
            toc.write(f'<h1>{toc_title}</h1>\n')
            toc.write(html_toc)
            toc.flush()

            pandoc(
                readme_path, arguments.output,
                arguments.template, arguments.filters, stylesheets,
                site_title=arguments.site_title, include_after=(toc.name,),
                variables=variables, metadata=metadata
            )
        return

    with NamedTemporaryFile(suffix='.md') as dummy_readme, \
         NamedTemporaryFile(mode='w+') as toc:
        toc.write(html_toc)
        toc.flush()

        metadata['pagetitle'] = toc_title
        metadata['title'] = 'Index'

        pandoc(
            dummy_readme.name, arguments.output,
            arguments.template, arguments.filters, stylesheets,
            site_title=arguments.site_title, include_after=(toc.name,),
            variables=variables, metadata=metadata
        )


if __name__ == '__main__':
    main(parse_arguments())