Coverage for trlcdoc/config.py: 98%

258 statements  

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

1"""Loading, validation and path resolution of the trlcdoc project configuration.""" 

2 

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

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

5# 

6# This file is part of trlcdoc program. 

7# 

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

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

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

11# 

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

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

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

15# 

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

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

18 

19# Imports ********************************************************************** 

20 

21import json 

22import re 

23from pathlib import Path 

24from typing import Any 

25 

26import jsonschema 

27import yaml 

28 

29from .util import TrlcdocError 

30 

31# Variables ******************************************************************** 

32 

33PACKAGE_DIR = Path(__file__).resolve().parent 

34SCHEMA_FILE = PACKAGE_DIR / "schema" / "trlcdoc.schema.json" 

35BUILTIN_DIR = PACKAGE_DIR / "converters" 

36BUILTIN_PREFIX = "builtin:" 

37TESTS_COVERAGE = "tests:coverage" 

38 

39# Document types whose content are TRLC records. 

40TRLC_DOCUMENT_TYPES = ("trlc", "test_results") 

41 

42# Placeholder in project owned pages for the page name of a document, {page:<id>}. 

43# Everything up to the closing brace is taken as id, so a misspelled id is reported. 

44PAGE_PLACEHOLDER = re.compile(r"\{page:([^}]*)\}") 

45 

46# Path of an entry in the configuration, e.g. ("documents", 1, "include"). 

47ConfigPath = tuple[str | int, ...] 

48 

49# Configuration error: path of the entry and message. 

50ConfigError = tuple[ConfigPath, str] 

51 

52# Classes ********************************************************************** 

53 

54 

55class Config: 

56 """Validated project configuration with resolved paths.""" 

57 

58 def __init__(self, data: dict[str, Any], config_file: Path, output: Path | None = None) -> None: 

59 # lobster-trace: SwRequirements.sw_req_project_settings 

60 # lobster-trace: SwRequirements.sw_req_documents 

61 # lobster-trace: SwRequirements.sw_req_output_option 

62 """Construct the configuration. 

63 

64 Args: 

65 data (dict[str, Any]): Schema validated configuration data. 

66 config_file (Path): The configuration file. Its folder is the project root. 

67 output (Path | None): Output folder from the command line, replaces paths.output. A relative 

68 path is relative to the current folder. 

69 """ 

70 self.data = data 

71 self.config_file = config_file.resolve() 

72 self.output_option = output.resolve() if output is not None else None 

73 self.root = self.config_file.parent 

74 self.documents: list[dict[str, Any]] = data["documents"] 

75 self.tests: dict[str, Any] | None = data.get("tests") 

76 self.trace: dict[str, Any] | None = data.get("trace") 

77 self.project: dict[str, Any] = data["project"] 

78 self.html: dict[str, Any] = data.get("html", {}) 

79 self.plantuml: dict[str, Any] = data.get("plantuml", {}) 

80 

81 # Paths ******************************************************************** 

82 

83 def path(self, value: str) -> Path: 

84 # lobster-trace: SwRequirements.sw_req_config_file 

85 """Resolve a configured path against the project root. 

86 

87 Args: 

88 value (str): Absolute path or path relative to the project root. 

89 

90 Returns: 

91 Path: The absolute path. 

92 """ 

93 return (self.root / value).resolve() 

94 

95 @property 

96 def output(self) -> Path: 

97 # lobster-trace: SwRequirements.sw_req_output_folder 

98 # lobster-trace: SwRequirements.sw_req_output_option 

99 """Folder for all generated files: the --output option, else paths.output.""" 

100 result = self.output_option 

101 if result is None: 

102 result = self.path(self.data["paths"].get("output", "build/trlcdoc")) 

103 return result 

104 

105 @property 

106 def trlc_model(self) -> Path: 

107 # lobster-trace: SwRequirements.sw_req_trlc_conversion 

108 """Folder with the TRLC model files.""" 

109 return self.path(self.data["paths"]["trlc_model"]) 

