Skip to content

Commit 85192b8

Browse files
committed
docs: update cpp reference links
1 parent 084441b commit 85192b8

File tree

9 files changed

+399
-261
lines changed

9 files changed

+399
-261
lines changed

content/reference/cpp/index.mdx

Lines changed: 164 additions & 164 deletions
Large diffs are not rendered by default.

scripts/docgen/_rendering.py

Lines changed: 0 additions & 64 deletions
This file was deleted.

scripts/docgen/cppgen.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
import logging
33
from pathlib import Path
44

5+
from generator import Generator, BaseGenerator
56
from mkdoxy.cache import Cache
67
from mkdoxy.constants import Kind
78
from mkdoxy.doxygen import Doxygen
89
from mkdoxy.doxyrun import DoxygenRun
910
from mkdoxy.generatorBase import GeneratorBase
1011
from mkdoxy.xml_parser import XmlParser
11-
from generator import Generator
1212

1313
logging.basicConfig()
1414
log: logging.Logger = logging.getLogger("mkdocs")
@@ -29,7 +29,9 @@ def generate(base_dir: Path, debug: bool = True):
2929
"STRIP_FROM_INC_PATH": str(base_dir / "include"),
3030
}
3131

32-
runner = DoxygenRun('doxygen', str(base_dir / "include" / "endstone"), str(temp_dir), config, "")
32+
runner = DoxygenRun(
33+
"doxygen", str(base_dir / "include" / "endstone"), str(temp_dir), config, ""
34+
)
3335
if runner.checkAndRun():
3436
log.info(" -> generating Doxygen files")
3537
else:
@@ -48,7 +50,7 @@ def generate(base_dir: Path, debug: bool = True):
4850

4951
# Prepare generator for future use (GeneratorAuto, SnippetGenerator)
5052
template_dir = str(Path(__file__).parent / "templates" / "mkdoxy")
51-
base_generator = GeneratorBase(template_dir, ignore_errors=False, debug=debug)
53+
base_generator = BaseGenerator(template_dir, ignore_errors=False, debug=debug)
5254

