Debian Codegraph @

docs/mkdocs/scripts/check_structure.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 import glob
4 import os.path
5 import re
6 import sys
7
8 import yaml
9
10 warnings = 0
11
12
13 def report(rule, location, description) -> None:
14 global warnings
15 warnings += 1
16 print(f'{warnings:3}. {location}: {description} [{rule}]')
17
18
19 def check_structure() -> None:
20 expected_sections = [
21 "Template parameters",
22 "Specializations",
23 "Iterator invalidation",
24 "Requirements",
25 "Member types",
26 "Member functions",
27 "Member variables",
28 "Static functions",
29 "Non-member functions",
30 "Literals",
31 "Helper classes",
32 "Parameters",
33 "Return value",
34 "Exception safety",
35 "Exceptions",
36 "Complexity",
37 "Possible implementation",
38 "Default definition",
39 "Notes",
40 "Examples",
41 "See also",
42 "Version history",
43 ]
44
45 required_sections = [
46 "Examples",
47 "Version history",
48 ]
49
50 files = sorted(glob.glob("api/**/*.md", recursive=True))
51 for file in files:
52 with open(file) as file_content:
53 section_idx = -1 # the index of the current h2 section
54 existing_sections = [] # the list of h2 sections in the file
55 in_initial_code_example = False # whether we are inside the first code example block
56 previous_line = None # the previous read line
57 h1sections = 0 # the number of h1 sections in the file
58 last_overload = 0 # the last seen overload number in the code example
59 documented_overloads = {} # the overloads that have been documented in the current block
60 current_section = None # the name of the current section
61
62 for lineno, original_line in enumerate(file_content.readlines()):
63 line = original_line.strip()
64
65 if line.startswith("# "):
66 h1sections += 1
67
68 # there should only be one top-level title
69 if h1sections > 1:
70 report("structure/unexpected_section", f"{file}:{lineno+1}", f'unexpected top-level title "{line}"')
71 h1sections = 1
72
73 # Overview pages should have a better title
74 if line == "# Overview":
75 report("style/title", f"{file}:{lineno+1}", 'overview pages should have a better title than "Overview"')
76
77 # lines longer than 160 characters are bad (unless they are tables)
78 if len(line) > 160 and "|" not in line:
79 report("whitespace/line_length", f"{file}:{lineno+1} ({current_section})", f"line is too long ({len(line)} vs. 160 chars)")
80
81 # sections in `<!-- NOLINT -->` comments are treated as present
82 if line.startswith("<!-- NOLINT"):
83 current_section = line.strip("<!-- NOLINT")
84 current_section = current_section.strip(" -->")
85 existing_sections.append(current_section)
86
87 # check if sections are correct
88 if line.startswith("## "):
89 # before starting a new section, check if the previous one documented all overloads
90 if current_section in documented_overloads and last_overload != 0:
91 if len(documented_overloads[current_section]) > 0 and len(documented_overloads[current_section]) != last_overload:
92 expected = list(range(1, last_overload+1))
93 undocumented = [x for x in expected if x not in documented_overloads[current_section]]
94 unexpected = [x for x in documented_overloads[current_section] if x not in expected]
95 if len(undocumented):
96 report("style/numbering", f"{file}:{lineno} ({current_section})", f'undocumented overloads: {", ".join([f"({x})" for x in undocumented])}')
97 if len(unexpected):
98 report("style/numbering", f"{file}:{lineno} ({current_section})", f'unexpected overloads: {", ".join([f"({x})" for x in unexpected])}')
99
100 current_section = line.strip("## ")
101 existing_sections.append(current_section)
102
103 if current_section in expected_sections:
104 idx = expected_sections.index(current_section)
105 if idx <= section_idx:
106 report("structure/section_order", f"{file}:{lineno+1}", f'section "{current_section}" is in an unexpected order (should be before "{expected_sections[section_idx]}")')
107 section_idx = idx
108 elif "index.md" not in file: # index.md files may have a different structure
109 report("structure/unknown_section", f"{file}:{lineno+1}", f'section "{current_section}" is not part of the expected sections')
110
111 # collect the numbered items of the current section to later check if they match the number of overloads
112 if last_overload != 0 and not in_initial_code_example:
113 if len(original_line) and original_line[0].isdigit():
114 number = int(re.findall(r"^(\d+).", original_line)[0])
115 if current_section not in documented_overloads:
116 documented_overloads[current_section] = []
117 documented_overloads[current_section].append(number)
118
119 # code example
120 if line == "```cpp" and section_idx == -1:
121 in_initial_code_example = True
122
123 if in_initial_code_example and line.startswith("//") and line not in ["// since C++20", "// until C++20"]:
124 # check numbering of overloads
125 if any(map(str.isdigit, line)):
126 number = int(re.findall(r"\d+", line)[0])
127 if number != last_overload + 1:
128 report("style/numbering", f"{file}:{lineno+1}", f"expected number ({number}) to be ({last_overload +1 })")
129 last_overload = number
130
131 if any(map(str.isdigit, line)) and "(" not in line:
132 report("style/numbering", f"{file}:{lineno+1}", f"number should be in parentheses: {line}")
133
134 if line == "```" and in_initial_code_example:
135 in_initial_code_example = False
136
137 # consecutive blank lines are bad
138 if line == "" and previous_line == "":
139 report("whitespace/blank_lines", f"{file}:{lineno}-{lineno+1} ({current_section})", "consecutive blank lines")
140
141 # check that non-example admonitions have titles
142 untitled_admonition = re.match(r"^(\?\?\?|!!!) ([^ ]+)$", line)
143 if untitled_admonition and untitled_admonition.group(2) != "example":
144 report("style/admonition_title", f"{file}:{lineno} ({current_section})", f'"{untitled_admonition.group(2)}" admonitions should have a title')
145
146 previous_line = line
147
148 if "index.md" not in file: # index.md files may have a different structure
149 for required_section in required_sections:
150 if required_section not in existing_sections:
151 report("structure/missing_section", f"{file}:{lineno+1}", f'required section "{required_section}" was not found')
152
153
154 def check_examples() -> None:
155 example_files = sorted(glob.glob("../../examples/*.cpp"))
156 markdown_files = sorted(glob.glob("**/*.md", recursive=True))
157
158 # check if every example file is used in at least one markdown file
159 for example_file in example_files:
160 example_file = os.path.join("examples", os.path.basename(example_file))
161
162 found = False
163 for markdown_file in markdown_files:
164 content = " ".join(open(markdown_file).readlines())
165 if example_file in content:
166 found = True
167 break
168
169 if not found:
170 report("examples/missing", f"{example_file}", "example file is not used in any documentation file")
171
172
173 def check_links() -> None:
174 """Check that every entry in the navigation (nav in mkdocs.yml) links to at most one file. If a file is linked more
175 than once, then the first entry is repeated. See https://github.com/nlohmann/json/issues/4564 for the issue in
176 this project and https://github.com/mkdocs/mkdocs/issues/3428 for the root cause.
177
178 The issue can be fixed by merging the keys, so
179
180 - 'NLOHMANN_JSON_VERSION_MAJOR': api/macros/nlohmann_json_version_major.md
181 - 'NLOHMANN_JSON_VERSION_MINOR': api/macros/nlohmann_json_version_major.md
182
183 would be replaced with
184
185 - 'NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR': api/macros/nlohmann_json_version_major.md
186 """
187 file_with_path = {}
188
189 def collect_links(node, path="") -> None:
190 if isinstance(node, list):
191 for x in node:
192 collect_links(x, path)
193 elif isinstance(node, dict):
194 for p, x in node.items():
195 collect_links(x, path + "/" + p)
196 else:
197 if node not in file_with_path:
198 file_with_path[node] = []
199 file_with_path[node].append(path)
200
201 with open("../mkdocs.yml") as mkdocs_file:
202 # see https://github.com/yaml/pyyaml/issues/86#issuecomment-1042485535
203 yaml.add_multi_constructor("tag:yaml.org,2002:python/name", lambda loader, suffix, node: None, Loader=yaml.SafeLoader)
204 yaml.add_multi_constructor("!ENV", lambda loader, suffix, node: None, Loader=yaml.SafeLoader)
205 y = yaml.safe_load(mkdocs_file)
206
207 collect_links(y["nav"])
208 for duplicate_file in [x for x in file_with_path if len(file_with_path[x]) > 1]:
209 file_list = [f'"{x}"' for x in file_with_path[duplicate_file]]
210 file_list_str = ", ".join(file_list)
211 report("nav/duplicate_files", "mkdocs.yml", f'file "{duplicate_file}" is linked with multiple keys in "nav": {file_list_str}; only one is rendered properly, see #4564')
212
213
214 if __name__ == "__main__":
215 print(120 * "-")
216 check_structure()
217 check_examples()
218 check_links()
219 print(120 * "-")
220
221 if warnings > 0:
222 sys.exit(1)