2021-11-18 23:26:27 +00:00
|
|
|
import collections
|
|
|
|
import json
|
|
|
|
import sys
|
2021-12-18 17:57:45 +00:00
|
|
|
from typing import Any, Dict, List
|
|
|
|
|
2022-08-02 22:44:34 +00:00
|
|
|
# for MD conversion
|
|
|
|
import mistune
|
|
|
|
import re
|
|
|
|
from xml.sax.saxutils import escape, quoteattr
|
|
|
|
|
2021-12-18 17:57:45 +00:00
|
|
|
JSON = Dict[str, Any]
|
2021-11-18 23:26:27 +00:00
|
|
|
|
|
|
|
class Key:
|
2021-12-18 17:57:45 +00:00
|
|
|
def __init__(self, path: List[str]):
|
2021-11-18 23:26:27 +00:00
|
|
|
self.path = path
|
|
|
|
def __hash__(self):
|
|
|
|
result = 0
|
|
|
|
for id in self.path:
|
|
|
|
result ^= hash(id)
|
|
|
|
return result
|
|
|
|
def __eq__(self, other):
|
|
|
|
return type(self) is type(other) and self.path == other.path
|
|
|
|
|
|
|
|
Option = collections.namedtuple('Option', ['name', 'value'])
|
|
|
|
|
|
|
|
# pivot a dict of options keyed by their display name to a dict keyed by their path
|
2021-12-18 17:57:45 +00:00
|
|
|
def pivot(options: Dict[str, JSON]) -> Dict[Key, Option]:
|
|
|
|
result: Dict[Key, Option] = dict()
|
2021-11-18 23:26:27 +00:00
|
|
|
for (name, opt) in options.items():
|
|
|
|
result[Key(opt['loc'])] = Option(name, opt)
|
|
|
|
return result
|
|
|
|
|
|
|
|
# pivot back to indexed-by-full-name
|
|
|
|
# like the docbook build we'll just fail if multiple options with differing locs
|
|
|
|
# render to the same option name.
|
2021-12-18 17:57:45 +00:00
|
|
|
def unpivot(options: Dict[Key, Option]) -> Dict[str, JSON]:
|
|
|
|
result: Dict[str, Dict] = dict()
|
2021-11-18 23:26:27 +00:00
|
|
|
for (key, opt) in options.items():
|
|
|
|
if opt.name in result:
|
|
|
|
raise RuntimeError(
|
|
|
|
'multiple options with colliding ids found',
|
|
|
|
opt.name,
|
|
|
|
result[opt.name]['loc'],
|
|
|
|
opt.value['loc'],
|
|
|
|
)
|
|
|
|
result[opt.name] = opt.value
|
|
|
|
return result
|
|
|
|
|
2022-08-02 22:44:34 +00:00
|
|
|
admonitions = {
|
|
|
|
'.warning': 'warning',
|
|
|
|
'.important': 'important',
|
|
|
|
'.note': 'note'
|
|
|
|
}
|
|
|
|
class Renderer(mistune.renderers.BaseRenderer):
|
|
|
|
def _get_method(self, name):
|
|
|
|
try:
|
|
|
|
return super(Renderer, self)._get_method(name)
|
|
|
|
except AttributeError:
|
|
|
|
def not_supported(*args, **kwargs):
|
|
|
|
raise NotImplementedError("md node not supported yet", name, args, **kwargs)
|
|
|
|
return not_supported
|
|
|
|
|
|
|
|
def text(self, text):
|
|
|
|
return escape(text)
|
|
|
|
def paragraph(self, text):
|
|
|
|
return text + "\n\n"
|
|
|
|
def newline(self):
|
|
|
|
return "<literallayout>\n</literallayout>"
|
|
|
|
def codespan(self, text):
|
|
|
|
return f"<literal>{escape(text)}</literal>"
|
|
|
|
def block_code(self, text, info=None):
|
|
|
|
info = f" language={quoteattr(info)}" if info is not None else ""
|
|
|
|
return f"<programlisting{info}>\n{escape(text)}</programlisting>"
|
|
|
|
def link(self, link, text=None, title=None):
|
2022-08-03 17:18:33 +00:00
|
|
|
tag = "link"
|
2022-08-02 22:44:34 +00:00
|
|
|
if link[0:1] == '#':
|
2022-08-03 17:18:33 +00:00
|
|
|
if text == "":
|
|
|
|
tag = "xref"
|
2022-08-02 22:44:34 +00:00
|
|
|
attr = "linkend"
|
|
|
|
link = quoteattr(link[1:])
|
|
|
|
else:
|
|
|
|
# try to faithfully reproduce links that were of the form <link href="..."/>
|
|
|
|
# in docbook format
|
|
|
|
if text == link:
|
|
|
|
text = ""
|
|
|
|
attr = "xlink:href"
|
|
|
|
link = quoteattr(link)
|
2022-08-03 17:18:33 +00:00
|
|
|
return f"<{tag} {attr}={link}>{text}</{tag}>"
|
2022-08-02 22:44:34 +00:00
|
|
|
def list(self, text, ordered, level, start=None):
|
|
|
|
if ordered:
|
|
|
|
raise NotImplementedError("ordered lists not supported yet")
|
|
|
|
return f"<itemizedlist>\n{text}\n</itemizedlist>"
|
|
|
|
def list_item(self, text, level):
|
|
|
|
return f"<listitem><para>{text}</para></listitem>\n"
|
|
|
|
def block_text(self, text):
|
|
|
|
return text
|
|
|
|
def emphasis(self, text):
|
|
|
|
return f"<emphasis>{text}</emphasis>"
|
|
|
|
def strong(self, text):
|
|
|
|
return f"<emphasis role=\"strong\">{text}</emphasis>"
|
|
|
|
def admonition(self, text, kind):
|
|
|
|
if kind not in admonitions:
|
|
|
|
raise NotImplementedError(f"admonition {kind} not supported yet")
|
|
|
|
tag = admonitions[kind]
|
|
|
|
# we don't keep whitespace here because usually we'll contain only
|
|
|
|
# a single paragraph and the original docbook string is no longer
|
|
|
|
# available to restore the trailer.
|
|
|
|
return f"<{tag}><para>{text.rstrip()}</para></{tag}>"
|
|
|
|
def block_quote(self, text):
|
|
|
|
return f"<blockquote><para>{text}</para></blockquote>"
|
|
|
|
def command(self, text):
|
|
|
|
return f"<command>{escape(text)}</command>"
|
|
|
|
def option(self, text):
|
|
|
|
return f"<option>{escape(text)}</option>"
|
|
|
|
def file(self, text):
|
|
|
|
return f"<filename>{escape(text)}</filename>"
|
2022-08-29 16:01:47 +00:00
|
|
|
def var(self, text):
|
|
|
|
return f"<varname>{escape(text)}</varname>"
|
|
|
|
def env(self, text):
|
|
|
|
return f"<envar>{escape(text)}</envar>"
|
2022-08-02 22:44:34 +00:00
|
|
|
def manpage(self, page, section):
|
|
|
|
title = f"<refentrytitle>{escape(page)}</refentrytitle>"
|
|
|
|
vol = f"<manvolnum>{escape(section)}</manvolnum>"
|
|
|
|
return f"<citerefentry>{title}{vol}</citerefentry>"
|
|
|
|
|
|
|
|
def finalize(self, data):
|
|
|
|
return "".join(data)
|
|
|
|
|
|
|
|
def p_command(md):
|
2022-06-03 19:47:57 +00:00
|
|
|
COMMAND_PATTERN = r'\{command\}`(.*?)`'
|
2022-08-02 22:44:34 +00:00
|
|
|
def parse(self, m, state):
|
|
|
|
return ('command', m.group(1))
|
|
|
|
md.inline.register_rule('command', COMMAND_PATTERN, parse)
|
|
|
|
md.inline.rules.append('command')
|
2022-06-03 19:47:57 +00:00
|
|
|
|
2022-08-02 22:44:34 +00:00
|
|
|
def p_file(md):
|
2022-06-03 19:47:57 +00:00
|
|
|
FILE_PATTERN = r'\{file\}`(.*?)`'
|
2022-08-02 22:44:34 +00:00
|
|
|
def parse(self, m, state):
|
|
|
|
return ('file', m.group(1))
|
|
|
|
md.inline.register_rule('file', FILE_PATTERN, parse)
|
|
|
|
md.inline.rules.append('file')
|
2022-06-03 19:47:57 +00:00
|
|
|
|
2022-08-29 16:01:47 +00:00
|
|
|
def p_var(md):
|
|
|
|
VAR_PATTERN = r'\{var\}`(.*?)`'
|
|
|
|
def parse(self, m, state):
|
|
|
|
return ('var', m.group(1))
|
|
|
|
md.inline.register_rule('var', VAR_PATTERN, parse)
|
|
|
|
md.inline.rules.append('var')
|
|
|
|
|
|
|
|
def p_env(md):
|
|
|
|
ENV_PATTERN = r'\{env\}`(.*?)`'
|
|
|
|
def parse(self, m, state):
|
|
|
|
return ('env', m.group(1))
|
|
|
|
md.inline.register_rule('env', ENV_PATTERN, parse)
|
|
|
|
md.inline.rules.append('env')
|
|
|
|
|
2022-08-02 22:44:34 +00:00
|
|
|
def p_option(md):
|
2022-06-03 19:47:57 +00:00
|
|
|
OPTION_PATTERN = r'\{option\}`(.*?)`'
|
2022-08-02 22:44:34 +00:00
|
|
|
def parse(self, m, state):
|
|
|
|
return ('option', m.group(1))
|
|
|
|
md.inline.register_rule('option', OPTION_PATTERN, parse)
|
|
|
|
md.inline.rules.append('option')
|
2022-06-03 19:47:57 +00:00
|
|
|
|
2022-08-02 22:44:34 +00:00
|
|
|
def p_manpage(md):
|
2022-06-03 19:47:57 +00:00
|
|
|
MANPAGE_PATTERN = r'\{manpage\}`(.*?)\((.+?)\)`'
|
2022-08-02 22:44:34 +00:00
|
|
|
def parse(self, m, state):
|
|
|
|
return ('manpage', m.group(1), m.group(2))
|
|
|
|
md.inline.register_rule('manpage', MANPAGE_PATTERN, parse)
|
|
|
|
md.inline.rules.append('manpage')
|
2022-06-03 19:47:57 +00:00
|
|
|
|
2022-08-02 22:44:34 +00:00
|
|
|
def p_admonition(md):
|
2022-08-20 21:21:30 +00:00
|
|
|
ADMONITION_PATTERN = re.compile(r'^::: \{([^\n]*?)\}\n(.*?)^:::$\n*', flags=re.MULTILINE|re.DOTALL)
|
2022-08-02 22:44:34 +00:00
|
|
|
def parse(self, m, state):
|
|
|
|
return {
|
|
|
|
'type': 'admonition',
|
|
|
|
'children': self.parse(m.group(2), state),
|
|
|
|
'params': [ m.group(1) ],
|
|
|
|
}
|
|
|
|
md.block.register_rule('admonition', ADMONITION_PATTERN, parse)
|
|
|
|
md.block.rules.append('admonition')
|
|
|
|
|
|
|
|
md = mistune.create_markdown(renderer=Renderer(), plugins=[
|
2022-08-29 16:01:47 +00:00
|
|
|
p_command, p_file, p_var, p_env, p_option, p_manpage, p_admonition
|
2022-08-02 22:44:34 +00:00
|
|
|
])
|
2022-06-03 19:47:57 +00:00
|
|
|
|
2022-08-02 22:44:34 +00:00
|
|
|
# converts in-place!
|
|
|
|
def convertMD(options: Dict[str, Any]) -> str:
|
2022-07-27 15:50:28 +00:00
|
|
|
def convertString(path: str, text: str) -> str:
|
2022-08-02 22:44:34 +00:00
|
|
|
try:
|
|
|
|
rendered = md(text)
|
|
|
|
# keep trailing spaces so we can diff the generated XML to check for conversion bugs.
|
|
|
|
return rendered.rstrip() + text[len(text.rstrip()):]
|
|
|
|
except:
|
|
|
|
print(f"error in {path}")
|
|
|
|
raise
|
2022-06-03 19:47:57 +00:00
|
|
|
|
|
|
|
def optionIs(option: Dict[str, Any], key: str, typ: str) -> bool:
|
|
|
|
if key not in option: return False
|
|
|
|
if type(option[key]) != dict: return False
|
|
|
|
if '_type' not in option[key]: return False
|
|
|
|
return option[key]['_type'] == typ
|
|
|
|
|
|
|
|
for (name, option) in options.items():
|
2022-11-11 05:31:15 +00:00
|
|
|
try:
|
|
|
|
if optionIs(option, 'description', 'mdDoc'):
|
|
|
|
option['description'] = convertString(name, option['description']['text'])
|
|
|
|
elif markdownByDefault:
|
|
|
|
option['description'] = convertString(name, option['description'])
|
|
|
|
|
|
|
|
if optionIs(option, 'example', 'literalMD'):
|
|
|
|
docbook = convertString(name, option['example']['text'])
|
|
|
|
option['example'] = { '_type': 'literalDocBook', 'text': docbook }
|
|
|
|
if optionIs(option, 'default', 'literalMD'):
|
|
|
|
docbook = convertString(name, option['default']['text'])
|
|
|
|
option['default'] = { '_type': 'literalDocBook', 'text': docbook }
|
|
|
|
except Exception as e:
|
|
|
|
raise Exception(f"Failed to render option {name}: {str(e)}")
|
|
|
|
|
2022-06-03 19:47:57 +00:00
|
|
|
|
|
|
|
return options
|
|
|
|
|
2022-09-01 17:23:59 +00:00
|
|
|
warningsAreErrors = False
|
|
|
|
errorOnDocbook = False
|
2022-11-11 05:15:46 +00:00
|
|
|
markdownByDefault = False
|
2022-09-01 17:23:59 +00:00
|
|
|
optOffset = 0
|
|
|
|
for arg in sys.argv[1:]:
|
|
|
|
if arg == "--warnings-are-errors":
|
|
|
|
optOffset += 1
|
|
|
|
warningsAreErrors = True
|
|
|
|
if arg == "--error-on-docbook":
|
|
|
|
optOffset += 1
|
|
|
|
errorOnDocbook = True
|
2022-11-11 05:15:46 +00:00
|
|
|
if arg == "--markdown-by-default":
|
|
|
|
optOffset += 1
|
|
|
|
markdownByDefault = True
|
2022-09-01 17:23:59 +00:00
|
|
|
|
2021-12-18 18:37:41 +00:00
|
|
|
options = pivot(json.load(open(sys.argv[1 + optOffset], 'r')))
|
|
|
|
overrides = pivot(json.load(open(sys.argv[2 + optOffset], 'r')))
|
2021-11-18 23:26:27 +00:00
|
|
|
|
|
|
|
# fix up declaration paths in lazy options, since we don't eval them from a full nixpkgs dir
|
|
|
|
for (k, v) in options.items():
|
2022-03-24 01:44:43 +00:00
|
|
|
# The _module options are not declared in nixos/modules
|
|
|
|
if v.value['loc'][0] != "_module":
|
2022-06-27 18:03:34 +00:00
|
|
|
v.value['declarations'] = list(map(lambda s: f'nixos/modules/{s}' if isinstance(s, str) else s, v.value['declarations']))
|
2021-11-18 23:26:27 +00:00
|
|
|
|
|
|
|
# merge both descriptions
|
|
|
|
for (k, v) in overrides.items():
|
|
|
|
cur = options.setdefault(k, v).value
|
|
|
|
for (ok, ov) in v.value.items():
|
|
|
|
if ok == 'declarations':
|
|
|
|
decls = cur[ok]
|
|
|
|
for d in ov:
|
|
|
|
if d not in decls:
|
|
|
|
decls += [d]
|
|
|
|
elif ok == "type":
|
|
|
|
# ignore types of placeholder options
|
|
|
|
if ov != "_unspecified" or cur[ok] == "_unspecified":
|
|
|
|
cur[ok] = ov
|
|
|
|
elif ov is not None or cur.get(ok, None) is None:
|
|
|
|
cur[ok] = ov
|
|
|
|
|
2021-06-16 10:27:47 +00:00
|
|
|
severity = "error" if warningsAreErrors else "warning"
|
|
|
|
|
2022-09-01 17:23:59 +00:00
|
|
|
def is_docbook(o, key):
|
|
|
|
val = o.get(key, {})
|
|
|
|
if not isinstance(val, dict):
|
|
|
|
return False
|
|
|
|
return val.get('_type', '') == 'literalDocBook'
|
|
|
|
|
2021-11-18 23:26:27 +00:00
|
|
|
# check that every option has a description
|
2021-12-18 18:37:41 +00:00
|
|
|
hasWarnings = False
|
2022-09-01 17:23:59 +00:00
|
|
|
hasErrors = False
|
2022-09-17 12:38:23 +00:00
|
|
|
hasDocBookErrors = False
|
2021-11-18 23:26:27 +00:00
|
|
|
for (k, v) in options.items():
|
2022-09-01 17:23:59 +00:00
|
|
|
if errorOnDocbook:
|
|
|
|
if isinstance(v.value.get('description', {}), str):
|
|
|
|
hasErrors = True
|
2022-09-17 12:38:23 +00:00
|
|
|
hasDocBookErrors = True
|
2022-09-01 17:23:59 +00:00
|
|
|
print(
|
|
|
|
f"\x1b[1;31merror: option {v.name} description uses DocBook\x1b[0m",
|
|
|
|
file=sys.stderr)
|
|
|
|
elif is_docbook(v.value, 'defaultText'):
|
|
|
|
hasErrors = True
|
2022-09-17 12:38:23 +00:00
|
|
|
hasDocBookErrors = True
|
2022-09-01 17:23:59 +00:00
|
|
|
print(
|
|
|
|
f"\x1b[1;31merror: option {v.name} default uses DocBook\x1b[0m",
|
|
|
|
file=sys.stderr)
|
|
|
|
elif is_docbook(v.value, 'example'):
|
|
|
|
hasErrors = True
|
2022-09-17 12:38:23 +00:00
|
|
|
hasDocBookErrors = True
|
2022-09-01 17:23:59 +00:00
|
|
|
print(
|
|
|
|
f"\x1b[1;31merror: option {v.name} example uses DocBook\x1b[0m",
|
|
|
|
file=sys.stderr)
|
|
|
|
|
2021-11-18 23:26:27 +00:00
|
|
|
if v.value.get('description', None) is None:
|
2021-12-18 18:37:41 +00:00
|
|
|
hasWarnings = True
|
|
|
|
print(f"\x1b[1;31m{severity}: option {v.name} has no description\x1b[0m", file=sys.stderr)
|
2021-11-18 23:26:27 +00:00
|
|
|
v.value['description'] = "This option has no description."
|
2021-06-16 10:27:47 +00:00
|
|
|
if v.value.get('type', "unspecified") == "unspecified":
|
|
|
|
hasWarnings = True
|
|
|
|
print(
|
|
|
|
f"\x1b[1;31m{severity}: option {v.name} has no type. Please specify a valid type, see " +
|
|
|
|
"https://nixos.org/manual/nixos/stable/index.html#sec-option-types\x1b[0m", file=sys.stderr)
|
|
|
|
|
2022-09-17 12:38:23 +00:00
|
|
|
if hasDocBookErrors:
|
|
|
|
print("Explanation: The documentation contains descriptions, examples, or defaults written in DocBook. " +
|
|
|
|
"NixOS is in the process of migrating from DocBook to Markdown, and " +
|
|
|
|
"DocBook is disallowed for in-tree modules. To change your contribution to "+
|
|
|
|
"use Markdown, apply mdDoc and literalMD. For example:\n" +
|
|
|
|
"\n" +
|
|
|
|
" example.foo = mkOption {\n" +
|
|
|
|
" description = lib.mdDoc ''your description'';\n" +
|
|
|
|
" defaultText = lib.literalMD ''your description of default'';\n" +
|
|
|
|
" }\n" +
|
|
|
|
"\n" +
|
|
|
|
" example.enable = mkEnableOption (lib.mdDoc ''your thing'');",
|
|
|
|
file = sys.stderr)
|
|
|
|
|
2022-09-01 17:23:59 +00:00
|
|
|
if hasErrors:
|
|
|
|
sys.exit(1)
|
2021-12-18 18:37:41 +00:00
|
|
|
if hasWarnings and warningsAreErrors:
|
|
|
|
print(
|
|
|
|
"\x1b[1;31m" +
|
|
|
|
"Treating warnings as errors. Set documentation.nixos.options.warningsAreErrors " +
|
|
|
|
"to false to ignore these warnings." +
|
|
|
|
"\x1b[0m",
|
|
|
|
file=sys.stderr)
|
|
|
|
sys.exit(1)
|
2021-11-18 23:26:27 +00:00
|
|
|
|
2022-06-03 19:47:57 +00:00
|
|
|
json.dump(convertMD(unpivot(options)), fp=sys.stdout)
|