xref: /aosp_15_r20/external/bazelbuild-rules_python/sphinxdocs/docs/starlark-docgen.md (revision 60517a1edbc8ecf509223e9af94a7adec7d736b8)
1# Starlark docgen
2
3Using the `sphinx_stardoc` rule, API documentation can be generated from bzl
4source code. This rule requires both MyST-based markdown and the `sphinx_bzl`
5Sphinx extension are enabled. This allows source code to use Markdown and
6Sphinx syntax to create rich documentation with cross references, types, and
7more.
8
9
10## Configuring Sphinx
11
12While the `sphinx_stardoc` rule doesn't require Sphinx itself, the source
13it generates requires some additional Sphinx plugins and config settings.
14
15When defining the `sphinx_build_binary` target, also depend on:
16* `@rules_python//sphinxdocs/src/sphinx_bzl:sphinx_bzl`
17* `myst_parser` (e.g. `@pypi//myst_parser`)
18* `typing_extensions` (e.g. `@pypi//myst_parser`)
19
20```
21sphinx_build_binary(
22    name = "sphinx-build",
23    deps = [
24        "@rules_python//sphinxdocs/src/sphinx_bzl",
25        "@pypi//myst_parser",
26        "@pypi//typing_extensions",
27        ...
28    ]
29)
30```
31
32In `conf.py`, enable the `sphinx_bzl` extension, `myst_parser` extension,
33and the `colon_fence` MyST extension.
34
35```
36extensions = [
37    "myst_parser",
38    "sphinx_bzl.bzl",
39]
40
41myst_enable_extensions = [
42    "colon_fence",
43]
44```
45
46## Generating docs from bzl files
47
48To convert the bzl code to Sphinx doc sources, `sphinx_stardocs` is the primary
49rule to do so. It takes a list of `bzl_library` targets or files and generates docs for
50each. When a `bzl_library` target is passed, the `bzl_library.srcs` value can only
51have a single file.
52
53Example:
54
55```
56sphinx_stardocs(
57    name = "my_docs",
58    srcs = [
59      ":binary_bzl",
60      ":library_bzl",
61    ]
62)
63
64bzl_library(
65   name = "binary_bzl",
66   srcs = ["binary.bzl"],
67   deps = ...
68)
69
70bzl_library(
71   name = "library_bzl",
72   srcs = ["library.bzl"],
73   deps = ...
74)
75```
76