110 

111 @property 

112 def plantuml_dir(self) -> Path: 

113 # lobster-trace: SwRequirements.sw_req_plantuml 

114 # lobster-trace: SwRequirements.sw_req_output_folder 

115 """Folder for the downloaded PlantUML jar and the log of the picoweb server.""" 

116 return self.output / "plantuml" 

117 

118 def convert_dir(self, fmt: str, doc_id: str) -> Path: 

119 # lobster-trace: SwRequirements.sw_req_trlc_conversion 

120 # lobster-trace: SwRequirements.sw_req_output_folder 

121 """Output folder of a converted document. 

122 

123 Args: 

124 fmt (str): Output format, rst or markdown. 

125 doc_id (str): Document id. 

126 

127 Returns: 

128 Path: The output folder. 

129 """ 

130 return self.output / "convert" / fmt / doc_id 

131 

132 @property 

133 def tests_dir(self) -> Path: 

134 # lobster-trace: SwRequirements.sw_req_test_run 

135 # lobster-trace: SwRequirements.sw_req_output_folder 

136 """Output folder of the tests step.""" 

137 return self.output / "tests" 

138 

139 @property 

140 def junit_file(self) -> Path: 

141 # lobster-trace: SwRequirements.sw_req_test_run 

142 """JUnit XML file with the test results.""" 

143 result = self.tests_dir / "junit.xml" 

144 if self.tests is not None and self.tests["runner"] == "command": 

145 result = self.path(self.tests["junit"]) 

146 return result 

147 

148 @property 

149 def coverage_dir(self) -> Path: 

150 # lobster-trace: SwRequirements.sw_req_test_run 

151 """HTML coverage report folder.""" 

152 result = self.tests_dir / "coverage" 

153 if self.tests is not None and "coverage" in self.tests: 

154 result = self.path(self.tests["coverage"]) 

155 return result 

156 

157 @property 

158 def test_results_dir(self) -> Path: 

159 # lobster-trace: SwRequirements.sw_req_test_results 

160 """Folder with the TRLC test result records generated from the JUnit XML.""" 

161 return self.tests_dir / "results" 

162 

163 @property 

164 def trace_dir(self) -> Path: 

165 # lobster-trace: SwRequirements.sw_req_trace_report 

166 # lobster-trace: SwRequirements.sw_req_output_folder 

167 """Output folder of the trace step.""" 

168 return self.output / "trace" 

169 

170 @property 

171 def trace_report_html(self) -> Path: 

172 # lobster-trace: SwRequirements.sw_req_trace_report 

173 """The HTML tracing report.""" 

174 return self.trace_dir / "tracing_report.html" 

175 

176 @property 

177 def trace_report_rst(self) -> Path: 

178 # lobster-trace: SwRequirements.sw_req_trace_report_rst 

179 """Folder of the reStructuredText tracing report, one page per level.""" 

180 return self.trace_dir / "rst" 

181 

182 @property 

183 def trace_report_format(self) -> str: 

184 # lobster-trace: SwRequirements.sw_req_trace_report_rst 

185 """Format of the tracing report: 'html' (default) or 'rst'.""" 

186 return (self.trace or {}).get("report", "html") 

187 

188 @property 

189 def sphinx_dir(self) -> Path: 

190 # lobster-trace: SwRequirements.sw_req_html_site 

191 # lobster-trace: SwRequirements.sw_req_output_folder 

192 """Generated Sphinx source folder.""" 

193 return self.output / "sphinx" 

194 

195 @property 

196 def html_dir(self) -> Path: 

197 # lobster-trace: SwRequirements.sw_req_html_site 

198 # lobster-trace: SwRequirements.sw_req_output_folder 

199 """Generated HTML site.""" 

200 return self.output / "html" 

201 

202 # Documents **************************************************************** 

203 

204 def document(self, doc_id: str) -> dict[str, Any]: 

205 # lobster-trace: SwRequirements.sw_req_documents 

