Coverage for trlcdoc/pages.py: 100%

118 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 14:00 +0000

1"""Placeholders of project owned pages and the check of their tables of contents. 

2 

3Project owned pages (html.index, html.page_header, rst and markdown documents) are copied into 

4the generated Sphinx folder at different depths. Their placeholders are replaced per page: 

5 

6- {project_root}: the relative path from the page to the project root 

7- {page:<id>}: the page name of a document, relative to the page 

8- {documents}: the page names of the documents in configuration order, one per line, without 

9 the documents a toctree of a project page lists explicitly 

10 

11With a project start page, the project owns the table of contents. The check compares its 

12toctree entries with the page names of the documents, which depend on the document type and 

13the format of the tracing report. 

14 

15""" 

16 

17# trlcdoc - A utility for producing project documentation from TRLC and LOBSTER contents. 

18# Copyright (c) 2026 - 2026 Norbert Schulz github@schulznorbert.de 

19# 

20# This file is part of trlcdoc program. 

21# 

22# The trlcdoc program is free software: you can redistribute it and/or modify it under 

23# the terms of the GNU General Public License as published by the Free Software Foundation, 

24# either version 3 of the License, or (at your option) any later version. 

25# 

26# The trlcdoc program is distributed in the hope that it will be useful, but 

27# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 

28# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 

29# 

30# You should have received a copy of the GNU General Public License along with pyTRLCConverter. 

31# If not, see <https://www.gnu.org/licenses/>. 

32 

33# Imports ********************************************************************** 

34 

35import os 

36import re 

37from pathlib import Path 

38from typing import Any 

39 

40from .config import PAGE_PLACEHOLDER, Config 

41 

42# Variables ******************************************************************** 

43 

44# Placeholder for the relative path from a page to the project root. 

45PROJECT_ROOT_PLACEHOLDER = "{project_root}" 

46 

47# Placeholder for the page names of all documents, alone on its line. Its indentation is kept 

48# for every page name, so it can be used as content of a toctree. 

49DOCUMENTS_PLACEHOLDER = re.compile(r"^([ \t]*)\{documents\}[ \t]*(\r?)$", re.MULTILINE) 

50 

51# Start of a reStructuredText toctree directive, with its indentation. 

52RST_TOCTREE = re.compile(r"^([ \t]*)\.\.[ \t]+toctree::") 

53 

54# Start of a MyST toctree directive in Markdown: a code fence of backticks or colons. 

55MD_TOCTREE = re.compile(r"^[ \t]*(`{3,}|:{3,})\{toctree\}") 

56 

57# Toctree entry with explicit title: 'Title <page>'. 

58TITLED_ENTRY = re.compile(r"^.*<([^<>]+)>$") 

59 

60# Source suffixes Sphinx removes from toctree entries. 

61SOURCE_SUFFIXES = (".rst", ".md") 

62 

63# Classes ********************************************************************** 

64 

65# Functions ******************************************************************** 

66 

67 

68def replace_placeholders(cfg: Config, text: str, page_file: Path) -> str: 

69 # lobster-trace: SwRequirements.sw_req_html_customization 

70 # lobster-trace: SwRequirements.sw_req_page_placeholders 

71 """Replace the placeholders of a project owned page. 

72 

73 The page names of documents and the project root are relative to the page, so the same 

74 file works in pages at different depths of the Sphinx folder. Unknown document ids are 

75 left unchanged, the configuration check reports them. 

76 

77 {documents} leaves out the documents that a toctree of a project page lists explicitly, 

78 by {page:<id>} or by page name, so a page can list a document in a toctree of its own, 

79 e.g. the license in a separate section, without listing it twice. 

80 

81 Args: 

82 cfg (Config): Project configuration. 

83 text (str): Page content with placeholders. 

84 page_file (Path): The page in the Sphinx source folder. 

85 

86 Returns: 

87 str: The content with replaced placeholders. 

88 """ 

89 page_dir = page_file.parent 

90 pages = {doc["id"]: _relative_page(cfg, cfg.page_name(doc), page_dir) for doc in cfg.documents} 

91 

92 if DOCUMENTS_PLACEHOLDER.search(text): 

93 explicit = _toctree_entries_of_project_pages(cfg, with_documents=False) 

94 listed = {entry for _, entry in explicit} 

95 unlisted = [pages[doc["id"]] for doc in cfg.documents if cfg.page_name(doc) not in listed] 

96 

97 def documents(match: re.Match) -> str: 

98 indent, line_end = match.group(1), match.group(2) 

99 return "\n".join(f"{indent}{page}{line_end}" for page in unlisted) 

100 

101 text = DOCUMENTS_PLACEHOLDER.sub(documents, text) 

102 

103 text = PAGE_PLACEHOLDER.sub(lambda match: pages.get(match.group(1), match.group(0)), text) 

104 return text.replace(PROJECT_ROOT_PLACEHOLDER, Path(os.path.relpath(cfg.root, page_dir)).as_posix()) 

105 

106 

107def _relative_page(cfg: Config, page: str, page_dir: Path) -> str: 

