From 26e475638a94e137baca7ef5c601322585630c99 Mon Sep 17 00:00:00 2001
From: Antoine Lambert <anlambert@softwareheritage.org>
Date: Wed, 15 Feb 2023 15:11:44 +0100
Subject: [PATCH] sphinx/conf.py: Include apidoc in toc of swh package doc
 index

When building the full swh documentation, add a sphinx transform step
to include a swh package apidoc in the toc of its documentation index
page.

Fix #4736
---
 swh/docs/sphinx/conf.py | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)

diff --git a/swh/docs/sphinx/conf.py b/swh/docs/sphinx/conf.py
index a6e34e5d..17ca69b2 100755
--- a/swh/docs/sphinx/conf.py
+++ b/swh/docs/sphinx/conf.py
@@ -5,9 +5,12 @@
 
 import logging
 import os
+import re
 from typing import Dict
 
+from sphinx import addnodes
 from sphinx.ext import autodoc
+from sphinx.transforms import SphinxTransform
 
 from swh.docs.django_settings import force_django_settings
 
@@ -337,3 +340,33 @@ def setup(app):
 
             # insert a custom filter in the warning log handler of sphinx
             logger.handlers[1].filters.insert(0, HttpDomainRefWarningFilter())
+
+    else:
+
+        class SwhPackageTocTreeAddApidoc(SphinxTransform):
+            # Post processing. Deadline to modify text and referencing.
+            default_priority = 700
+
+            def apply(self, **kwargs):
+                # Act only on indexes of swh packages
+                match = re.match(r"^devel/(swh-[^/]+)/index$", self.env.docname)
+                if not match:
+                    return
+
+                # Compute path to the module index generated by apidoc
+                swh_package = match.group(1).replace("-", ".")
+                swh_package_apidoc = f"devel/apidoc/{swh_package}"
+                swh_package_apidoc_file = (
+                    os.path.join(self.env.srcdir, swh_package_apidoc) + ".rst"
+                )
+
+                # If the path exists, add it to the toc
+                if not os.path.exists(swh_package_apidoc_file):
+                    return
+                nodes = list(self.document.findall(addnodes.toctree))
+                if nodes:
+                    main_toc = nodes[0]
+                    main_toc["entries"].append((None, swh_package_apidoc))
+                    main_toc["includefiles"].append(swh_package_apidoc)
+
+        app.add_transform(SwhPackageTocTreeAddApidoc)
-- 
GitLab