206 """Get a document by its id. 

207 

208 Args: 

209 doc_id (str): Document id. 

210 

211 Returns: 

212 dict[str, Any]: The document configuration. 

213 """ 

214 return next(doc for doc in self.documents if doc["id"] == doc_id) 

215 

216 def page_name(self, doc: dict[str, Any]) -> str: 

217 # lobster-trace: SwRequirements.sw_req_documents 

218 # lobster-trace: SwRequirements.sw_req_page_placeholders 

219 """Get the Sphinx page name of a document, the name used in a table of contents. 

220 

221 Documents with several pages are a folder with an index page: TRLC documents and the 

222 reStructuredText tracing report. All other documents are a single page. 

223 

224 Args: 

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

226 

227 Returns: 

228 str: '<id>/index' for a folder of pages, otherwise '<id>'. 

229 """ 

230 result = doc["id"] 

231 if doc["type"] in TRLC_DOCUMENT_TYPES or (doc["type"] == "trace_report" and self.trace_report_format == "rst"): 

232 result = f"{doc['id']}/index" 

233 return result 

234 

235 def placeholder_files(self) -> list[tuple[str, ConfigPath, Path]]: 

236 # lobster-trace: SwRequirements.sw_req_html_customization 

237 # lobster-trace: SwRequirements.sw_req_page_placeholders 

238 """Get the project owned files whose placeholders are replaced. 

239 

240 Returns: 

241 list[tuple[str, ConfigPath, Path]]: Configuration location, its entry path and the path of html.index, 

242 html.page_header and the rst and markdown documents, except documents with 'placeholders: false'. 

243 """ 

244 result: list[tuple[str, ConfigPath, Path]] = [ 

245 (f"html.{key}", ("html", key), self.path(self.html[key])) 

246 for key in ("index", "page_header") 

247 if key in self.html 

248 ] 

249 result.extend( 

250 (f"documents[{doc['id']}]", ("documents", index, "source"), self.path(doc["source"])) 

251 for index, doc in enumerate(self.documents) 

252 if doc["type"] in ("rst", "markdown") and doc.get("placeholders", True) 

253 ) 

254 return result 

255 

256 def trlc_sources(self, doc: dict[str, Any]) -> list[Path]: 

257 # lobster-trace: SwRequirements.sw_req_trlc_conversion 

258 """Get the TRLC source folders of a TRLC document. 

259 

260 Args: 

261 doc (dict[str, Any]): Document of type trlc or test_results. 

262 

263 Returns: 

264 list[Path]: The source folders. 

265 """ 

266 result = [self.test_results_dir] 

267 if doc["type"] == "trlc": 

268 result = [self.path(doc["source"])] 

269 return result 

270 

271 def included_documents(self, doc: dict[str, Any]) -> list[dict[str, Any]]: 

272 # lobster-trace: SwRequirements.sw_req_trlc_conversion 

273 """Get all documents included by a document, transitively. 

274 

275 Args: 

276 doc (dict[str, Any]): The including document. 

277 

278 Returns: 

279 list[dict[str, Any]]: Included documents, without the document itself. 

280 """ 

281 result: list[dict[str, Any]] = [] 

282 pending = list(doc.get("include", [])) 

283 while pending: 

284 doc_id = pending.pop(0) 

285 if doc_id != doc["id"] and all(inc["id"] != doc_id for inc in result): 

286 included = self.document(doc_id) 

287 result.append(included) 

288 pending.extend(included.get("include", [])) 

289 return result 

290 

291 def included_sources(self, doc: dict[str, Any]) -> list[Path]: 

292 # lobster-trace: SwRequirements.sw_req_trlc_conversion 

293 """Get the TRLC source folders of all documents included by a document. 

294 

295 Args: 

296 doc (dict[str, Any]): The including document. 

297 

298 Returns: 

299 list[Path]: The source folders. 

300 """ 

301 result: list[Path] = [] 

302 for included in self.included_documents(doc): 

303 result.extend(self.trlc_sources(included)) 

304 return result 

305 