108 # lobster-trace: SwRequirements.sw_req_page_placeholders 

109 """Get the name of a page relative to the folder of the page referring to it. 

110 

111 Args: 

112 cfg (Config): Project configuration. 

113 page (str): Page name relative to the Sphinx source folder. 

114 page_dir (Path): Folder of the referring page in the Sphinx source folder. 

115 

116 Returns: 

117 str: The relative page name, as used in toctree entries and :doc: references. 

118 """ 

119 return Path(os.path.relpath(cfg.sphinx_dir / page, page_dir)).as_posix() 

120 

121 

122def toctree_entries(text: str, markdown: bool = False) -> list[str]: 

123 # lobster-trace: SwRequirements.sw_req_toctree_check 

124 """Get the page names listed in the toctrees of a page. 

125 

126 Entries with explicit title ('Title <page>') give their page, a leading '/' and a source 

127 suffix are removed. 'self', URLs and glob patterns are no page names and are skipped. 

128 

129 Args: 

130 text (str): Content of a reStructuredText or Markdown (MyST) page. 

131 markdown (bool): The page is Markdown, with MyST toctree directives in code fences. 

132 

133 Returns: 

134 list[str]: The page names in the order of the page. 

135 """ 

136 raw_entries = _md_toctree_lines(text) if markdown else _rst_toctree_lines(text) 

137 entries = [] 

138 for entry in raw_entries: 

139 match = TITLED_ENTRY.match(entry) 

140 page = match.group(1).strip() if match else entry 

141 page = page.lstrip("/").removeprefix("./") 

142 for suffix in SOURCE_SUFFIXES: 

143 page = page.removesuffix(suffix) 

144 if page != "self" and "://" not in page and not any(char in page for char in "*?["): 

145 entries.append(page) 

146 return entries 

147 

148 

149def _rst_toctree_lines(text: str) -> list[str]: 

150 # lobster-trace: SwRequirements.sw_req_toctree_check 

151 """Get the content lines of the reStructuredText toctree directives, without their options. 

152 

153 Args: 

154 text (str): Content of a reStructuredText page. 

155 

156 Returns: 

157 list[str]: The stripped entry lines. 

158 """ 

159 lines: list[str] = [] 

160 directive_indent: int | None = None 

161 for line in text.splitlines(): 

162 stripped = line.strip() 

163 indent = len(line) - len(line.lstrip()) 

164 # A non-empty line not indented deeper than the directive ends its content. 

165 if directive_indent is not None and stripped and indent <= directive_indent: 

166 directive_indent = None 

167 if directive_indent is not None: 

168 if stripped and not stripped.startswith(":"): 

169 lines.append(stripped) 

170 else: 

171 match = RST_TOCTREE.match(line) 

172 if match: 

173 directive_indent = len(match.group(1).expandtabs()) 

174 return lines 

175 

176 

177def _md_toctree_lines(text: str) -> list[str]: 

178 # lobster-trace: SwRequirements.sw_req_toctree_check 

179 """Get the content lines of the MyST toctree directives of a Markdown page, without their options. 

180 

181 Args: 

182 text (str): Content of a Markdown page. 

183 

184 Returns: 

185 list[str]: The stripped entry lines. 

186 """ 

187 lines: list[str] = [] 

188 fence: str | None = None 

189 in_yaml_options = False 

190 for line in text.splitlines(): 

191 stripped = line.strip() 

192 if fence is None: 

193 match = MD_TOCTREE.match(line) 

194 fence = match.group(1) if match else None 

195 elif stripped.startswith(fence) and stripped.strip(fence[0]) == "": 

196 fence = None 

197 elif stripped == "---": 

198 in_yaml_options = not in_yaml_options 

199 elif stripped and not in_yaml_options and not stripped.startswith(":"): 

200 lines.append(stripped) 

201 return lines 

202 

203 

204def check_toctrees(cfg: Config) -> list[str]: 

205 # lobster-trace: SwRequirements.sw_req_toctree_check 

206 """Check the tables of contents of a project start page against the page names of the documents. 

207 

208 Without html.index, trlcdoc generates the table of contents itself and there is nothing to 

209 check. Otherwise the toctrees of html.index and of the rst and markdown documents are read, 

210 after replacing their placeholders, and checked for 

211 

212 - entries which are no page, with a hint if a document has a similar page name 

213 - documents whose page is in no toctree 

214 

215 Entries in folders that belong to no document, e.g. pages of Sphinx extensions like 

216 sphinx-autoapi, cannot be checked and are accepted. 

217 

218 Args: 

219 cfg (Config): Project configuration. 

220 

221 Returns: 

222 list[str]: Findings, empty if the tables of contents list every document correctly. 

223 """ 

224 findings: list[str] = [] 

225 if "index" in cfg.html: 

226 pages = {cfg.page_name(doc): doc for doc in cfg.documents} 

227 listed: set[str] = set() 

228 for where, entry in _toctree_entries_of_project_pages(cfg): 

229 finding, page = _check_entry(cfg, pages, where, entry) 

