summaryrefslogtreecommitdiffstats
path: root/scripts/generate.py
blob: b4da7b4c6a9f030d1cf0e2e3e36c605936b608df (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
import os
import os.path
import re
from dataclasses import dataclass
from functools import lru_cache
from typing import List

from nvim_doc_tools import (
    Vimdoc,
    VimdocSection,
    generate_md_toc,
    indent,
    parse_functions,
    read_nvim_json,
    render_md_api,
    render_vimdoc_api,
    replace_section,
    wrap,
)

HERE = os.path.dirname(__file__)
ROOT = os.path.abspath(os.path.join(HERE, os.path.pardir))
README = os.path.join(ROOT, "README.md")
DOC = os.path.join(ROOT, "doc")
RECIPES = os.path.join(DOC, "recipes.md")
ADVANCED = os.path.join(DOC, "advanced_topics.md")
VIMDOC = os.path.join(DOC, "conform.txt")
OPTIONS = os.path.join(ROOT, "scripts", "options_doc.lua")
AUTOFORMAT = os.path.join(ROOT, "scripts", "autoformat_doc.lua")


@dataclass
class Formatter:
    name: str
    description: str
    url: str
    deprecated: bool = False


@lru_cache
def get_all_formatters() -> List[Formatter]:
    formatters = []
    formatter_map = read_nvim_json(
        'require("conform.formatters").list_all_formatters()'
    )
    for name, meta in formatter_map.items():
        formatter = Formatter(name, **meta)
        if not formatter.deprecated:
            formatters.append(formatter)
    formatters.sort(key=lambda f: f.name)
    return formatters


def update_formatter_list():
    formatter_lines = ["\n"]
    for formatter in get_all_formatters():
        formatter_lines.append(
            f"- [{formatter.name}]({formatter.url}) - {formatter.description}\n"
        )
    replace_section(
        README,
        r"^<!-- FORMATTERS -->$",
        r"^<!-- /FORMATTERS -->$",
        formatter_lines,
    )


def update_options():
    option_lines = ["\n", "```lua\n"]
    with open(OPTIONS, "r", encoding="utf-8") as f:
        option_lines.extend(f.readlines())
    option_lines.extend(["```\n", "\n"])
    replace_section(
        README,
        r"^<!-- OPTIONS -->$",
        r"^<!-- /OPTIONS -->$",
        option_lines,
    )


def update_autocmd_md():
    example_lines = ["\n", "```lua\n"]
    with open(AUTOFORMAT, "r", encoding="utf-8") as f:
        example_lines.extend(f.readlines())
    example_lines.extend(["```\n", "\n"])
    replace_section(
        RECIPES,
        r"^<!-- AUTOFORMAT -->$",
        r"^<!-- /AUTOFORMAT -->$",
        example_lines,
    )


def add_md_link_path(path: str, lines: List[str]) -> List[str]:
    ret = []
    for line in lines:
        ret.append(re.sub(r"(\(#)", "(" + path + "#", line))
    return ret


def update_md_api():
    funcs = parse_functions(os.path.join(ROOT, "lua", "conform", "init.lua"))
    lines = ["\n"] + render_md_api(funcs, 3)[:-1]  # trim last newline
    replace_section(
        README,
        r"^<!-- API -->$",
        r"^<!-- /API -->$",
        lines,
    )


def update_readme_toc():
    toc = ["\n"] + generate_md_toc(README) + ["\n"]
    replace_section(
        README,
        r"^<!-- TOC -->$",
        r"^<!-- /TOC -->$",
        toc,
    )


def update_recipes_toc():
    toc = ["\n"] + generate_md_toc(RECIPES) + ["\n"]
    replace_section(RECIPES, r"^<!-- TOC -->$", r"^<!-- /TOC -->$", toc)
    subtoc = add_md_link_path("doc/recipes.md", toc)
    replace_section(README, r"^<!-- RECIPES -->$", r"^<!-- /RECIPES -->$", subtoc)


def update_advanced_toc():
    toc = ["\n"] + generate_md_toc(ADVANCED) + ["\n"]
    replace_section(ADVANCED, r"^<!-- TOC -->$", r"^<!-- /TOC -->$", toc)
    subtoc = add_md_link_path("doc/advanced_topics.md", toc)
    replace_section(README, r"^<!-- ADVANCED -->$", r"^<!-- /ADVANCED -->$", subtoc)


def gen_options_vimdoc() -> VimdocSection:
    section = VimdocSection("Options", "conform-options", ["\n", ">lua\n"])
    with open(OPTIONS, "r", encoding="utf-8") as f:
        section.body.extend(indent(f.readlines(), 4))
    section.body.append("<\n")
    return section


def gen_self_compat_vimdoc() -> VimdocSection:
    section = VimdocSection("self argument migration", "conform-self-args", ["\n"])
    section.body.extend(
        wrap(
            "The function arguments for formatter config functions have changed. Previously, they took a single `ctx` argument."
        )
    )
    section.body.append(
        """>lua
    {
        command = "phpcbf",
        args = function(ctx)
            return { "-q", "--stdin-path=" .. ctx.filename, "-" }
        end
    }
<"""
    )
    section.body.extend(
        wrap("Now, they take `self` as the first argument, and `ctx` as the second.")
    )
    section.body.append(
        """>lua
    {
        command = "phpcbf",
        args = function(self, ctx)
            return { "-q", "--stdin-path=" .. ctx.filename, "-" }
        end
    }
<"""
    )
    section.body.extend(
        wrap(
            "The config values that can be defined as functions are: `command`, `args`, `range_args`, `cwd`, `env`, and `condition`."
        )
    )
    return section


def gen_formatter_vimdoc() -> VimdocSection:
    section = VimdocSection("Formatters", "conform-formatters", ["\n"])
    for formatter in get_all_formatters():
        line = f"`{formatter.name}` - {formatter.description}\n"
        section.body.extend(wrap(line, sub_indent=len(formatter.name) + 3))
    return section


def generate_vimdoc():
    doc = Vimdoc("conform.txt", "conform")
    funcs = parse_functions(os.path.join(ROOT, "lua", "conform", "init.lua"))
    doc.sections.extend(
        [
            gen_options_vimdoc(),
            VimdocSection("API", "conform-api", render_vimdoc_api("conform", funcs)),
            gen_formatter_vimdoc(),
            gen_self_compat_vimdoc(),
        ]
    )

    with open(VIMDOC, "w", encoding="utf-8") as ofile:
        ofile.writelines(doc.render())


def main() -> None:
    """Update the README"""
    update_formatter_list()
    update_options()
    update_autocmd_md()
    update_md_api()
    update_recipes_toc()
    update_advanced_toc()
    update_readme_toc()
    generate_vimdoc()