306 def file_reference(self, value: str) -> Path: 

307 # lobster-trace: SwRequirements.sw_req_trlc_conversion 

308 # lobster-trace: SwRequirements.sw_req_builtin_converters 

309 """Resolve a converter, translation or render configuration file reference. 

310 

311 Args: 

312 value (str): 'builtin:<file>' or a path relative to the project root. 

313 

314 Returns: 

315 Path: The absolute file path. 

316 """ 

317 result = self.path(value) 

318 if value.startswith(BUILTIN_PREFIX): 

319 result = BUILTIN_DIR / value[len(BUILTIN_PREFIX) :] 

320 return result 

321 

322 def html_source(self, doc: dict[str, Any]) -> Path: 

323 # lobster-trace: SwRequirements.sw_req_document_types 

324 """Resolve the HTML folder of a document of type html or command. 

325 

326 Args: 

327 doc (dict[str, Any]): Document of type html or command. 

328 

329 Returns: 

330 Path: The HTML folder. 

331 """ 

332 result = self.coverage_dir 

333 if doc["type"] == "command": 

334 result = self.path(doc["output"]) 

335 elif doc["source"] != TESTS_COVERAGE: 

336 result = self.path(doc["source"]) 

337 return result 

338 

339 # Project ****************************************************************** 

340 

341 @property 

342 def repository(self) -> str: 

343 # lobster-trace: SwRequirements.sw_req_project_settings 

344 # lobster-trace: SwRequirements.sw_req_trace_report 

345 """Configured repository URL or 'auto'.""" 

346 return self.project.get("repository", "auto") 

347 

348 

349# Functions ******************************************************************** 

350 

351 

352def _check_references(cfg: Config) -> list[ConfigError]: 

353 # lobster-trace: SwRequirements.sw_req_config_validation 

354 # lobster-trace: SwRequirements.sw_req_output_folder 

355 """Check the cross references, which the JSON schema cannot express. 

356 

357 Args: 

358 cfg (Config): Schema validated configuration. 

359 

360 Returns: 

361 list[ConfigError]: Errors, empty if all references are valid. 

362 """ 

363 errors: list[ConfigError] = [] 

364 doc_ids = [doc["id"] for doc in cfg.documents] 

365 doc_types = {doc["id"]: doc["type"] for doc in cfg.documents} 

366 

367 # A repeated id is reported at its second occurrence. 

368 for index, doc_id in enumerate(doc_ids): 

369 if doc_ids[:index].count(doc_id) == 1: 

370 errors.append((("documents", index, "id"), f"documents: id '{doc_id}' is used more than once.")) 

371 

372 for index, doc in enumerate(cfg.documents): 

373 errors.extend(_check_document(cfg, ("documents", index), doc, doc_types)) 

374 

375 if cfg.trace is not None: 

376 errors.extend(_check_levels(cfg, cfg.trace["levels"], doc_types)) 

377 

378 for key in ("logo", "favicon"): 

379 if cfg.project.get(key) and not cfg.path(cfg.project[key]).is_file(): 

380 errors.append((("project", key), f"project.{key}: file '{cfg.project[key]}' not found.")) 

381 

382 for key in ("conf", "index", "page_header"): 

383 if key in cfg.html and not cfg.path(cfg.html[key]).is_file(): 

384 errors.append((("html", key), f"html.{key}: file '{cfg.html[key]}' not found.")) 

385 

386 errors.extend(_check_page_placeholders(cfg, doc_ids)) 

387 

388 # With the --output option, paths.output is not used. load_config() checks the option instead. 

389 if cfg.output_option is None: 

390 for message in _check_output(cfg): 

391 errors.append((("paths", "output"), f"paths.output: {message}")) 

392 

393 return errors 

394 

395 

396def _check_output(cfg: Config) -> list[str]: 

397 # lobster-trace: SwRequirements.sw_req_output_folder 

398 # lobster-trace: SwRequirements.sw_req_output_option 