230 # A wrong entry naming a document lists it, its finding already tells the fix. 

231 listed.add(page) 

232 if finding is not None: 

233 findings.append(finding) 

234 findings.extend( 

235 f"html.index: document '{doc['id']}' (page '{page}') is not in any toctree. " 

236 f"Add {{page:{doc['id']}}} to a toctree." 

237 for page, doc in pages.items() 

238 if page not in listed 

239 ) 

240 return findings 

241 

242 

243def _toctree_entries_of_project_pages(cfg: Config, with_documents: bool = True) -> list[tuple[str, str]]: 

244 # lobster-trace: SwRequirements.sw_req_toctree_check 

245 # lobster-trace: SwRequirements.sw_req_page_placeholders 

246 """Get the toctree entries of html.index and the rst and markdown documents. 

247 

248 The project pages are placed at the top of the Sphinx folder, so their entries are page 

249 names relative to the Sphinx folder. 

250 

251 Args: 

252 cfg (Config): Project configuration. 

253 with_documents (bool): Include the entries of {documents}, False gives only the 

254 explicitly listed entries. 

255 

256 Returns: 

257 list[tuple[str, str]]: Configuration location of the page and the entry. 

258 """ 

259 project_pages = [] 

260 if "index" in cfg.html: 

261 project_pages.append(("html.index", cfg.path(cfg.html["index"]), "index.rst", True)) 

262 project_pages.extend( 

263 ( 

264 f"documents[{doc['id']}]", 

265 cfg.path(doc["source"]), 

266 doc["id"] + (".md" if doc["type"] == "markdown" else ".rst"), 

267 doc.get("placeholders", True), 

268 ) 

269 for doc in cfg.documents 

270 if doc["type"] in ("rst", "markdown") 

271 ) 

272 result = [] 

273 for where, source, name, placeholders in project_pages: 

274 if source.is_file(): 

275 text = source.read_text(encoding="utf-8") 

276 if not with_documents: 

277 text = DOCUMENTS_PLACEHOLDER.sub("", text) 

278 if placeholders: 

279 text = replace_placeholders(cfg, text, cfg.sphinx_dir / name) 

280 result.extend((where, entry) for entry in toctree_entries(text, name.endswith(".md"))) 

281 return result 

282 

283 

284def _check_entry(cfg: Config, pages: dict[str, dict[str, Any]], where: str, entry: str) -> tuple[str | None, str]: 

285 # lobster-trace: SwRequirements.sw_req_toctree_check 

286 """Check one toctree entry against the page names of the documents. 

287 

288 Args: 

289 cfg (Config): Project configuration. 

290 pages (dict[str, dict[str, Any]]): Document per page name. 

291 where (str): Configuration location of the page with the toctree. 

292 entry (str): The toctree entry, a page name relative to the Sphinx folder. 

293 

294 Returns: 

295 tuple[str | None, str]: A finding, or None if the entry is a page of a document or cannot be 

296 checked, and the page the entry means: the page of a document with a similar name, else the entry. 

297 """ 

298 folder = entry.split("/", 1)[0] 

299 documents = {doc["id"]: doc for doc in cfg.documents} 

300 similar = [page for page in (f"{entry}/index", entry.removesuffix("/index")) if page in pages] 

301 finding: str | None = None 

302 page = entry 

303 if entry in pages: 

304 finding = None 

305 elif similar: 

306 page = similar[0] 

307 doc = pages[page] 

308 finding = ( 

309 f"{where}: toctree entry '{entry}' is no page. Document '{doc['id']}' is the page " 

310 f"'{similar[0]}' ({_page_reason(cfg, doc)}). Write {{page:{doc['id']}}} to use its page name." 

311 ) 

312 elif "/" not in entry or (folder in documents and not _has_subpages(cfg, documents[folder])): 

313 finding = f"{where}: toctree entry '{entry}' is no page of a document." 

314 return finding, page 

315 

316 

317def _has_subpages(cfg: Config, doc: dict[str, Any]) -> bool: 

318 # lobster-trace: SwRequirements.sw_req_toctree_check 

319 """Check whether the folder of a document contains further pages besides its index page. 

320 

321 Args: 

322 cfg (Config): Project configuration. 

323 doc (dict[str, Any]): Document configuration. 

324 

325 Returns: 

326 bool: True for the reStructuredText tracing report, which has a page per trace level. 

327 """ 

328 return doc["type"] == "trace_report" and cfg.trace_report_format == "rst" 

329 

330 

331def _page_reason(cfg: Config, doc: dict[str, Any]) -> str: 

332 # lobster-trace: SwRequirements.sw_req_toctree_check 

333 """Explain the page name of a document by its type. 

334 

335 Args: 

336 cfg (Config): Project configuration. 

337 doc (dict[str, Any]): Document configuration. 

338 

339 Returns: 

340 str: The settings that determine the page name. 

341 """ 

342 reason = f"type {doc['type']}" 

343 if doc["type"] == "trace_report": 

344 reason += f", trace.report: {cfg.trace_report_format}" 

345 return reason 

346 

347 

348# Main *************************************************************************