summaryrefslogtreecommitdiff
path: root/contrib/gendocs.py
blob: 4d607d9971a3c1fc02c253d0b35c8ba1f7a56f67 (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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/env python3

# This script generates a static documentation web site
# by parsing the `**/*.asiidoc` files from the repository.
#
# Dependencies:
# * Python 3
# * `xdg-open` for opening the final result in a web browser.
# * `antora` - a static documentation web site generator,
#     https://docs.antora.org/antora/latest
#
# Usage:
# ```console
# $ ./contrib/gendocs.py
# ```
#
# After running it should open the generated web site in a browser.
#


from dataclasses import dataclass
from typing import Optional
import glob
import itertools
import os
import pathlib
import re
import shutil
import subprocess

# Get the script directory.
script_dir = os.path.dirname(os.path.realpath(__file__))

# Switch to the projects root dir.
os.chdir(os.path.join(script_dir, ".."))

# Recreating the final output dir to start from scratch.
shutil.rmtree("doc_gen", ignore_errors=True)
os.makedirs("doc_gen", exist_ok=True)

# Antora fails if the repo contains broken symbolic links.
# shutil.rmtree("libexec", ignore_errors=True)

# Canonical Antora paths.
# See: https://docs.antora.org/antora/latest/standard-directories.
#      https://docs.antora.org/antora/latest/root-module-directory.
os.makedirs("doc_gen/modules/ROOT/images", exist_ok=True)
os.makedirs("doc_gen/modules/ROOT/pages", exist_ok=True)


# Put necessary images to the Antora canonical directory.
# See: https://docs.antora.org/antora/latest/images-directory.
for gif_file in glob.glob("doc/*.gif"):
    shutil.copy(gif_file, "doc_gen/modules/ROOT/images/")


# Fix links according to the Antora specification.
# See: https://docs.antora.org/antora/latest/page/xref.
def fix_links(path):
    @dataclass
    class Link:
        path: Optional[str]
        file: Optional[str]
        fragment: Optional[str]
        title: str

        def __init__(self, path, file, fragment, title):
            self.path = path
            self.file = file
            self.fragment = fragment
            self.title = title

    def dropwhile(predicate, string):
        return "".join(
            itertools.dropwhile(
                predicate,
                string,
            )
        )

    def dropwhileright(predicate, string):
        return "".join(
            reversed(
                list(
                    itertools.dropwhile(
                        predicate,
                        reversed(string),
                    )
                )
            )
        )

    def takewhile(predicate, string):
        return "".join(
            itertools.takewhile(
                predicate,
                string,
            )
        )

    def untag(string):
        no_opening = dropwhile(lambda c: c == "<", string)
        no_closing = dropwhileright(lambda c: c == ">", no_opening)
        return no_closing

    def parse(string):
        untagged = untag(string)
        prefix, title = untagged.split(",", 1)
        title = title.strip()
        fragment = dropwhile(lambda c: c != "#", prefix)
        fragment = fragment if fragment else None
        fragmentless = takewhile(lambda c: c != "#", prefix)
        segments = fragmentless.split("/")
        path, file = (
            ("/".join(segments[:-1]), segments[-1])
            if "/" in fragmentless
            else (None, fragmentless)
        )
        return Link(path, file, fragment, title)

    def render(link):
        if link.path and link.file and link.fragment == "#":
            return f"xref:{link.path}/{link.file}.adoc[{link.title}]"
        elif link.path and link.file and link.fragment:
            return f"xref:{link.path}/{link.file}.adoc{link.fragment}[{link.title}]"
        elif not link.path and link.file and link.fragment == "#":
            return f"xref:./{link.file}.adoc[{link.title}]"
        elif not link.path and link.file and link.fragment:
            return f"xref:./{link.file}.adoc{link.fragment}[{link.title}]"
        elif not link.path and link.file and not link.fragment:
            return f"<<{link.file},{link.title}>>"
        else:
            raise RuntimeError(f"Failed to render link: {link}")

    def process(m):
        string = m.group(0)
        return render(parse(string)) if "," in string else string

    content = None

    with open(path, "r") as file:
        content = file.read()

    # Fix image links according the Antora specification.
    # See: https://docs.antora.org/antora/latest/page/image-resource-id-examples.
    content = content.replace("image::doc/", "image::")

    with open(path, "w") as file:
        file.write(re.sub(r"<<[^>]+>>", process, content))


# A useful documentation page.
# Add the `.adoc` extension to include it into the result.
shutil.copy(
    "VIMTOKAK",
    "doc_gen/modules/ROOT/pages/VIMTOKAK.adoc",
)
fix_links("doc_gen/modules/ROOT/pages/VIMTOKAK.adoc")

for source in glob.glob("**/*.asciidoc", recursive=True):
    # Create directories structure matching the project's original structure.
    # See: https://docs.antora.org/antora/latest/pages-directory.
    page_dir = os.path.join(
        "doc_gen/modules/ROOT/pages",
        os.path.dirname(source),
    )
    os.makedirs(page_dir, exist_ok=True)

    # Copy the `asciidoc` file into the Antora `pages` directory
    # with the mandatory `.adoc` filename extension.
    adoc = os.path.join(page_dir, pathlib.Path(source).stem + ".adoc")
    shutil.copy(source, adoc)

    if source == "README.asciidoc":
        # Update the filename so it reflects the content.
        # The filename is used for navigation links.
        shutil.move(
            "doc_gen/modules/ROOT/pages/README.adoc",
            "doc_gen/modules/ROOT/pages/index.adoc",
        )
        adoc = "doc_gen/modules/ROOT/pages/index.adoc"
    elif source == "test/README.asciidoc":
        # The file name is used for navigation links.
        # Update so it reflects the content.
        shutil.move(
            "doc_gen/modules/ROOT/pages/test/README.adoc",
            "doc_gen/modules/ROOT/pages/test/tests.adoc",
        )
        adoc = "doc_gen/modules/ROOT/pages/test/tests.adoc"
    fix_links(adoc)


# A navigation file for the sidebar.
# See: https://docs.antora.org/antora/latest/navigation/single-list.
#
# TODO: Generate automatically.
nav_content = """
* xref:index.adoc[Getting Started]
* xref:doc/pages/commands.adoc[Commands]
* xref:doc/pages/expansions.adoc[Expansions]
* xref:doc/pages/execeval.adoc[Exec Eval]
* xref:doc/pages/scopes.adoc[Scopes]
* xref:doc/pages/faces.adoc[Faces]
* xref:doc/pages/buffers.adoc[Buffers]
* xref:doc/pages/registers.adoc[Registers]
* xref:doc/pages/mapping.adoc[Mapping]
* xref:doc/pages/hooks.adoc[Hooks]
* xref:doc/pages/command-parsing.adoc[Command Parsing]
* xref:doc/pages/keys.adoc[Keys]
* xref:doc/pages/regex.adoc[Regex]
* xref:doc/pages/options.adoc[Options]
* xref:doc/pages/highlighters.adoc[Highlighters]
* xref:doc/pages/modes.adoc[Modes]
* xref:doc/pages/keymap.adoc[KEYMAP]
* xref:doc/pages/faq.adoc[FAQ]
* xref:doc/pages/changelog.adoc[Changelog]
* xref:doc/design.adoc[Design]
* xref:doc/coding-style.adoc[Coding Style]
* xref:doc/writing_scripts.adoc[Writing Scripts]
* xref:doc/json_ui.adoc[JSON UI]
* xref:doc/autoedit.adoc[Autoedit]
* xref:doc/interfacing.adoc[Interfacing]
* xref:rc/tools/lint.adoc[Linting]
* xref:rc/tools/autorestore.adoc[Autorestore]
* xref:rc/tools/doc.adoc[Doc]
* xref:test/tests.adoc[Tests]
* xref:VIMTOKAK.adoc[Vi(m) to Kakoune]
"""

with open("doc_gen/modules/ROOT/nav.adoc", "w") as f:
    f.write(nav_content)

# Antora component description file.
# See: https://docs.antora.org/antora/latest/component-version-descriptor.
antora_yml_content = """
name: Kakoune
nav:
  - modules/ROOT/nav.adoc
title: Kakoune
version: latest
"""

with open("doc_gen/antora.yml", "w") as f:
    f.write(antora_yml_content)

# Antora playbook file.
# See: https://docs.antora.org/antora/latest/playbook.
antora_playbook_content = """
asciidoc:
  attributes:

    # Do not complain on missing attributes,
    # TODO: fix and turn to a fatal warning
    attribute-missing: skip

    # To fix links
    idprefix: ""

    # To fix links
    idseparator: "-"

    # Better to be reproducible, in general
    reproducible: true

    # More convenient to turn sections to IDs
    sectids: true

    # More convenient to have sections as links
    sectlinks: true

    # Do not want to miss something
    sectnumlevels: 5

    # More convenient to number the sections
    sectnums: true

    # Do not want to miss something
    toclevels: 5

  sourcemap: true

content:
  sources:
  - url: ./..
    start_path: doc_gen
    branches: ["HEAD"]

runtime:
  cache_dir: ./doc_gen/cache # More convenient for the development
  fetch: true # More convenient for the development

  log:
    failure_level: fatal
    level: warn

output:
  clean: true # More convenient for the development
  dir: ./build # Simpler to have it explicit in code

site:
  title: Kakoune Docs

ui:
  bundle:
    url: https://gitlab.com/antora/antora-ui-default/-/jobs/artifacts/HEAD/raw/build/ui-bundle.zip?job=bundle-stable
"""

with open("doc_gen/antora-playbook.yml", "w") as f:
    f.write(antora_playbook_content)

# Finally, generate the documentation,
# results will be saved to the output directory
# as specified in the `antora-playbook.yml`.
use_npx = shutil.which("antora") is None and shutil.which("npx") is not None
subprocess.run((["npx"] if use_npx else []) + ["antora", "generate", "doc_gen/antora-playbook.yml"])
subprocess.run(["xdg-open", "./doc_gen/build/Kakoune/latest/index.html"])