399 """Check that the output folder is at a safe location. 

400 

401 Args: 

402 cfg (Config): Schema validated configuration. 

403 

404 Returns: 

405 list[str]: Errors without the name of the setting, empty if the location is safe. 

406 """ 

407 errors: list[str] = [] 

408 if cfg.output.is_relative_to(PACKAGE_DIR): 

409 errors.append("must not be inside the trlcdoc package folder.") 

410 # The clean step removes the output folder, so it must never contain the project. 

411 if cfg.root.is_relative_to(cfg.output): 

412 errors.append("must not be the project root or one of its parents.") 

413 return errors 

414 

415 

416def _check_page_placeholders(cfg: Config, doc_ids: list[str]) -> list[ConfigError]: 

417 # lobster-trace: SwRequirements.sw_req_config_validation 

418 # lobster-trace: SwRequirements.sw_req_page_placeholders 

419 """Check that the {page:<id>} placeholders of the project owned files name configured documents. 

420 

421 Args: 

422 cfg (Config): Schema validated configuration. 

423 doc_ids (list[str]): Ids of the configured documents. 

424 

425 Returns: 

426 list[ConfigError]: Errors, empty if all placeholders name a document. 

427 """ 

428 errors: list[ConfigError] = [] 

429 for where, entry, file in cfg.placeholder_files(): 

430 if file.is_file(): 

431 ids = PAGE_PLACEHOLDER.findall(file.read_text(encoding="utf-8")) 

432 errors.extend( 

433 (entry, f"{where}: placeholder '{{page:{doc_id}}}' names no document.") 

434 for doc_id in sorted(set(ids)) 

435 if doc_id not in doc_ids 

436 ) 

437 return errors 

438 

439 

440def _check_document( 

441 cfg: Config, entry: ConfigPath, doc: dict[str, Any], doc_types: dict[str, str] 

442) -> list[ConfigError]: 

443 # lobster-trace: SwRequirements.sw_req_config_validation 

444 """Check the references of one document. 

445 

446 Args: 

447 cfg (Config): Schema validated configuration. 

448 entry (ConfigPath): Path of the document in the configuration. 

449 doc (dict[str, Any]): The document. 

450 doc_types (dict[str, str]): Document type per document id. 

451 

452 Returns: 

453 list[ConfigError]: Errors, empty if all references are valid. 

454 """ 

455 errors: list[ConfigError] = [] 

456 where = f"documents[{doc['id']}]" 

457 

458 for index, inc in enumerate(doc.get("include", [])): 

459 if doc_types.get(inc) not in TRLC_DOCUMENT_TYPES: 

460 errors.append( 

461 ((*entry, "include", index), f"{where}.include: '{inc}' is no document of type trlc or test_results.") 

462 ) 

463 

464 options = doc.get("pytrlcconverter", {}) 

465 files = {("converter", fmt): value for fmt, value in options.get("converter", {}).items()} 

466 files.update({(key,): options[key] for key in ("translation", "render_cfg") if key in options}) 

467 for keys, value in files.items(): 

468 if not cfg.file_reference(value).is_file(): 

469 errors.append( 

470 ( 

471 (*entry, "pytrlcconverter", *keys), 

472 f"{where}.pytrlcconverter.{'.'.join(keys)}: file '{value}' not found.", 

473 ) 

474 ) 

475 

476 needs_tests = doc["type"] == "test_results" or doc.get("source") == TESTS_COVERAGE 

477 if needs_tests and cfg.tests is None: 

478 errors.append((entry, f"{where}: needs a 'tests' section.")) 

479 if doc["type"] == "trace_report" and cfg.trace is None: 

480 errors.append((entry, f"{where}: type trace_report needs a 'trace' section.")) 

481 return errors 

482 

483 

484def _check_levels(cfg: Config, levels: list[dict[str, Any]], doc_types: dict[str, str]) -> list[ConfigError]: 

485 # lobster-trace: SwRequirements.sw_req_config_validation 

486 # lobster-trace: SwRequirements.sw_req_trace_levels 

