Skip to content

Commit 2e96b3f

Browse files
authored
sphinxdocs: make bazel package xrefs work (#2903)
This allows using xrefs like `//python/runtime_env_toolchains` and `runtime_env_toolchains`.
1 parent 8f9ef76 commit 2e96b3f

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

sphinxdocs/src/sphinx_bzl/bzl.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,7 @@ def _make_xrefs_for_arg_attr(
394394
# This allows referencing an arg as e.g `funcname.argname`
395395
anchor_id,
396396
# This allows referencing an arg as simply `argname`
397-
arg_name
397+
arg_name,
398398
],
399399
)
400400

@@ -503,7 +503,22 @@ def run(self) -> list[docutils_nodes.Node]:
503503
self.env.ref_context["bzl:object_id_stack"] = []
504504
self.env.ref_context["bzl:doc_id_stack"] = []
505505

506-
_, _, basename = file_label.partition(":")
506+
package_label, _, basename = file_label.partition(":")
507+
508+
# Transform //foo/bar:BUILD.bazel into "bar"
509+
# This allows referencing "bar" as itself
510+
extra_alt_names = []
511+
if basename in ("BUILD.bazel", "BUILD"):
512+
# Allow xref //foo
513+
extra_alt_names.append(package_label)
514+
basename = os.path.basename(package_label)
515+
# Handle //:BUILD.bazel
516+
if not basename:
517+
# There isn't a convention for referring to the root package
518+
# besides `//:`, which is already the file_label. So just
519+
# use some obvious value
520+
basename = "__ROOT_BAZEL_PACKAGE__"
521+
507522
index_description = f"File {label}"
508523
absolute_label = repo + label
509524
self.env.get_domain("bzl").add_object(
@@ -527,7 +542,8 @@ def run(self) -> list[docutils_nodes.Node]:
527542
file_label,
528543
# Allow xref bar.bzl
529544
basename,
530-
],
545+
]
546+
+ extra_alt_names,
531547
)
532548
index_node = addnodes.index(
533549
entries=[

sphinxdocs/tests/sphinx_stardoc/sphinx_output_test.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ def _doc_element(self, doc):
6767
("tag_class_attr_using_attr_role_just_attr_name", "ta1", "module_extension.html#myext.mytag.ta1"),
6868
("file_without_repo", "//lang:rule.bzl", "rule.html"),
6969
("file_with_repo", "@testrepo//lang:rule.bzl", "rule.html"),
70+
("package_absolute", "//lang", "target.html"),
71+
("package_basename", "lang", "target.html"),
7072
# fmt: on
7173
)
7274
def test_xrefs(self, text, href):

sphinxdocs/tests/sphinx_stardoc/xrefs.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,8 @@ Various tests of cross referencing support
5151

5252
* without repo {obj}`//lang:rule.bzl`
5353
* with repo {obj}`@testrepo//lang:rule.bzl`
54+
55+
## Package refs
56+
57+
* absolute label {obj}`//lang`
58+
* package basename {obj}`lang`

0 commit comments

Comments
 (0)