From 7406efb58ea685eb4ede83952f74213ef0ce5cac Mon Sep 17 00:00:00 2001 From: Richard Levasseur Date: Sat, 17 May 2025 19:01:01 -0700 Subject: [PATCH] sphinxdocs: make bazel package xrefs work --- sphinxdocs/src/sphinx_bzl/bzl.py | 22 ++++++++++++++++--- .../sphinx_stardoc/sphinx_output_test.py | 2 ++ sphinxdocs/tests/sphinx_stardoc/xrefs.md | 5 +++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/sphinxdocs/src/sphinx_bzl/bzl.py b/sphinxdocs/src/sphinx_bzl/bzl.py index 7804e7f5e2..4468ec660c 100644 --- a/sphinxdocs/src/sphinx_bzl/bzl.py +++ b/sphinxdocs/src/sphinx_bzl/bzl.py @@ -394,7 +394,7 @@ def _make_xrefs_for_arg_attr( # This allows referencing an arg as e.g `funcname.argname` anchor_id, # This allows referencing an arg as simply `argname` - arg_name + arg_name, ], ) @@ -503,7 +503,22 @@ def run(self) -> list[docutils_nodes.Node]: self.env.ref_context["bzl:object_id_stack"] = [] self.env.ref_context["bzl:doc_id_stack"] = [] - _, _, basename = file_label.partition(":") + package_label, _, basename = file_label.partition(":") + + # Transform //foo/bar:BUILD.bazel into "bar" + # This allows referencing "bar" as itself + extra_alt_names = [] + if basename in ("BUILD.bazel", "BUILD"): + # Allow xref //foo + extra_alt_names.append(package_label) + basename = os.path.basename(package_label) + # Handle //:BUILD.bazel + if not basename: + # There isn't a convention for referring to the root package + # besides `//:`, which is already the file_label. So just + # use some obvious value + basename = "__ROOT_BAZEL_PACKAGE__" + index_description = f"File {label}" absolute_label = repo + label self.env.get_domain("bzl").add_object( @@ -527,7 +542,8 @@ def run(self) -> list[docutils_nodes.Node]: file_label, # Allow xref bar.bzl basename, - ], + ] + + extra_alt_names, ) index_node = addnodes.index( entries=[ diff --git a/sphinxdocs/tests/sphinx_stardoc/sphinx_output_test.py b/sphinxdocs/tests/sphinx_stardoc/sphinx_output_test.py index aa21369b40..c78089ac14 100644 --- a/sphinxdocs/tests/sphinx_stardoc/sphinx_output_test.py +++ b/sphinxdocs/tests/sphinx_stardoc/sphinx_output_test.py @@ -67,6 +67,8 @@ def _doc_element(self, doc): ("tag_class_attr_using_attr_role_just_attr_name", "ta1", "module_extension.html#myext.mytag.ta1"), ("file_without_repo", "//lang:rule.bzl", "rule.html"), ("file_with_repo", "@testrepo//lang:rule.bzl", "rule.html"), + ("package_absolute", "//lang", "target.html"), + ("package_basename", "lang", "target.html"), # fmt: on ) def test_xrefs(self, text, href): diff --git a/sphinxdocs/tests/sphinx_stardoc/xrefs.md b/sphinxdocs/tests/sphinx_stardoc/xrefs.md index a32bb10339..bbd415ce19 100644 --- a/sphinxdocs/tests/sphinx_stardoc/xrefs.md +++ b/sphinxdocs/tests/sphinx_stardoc/xrefs.md @@ -51,3 +51,8 @@ Various tests of cross referencing support * without repo {obj}`//lang:rule.bzl` * with repo {obj}`@testrepo//lang:rule.bzl` + +## Package refs + +* absolute label {obj}`//lang` +* package basename {obj}`lang`