487 # lobster-trace: SwRequirements.sw_req_trace_doxygen 

488 """Check the trace level references. 

489 

490 Args: 

491 cfg (Config): Schema validated configuration. 

492 levels (list[dict[str, Any]]): Configured trace levels. 

493 doc_types (dict[str, str]): Document type per document id. 

494 

495 Returns: 

496 list[ConfigError]: Errors, empty if all references are valid. 

497 """ 

498 errors: list[ConfigError] = [] 

499 names = [level["name"] for level in levels] 

500 

501 # A repeated name is reported at its second occurrence. 

502 for index, name in enumerate(names): 

503 if names[:index].count(name) == 1: 

504 errors.append((("trace", "levels", index, "name"), f"trace.levels: name '{name}' is used more than once.")) 

505 

506 for index, level in enumerate(levels): 

507 entry: ConfigPath = ("trace", "levels", index) 

508 where = f"trace.levels[{level['name']}]" 

509 if "document" in level and doc_types.get(level["document"]) not in TRLC_DOCUMENT_TYPES: 

510 errors.append( 

511 ( 

512 (*entry, "document"), 

513 f"{where}.document: '{level['document']}' is no document of type trlc or test_results.", 

514 ) 

515 ) 

516 if "doxyfile" in level and not cfg.path(level["doxyfile"]).is_file(): 

517 errors.append(((*entry, "doxyfile"), f"{where}.doxyfile: file '{level['doxyfile']}' not found.")) 

518 for key in ("trace_to", "requires"): 

519 for target_index, target in enumerate(level.get(key, [])): 

520 if target not in names: 

521 errors.append(((*entry, key, target_index), f"{where}.{key}: level '{target}' is not defined.")) 

522 return errors 

523 

524 

525def _line_map(text: str) -> dict[ConfigPath, int]: 

526 # lobster-trace: SwRequirements.sw_req_config_validation 

527 """Map the path of every configuration entry to its line in the file. 

528 

529 Args: 

530 text (str): Content of the configuration file, valid YAML. 

531 

532 Returns: 

533 dict[ConfigPath, int]: Line number, starting at 1, per entry path. A mapping key gives the line of the 

534 key, a list item the line of the item. The root is line 1. 

535 """ 

536 lines: dict[ConfigPath, int] = {(): 1} 

537 

538 def walk(node: yaml.Node, path: ConfigPath, parents: tuple[int, ...]) -> None: 

539 # Aliases may refer to an enclosing node, which would recurse forever. 

540 if id(node) in parents: 

541 return 

542 parents = (*parents, id(node)) 

543 children: list[tuple[str | int, yaml.Node, yaml.Node]] = [] 

544 if isinstance(node, yaml.MappingNode): 

545 children = [(key.value, key, value) for key, value in node.value if isinstance(key, yaml.ScalarNode)] 

546 elif isinstance(node, yaml.SequenceNode): 

547 children = [(index, item, item) for index, item in enumerate(node.value)] 

548 for name, position, value in children: 

549 lines.setdefault((*path, name), position.start_mark.line + 1) 

550 walk(value, (*path, name), parents) 

551 

552 root = yaml.compose(text, Loader=yaml.SafeLoader) 

553 if root is not None: 

554 walk(root, (), ()) 

555 return lines 

556 

557 

558def _schema_error_path(err: jsonschema.ValidationError) -> ConfigPath: 

559 # lobster-trace: SwRequirements.sw_req_config_validation 

560 """Get the path of the entry a schema error is about. 

561 

562 Args: 

563 err (jsonschema.ValidationError): The schema error. 

564 

565 Returns: 

566 ConfigPath: The path of the value, or of the key for a key that is not allowed. 

567 """ 

568 path: ConfigPath = tuple(err.absolute_path) 

569 if "propertyNames" in err.schema_path: 

570 path = (*path, err.instance) 

571 elif err.validator == "additionalProperties" and isinstance(err.instance, dict): 

572 allowed = err.schema.get("properties", {}) 

