diff --git a/scripts/generate-options.py b/scripts/generate-options.py index 3cfc0b0..e78e262 100644 --- a/scripts/generate-options.py +++ b/scripts/generate-options.py @@ -1,5 +1,7 @@ import json import sys +from textwrap import indent +from typing import Any, Mapping header = """ # Mailserver options @@ -35,45 +37,61 @@ groups = [ ] -def render_option_value(opt, attr): - if attr not in opt: +def md_literal(value: str) -> str: + return f"`{value}`" + + +def md_codefence(value: str, language: str = "nix") -> str: + return indent( + f"\n```{language}\n{value}\n```", + prefix=2 * " ", + ) + + +def render_option_value(option: Mapping[str, Any], key: str) -> str: + if key not in option: return "" - if isinstance(opt[attr], dict) and "_type" in opt[attr]: - if opt[attr]["_type"] == "literalExpression": - if "\n" in opt[attr]["text"]: - text = opt[attr]["text"].rstrip("\n") - res = f"\n```nix\n{text}\n```" + if isinstance(option[key], dict) and "_type" in option[key]: + if option[key]["_type"] == "literalExpression": + # multi-line codeblock + if "\n" in option[key]["text"]: + text = option[key]["text"].rstrip("\n") + value = md_codefence(text) + # inline codeblock else: - res = f"```{opt[attr]["text"]}```" - elif opt[attr]["_type"] == "literalMD": - res = opt[attr]["text"] + value = md_literal(option[key]["text"]) + # literal markdown + elif option[key]["_type"] == "literalMD": + value = option[key]["text"] else: - assert RuntimeError(f"Unhandled option type {opt[attr]["_type"]}") + assert RuntimeError(f"Unhandled option type {option[key]['_type']}") else: - s = str(opt[attr]) - if s == "": - res = '`""`' - elif "\n" in s: - res = f"\n```\n{s.rstrip("\n")}\n```" + text = str(option[key]) + if text == "": + value = md_literal('""') + elif "\n" in text: + value = md_codefence(text.rstrip("\n")) else: - res = f"```{s}```" + value = md_literal(text) - return "- " + attr + ": " + res # type: ignore + return f"- {key}: {value}" # type: ignore -def print_option(opt): - if isinstance(opt["description"], dict) and "_type" in opt["description"]: # mdDoc - description = opt["description"]["text"] +def print_option(option): + if ( + isinstance(option["description"], dict) and "_type" in option["description"] + ): # mdDoc + description = option["description"]["text"] else: - description = opt["description"] + description = option["description"] print( template.format( - key=opt["name"], + key=option["name"], description=description or "", - type=f"- type: ```{opt["type"]}```", - default=render_option_value(opt, "default"), - example=render_option_value(opt, "example"), + type=f"- type: {md_literal(option['type'])}", + default=render_option_value(option, "default"), + example=render_option_value(option, "example"), ) )