5355
generator = Generator(
5456
generatorBase=base_generator,

scripts/docgen/extension.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
11
import ast
2-
3-
from griffe import Class, Extension, Function, Inspector, Kind, ObjectNode, Visitor, typing_overload
42
from typing import Any
53

4+
from griffe import (
5+
Class,
6+
Extension,
7+
Function,
8+
Inspector,
9+
Kind,
10+
ObjectNode,
11+
Visitor,
12+
typing_overload,
13+
)
14+
615

716
class StubOverloadExtension(Extension):
817
def on_function_instance(
9-
self,
10-
*,
11-
node: ast.AST | ObjectNode,
12-
func: Function,
13-
agent: Visitor | Inspector,
14-
**kwargs: Any,
18+
self,
19+
*,
20+
node: ast.AST | ObjectNode,
21+
func: Function,
22+
agent: Visitor | Inspector,
23+
**kwargs: Any,
1524
) -> None:
1625
"""
1726
Fix overloads with implementations in stub files not detected

scripts/docgen/filters.py

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import re
2+
from typing import Sequence
3+
4+
from griffe import DocstringFunction, DocstringSectionFunctions, Function
5+
6+
7+
def do_heading(
8+
content: str, heading_level: int, role: str | None = None, **attributes: str
9+
) -> str:
10+
"""Render a Markdown heading.
11+
12+
Arguments:
13+
content: The HTML within the heading.
14+
heading_level: The level of heading (e.g. 3 -> `###`).
15+
role: An optional role for the object bound to this heading.
16+
**attributes: Any extra attributes of the heading.
17+
"""
18+
19+
heading = f"\n{'#' * heading_level}"
20+
21+
if role:
22+
heading += f' <code className="doc-symbol doc-symbol-{role}"/>'
23+
24+
heading += f" {content}"
25+
26+
if "id" in attributes:
27+
heading += f" [#{attributes['id']}]"
28+
29+
heading += "\n\n"
30+
return heading
31+
32+
33+
def do_as_functions_section(
34+
functions: Sequence[Function],
35+
*,
36+
check_public: bool = True,
37+
) -> DocstringSectionFunctions:
38+
"""Build a functions section from a list of functions.
39+
40+
Parameters:
41+
functions: The functions to build the section from.
42+
check_public: Whether to check if the function is public.
43+
44+
Returns:
45+
A functions docstring section.
46+
"""
47+
value = []
48+
for function in functions:
49+
if (check_public and not function.is_public) or (function.name == "__init__"):
50+
continue
51+
52+
if function.overloads:
53+
value.append(
54+
DocstringFunction(
55+
name=function.name,
56+
description="\n".join(
57+
list(
58+
dict.fromkeys(
59+
[
60+
overload.docstring.value.split("\n", 1)[0]
61+
if overload.docstring
62+
else ""
63+
for overload in function.overloads
64+
]
65+
)
66+
)
67+
),
68+
)
69+
)
70+
71+
else:
72+
value.append(
73+
DocstringFunction(
74+
name=function.name,
75+
description=function.docstring.value.split("\n", 1)[0]
76+
if function.docstring
77+
else "",
78+
)
79+
)
80+
81+
return DocstringSectionFunctions(value)
82+
83+
84+
def do_format_refid(refid: str) -> str:
85+
"""
86+
Examples:
87+
'classendstone_1_1_dimension' -> 'dimension'
88+
'classfoo_1_1bar_1_1Baz' -> 'baz'
89+
'structmy__type' -> 'my_type'
90+
'classns_1_1vector_3_01T_01_4' -> 'vector'
91+
"""
92+
if not refid:
93+
return ""
94+
# drop leading kind
95+
s = re.sub(r"^(class|struct|union|interface|namespace|enum|file)", "", refid)
96+
# take last namespace component
97+
s = re.split(r"(?:_1_1)+", s)[-1]
98+
# remove any stray leading underscores left by the split (e.g. '_dimension')
99+
s = s.lstrip("_")
100+
# remove template-argument encoding (anything after '_3')
101+
s = re.sub(r"_[3-9].*$", "", s)
102+
# fix doxygen’s doubled-underscore escape
103+
s = s.replace("__", "_")
104+
105+
if s == "u_u_i_d":
106+
s = "uuid"
107+
108+
return s.lower()

scripts/docgen/generator.py

Lines changed: 87 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,105 @@
1+
import logging
12
import os
23

4+
import filters
5+
import mkdoxy
6+
from jinja2 import BaseLoader, Environment, Template
7+
from mkdocs import exceptions
38
from mkdocs.structure import files
9+
from mkdoxy.filters import use_code_language
410
from mkdoxy.generatorAuto import GeneratorAuto
11+
from mkdoxy.generatorBase import GeneratorBase
512
from mkdoxy.node import Node
6-
import inflection
13+
from mkdoxy.utils import parseTemplateFile
14+
15+
from scripts.docgen.filters import do_format_refid
16+
17+
log: logging.Logger = logging.getLogger("mkdocs")
18+
19+
20+
class BaseGenerator(GeneratorBase):
21+
def __init__(
22+
self, templateDir: str = "", ignore_errors: bool = False, debug: bool = False
23+
):
24+
"""! Constructor.
25+
@details
26+
@param templateDir (str): Path to the directory with custom templates (default: "")
27+
@param ignore_errors (bool): If True, errors will be ignored (default: False)
28+
@param debug (bool): If True, debug messages will be printed (default: False)
29+
"""
30+
31+
"""! Constructor.
32+
@details
33+
@param templateDir (str): Path to the directory with custom templates (default: "")
34+
@param ignore_errors (bool): If True, errors will be ignored (default: False)
35+
@param debug (bool): If True, debug messages will be printed (default: False)
36+
"""
37+
38+
self.debug: bool = debug # if True, debug messages will be printed
39+
self.templates: dict[str, Template] = {}
40+
self.metaData: dict[str, list[str]] = {}
41+
42+
environment = Environment(loader=BaseLoader())
43+
environment.filters["use_code_language"] = use_code_language
44+
environment.filters["format_refid"] = do_format_refid
45+
# code from https://github.com/daizutabi/mkapi/blob/master/mkapi/core/renderer.py#L29-L38
46+
path = os.path.join(os.path.dirname(mkdoxy.__file__), "templates")
47+
ENDING = (".jinja2", ".j2", ".jinja")
48+
for fileName in os.listdir(path):
49+
filePath = os.path.join(path, fileName)
50+
51+
# accept any case of the file ending
52+
if fileName.lower().endswith(ENDING):
53+
with open(filePath, "r") as file:
54+
name = os.path.splitext(fileName)[0]
55+
fileTemplate, metaData = parseTemplateFile(file.read())
56+
self.templates[name] = environment.from_string(fileTemplate)
57+
self.metaData[name] = metaData
58+
else:
59+
log.error(
60+
f"Trying to load unsupported file '{filePath}'. Supported file ends with {ENDING}."
61+
f"Look at documentation: https://mkdoxy.kubaandrysek.cz/usage/#custom-jinja-templates."
62+
)
63+
64+
# test if templateDir is existing
65+
if templateDir:
66+
if not os.path.exists(templateDir):
67+
raise exceptions.ConfigurationError(
68+
f"Custom template directory '{templateDir}' does not exist."
69+
)
70+
# load custom templates and overwrite default templates - if they exist
71+
for fileName in os.listdir(templateDir):
72+
filePath = os.path.join(templateDir, fileName)
73+
if fileName.lower().endswith(ENDING):
74+
with open(filePath, "r") as file:
75+
name = os.path.splitext(fileName)[0]
76+
fileTemplate, metaData = parseTemplateFile(file.read())
77+
self.templates[name] = environment.from_string(fileTemplate)
78+
self.metaData[name] = metaData
79+
log.info(f"Overwriting template '{name}' with custom template.")
80+
else:
81+
log.error(
82+
f"Trying to load unsupported file '{filePath}'. Supported file ends with {ENDING}."
83+
f"Look at documentation: https://mkdoxy.kubaandrysek.cz/usage/#custom-jinja-templates."
84+
)
785

886

987
class Generator(GeneratorAuto):
1088
def save(self, path: str, output: str):
1189
rel_path = os.path.join(self.apiPath, path)
12-
self.fullDocFiles.append(files.File(rel_path, self.tempDoxyDir, self.siteDir, self.useDirectoryUrls))
90+
self.fullDocFiles.append(
91+
files.File(rel_path, self.tempDoxyDir, self.siteDir, self.useDirectoryUrls)
92+
)
1393
with open(os.path.join(self.siteDir, rel_path), "w", encoding="utf-8") as file:
1494
file.write(output)
1595

1696
def member(self, node: Node, config: dict = None):
17-
path = inflection.underscore(node.name_short) + ".mdx"
97+
path = filters.do_format_refid(node.refid) + ".mdx"
1898

1999
output = ""
20-
output += '---\n'
100+
output += "---\n"
21101
output += f'title: "{node.name_short}"\n'
22-
output += '---\n\n'
102+
output += "---\n\n"
23103
output += self.generatorBase.member(node, config)
24104
self.save(path, output)
25105

@@ -30,8 +110,8 @@ def classes(self, nodes: [Node], config: dict = None):
30110
path = "index.mdx"
31111

32112
output = ""
33-
output += '---\n'
113+
output += "---\n"
34114
output += f'asIndexPage: true"\n'
35-
output += '---\n\n'
115+
output += "---\n\n"
36116
output += self.generatorBase.classes(nodes, config)
37117
self.save(path, output)

scripts/docgen/main.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
import argparse
22
from pathlib import Path
3-
import pygen
3+
44
import cppgen
5+
import pygen
56

67
if __name__ == "__main__":
78
parser = argparse.ArgumentParser()
8-
parser.add_argument("base_dir", type=Path, help="Base directory for code generation")
9+
parser.add_argument(
10+
"base_dir", type=Path, help="Base directory for code generation"
11+
)
912
parser.add_argument(
1013
"--language",
1114
type=str,
1215
choices=["python", "cpp"],
13-
help="Language to generate code for (default: both)"
16+
help="Language to generate code for (default: both)",
1417
)
1518
args = parser.parse_args()
1619

0 commit comments

Comments
 (0)