573 path = (*path, *[key for key in err.instance if key not in allowed][:1]) 

574 return path 

575 

576 

577def _format_errors(config_file: Path, text: str, errors: list[ConfigError]) -> str: 

578 # lobster-trace: SwRequirements.sw_req_config_validation 

579 """Format configuration errors with file and line of their entry, ordered by line. 

580 

581 Args: 

582 config_file (Path): The configuration file. 

583 text (str): Content of the configuration file, valid YAML. 

584 errors (list[ConfigError]): The errors. 

585 

586 Returns: 

587 str: One line '<file>:<line>: <message>' per error. An entry that is not in the file, e.g. a 

588 missing key, gets the line of its closest parent. 

589 """ 

590 lines = _line_map(text) 

591 

592 def line(path: ConfigPath) -> int: 

593 while path not in lines: 

594 path = path[:-1] 

595 return lines[path] 

596 

597 numbered = sorted(((line(path), message) for path, message in errors), key=lambda error: error[0]) 

598 return "\n ".join(f"{config_file}:{number}: {message}" for number, message in numbered) 

599 

600 

601def load_config(config_file: Path, output: Path | None = None) -> Config: 

602 # lobster-trace: SwRequirements.sw_req_config_file 

603 # lobster-trace: SwRequirements.sw_req_config_validation 

604 # lobster-trace: SwRequirements.sw_req_output_option 

605 """Load and validate the project configuration. 

606 

607 Args: 

608 config_file (Path): The trlcdoc YAML configuration file. 

609 output (Path | None): Output folder from the command line, replaces paths.output. A relative 

610 path is relative to the current folder. 

611 

612 Returns: 

613 Config: The validated configuration. 

614 

615 Raises: 

616 TrlcdocError: If the file is missing or invalid. 

617 """ 

618 if not config_file.is_file(): 

619 raise TrlcdocError(f"Configuration file {config_file} not found.") 

620 

621 text = config_file.read_text(encoding="utf-8") 

622 try: 

623 data = yaml.safe_load(text) 

624 except yaml.YAMLError as error: 

625 raise TrlcdocError(f"{config_file} is no valid YAML: {error}") from error 

626 

627 with open(SCHEMA_FILE, encoding="utf-8") as file: 

628 schema = json.load(file) 

629 

630 validator = jsonschema.Draft202012Validator(schema) 

631 schema_errors: list[ConfigError] = [ 

632 (_schema_error_path(err), f"{'/'.join(str(p) for p in err.absolute_path) or '<root>'}: {err.message}") 

633 for err in sorted(validator.iter_errors(data), key=lambda err: list(err.absolute_path)) 

634 ] 

635 if schema_errors: 

636 raise TrlcdocError( 

637 f"{config_file} does not match the schema:\n " + _format_errors(config_file, text, schema_errors) 

638 ) 

639 

640 cfg = Config(data, config_file, output) 

641 reference_errors = _check_references(cfg) 

642 if reference_errors: 

643 raise TrlcdocError( 

644 f"{config_file} has invalid settings:\n " + _format_errors(config_file, text, reference_errors) 

645 ) 

646 

647 if cfg.output_option is not None: 

648 output_errors = _check_output(cfg) 

649 if output_errors: 

650 raise TrlcdocError(f"--output {cfg.output_option}: " + " ".join(output_errors)) 

651 

652 return cfg 

653 

654 

655def find_config(start: Path) -> Path: 

656 # lobster-trace: SwRequirements.sw_req_config_file 

657 """Find the default configuration file trlcdoc.yaml in a folder or its parents. 

658 

659 Args: 

660 start (Path): Folder to start the search in. 

661 

662 Returns: 

663 Path: The configuration file, or start/trlcdoc.yaml if none was found. 

664 """ 

665 candidates = [folder / "trlcdoc.yaml" for folder in (start, *start.parents)] 

666 return next((file for file in candidates if file.is_file()), start / "trlcdoc.yaml") 

667 

668 

669# Main *************************************************************************