diff --git a/docs/user_guide/05-configuration.qmd b/docs/user_guide/05-configuration.qmd index d398beb6..e36edbc4 100644 --- a/docs/user_guide/05-configuration.qmd +++ b/docs/user_guide/05-configuration.qmd @@ -323,7 +323,17 @@ interlinks: ``` With it, `` `mp.add()` `` and `` [](`mp.add`) `` link to your own reference as `my_package.add`. -If a source declares the same alias, your package keeps it and the build log says so. See +Provide a mapping to give each alias a specific module path. + +```yaml +interlinks: + aliases: + mp: my_package + tools: my_package.tools +``` + +Now `` `tools.Parser` `` links to the reference for `my_package.tools.Parser`. If a source declares +the same alias, your project keeps it and the build log says so. See [Cross-Referencing](12-cross-referencing.qmd) for details. Inventories are downloaded during the build and cached, so repeated builds do no network work, diff --git a/docs/user_guide/12-cross-referencing.qmd b/docs/user_guide/12-cross-referencing.qmd index 1402ae63..d8a1c445 100644 --- a/docs/user_guide/12-cross-referencing.qmd +++ b/docs/user_guide/12-cross-referencing.qmd @@ -84,8 +84,17 @@ wherever that name does. This works for code autolinks and for explicit referenc `` [](`mp.Pipeline`) ``. A name your package does not document, such as a module-level instance, stays unlinked. -An alias names one package. If a source in `interlinks.sources` also declares it, your own -package keeps it and the build log notes the clash. +To use an alias for a subpackage, specify the full module path. With this configuration, +`` `tools.Parser` `` links to `my_package.tools.Parser` in your reference. + +```yaml +interlinks: + aliases: + tools: my_package.tools +``` + +If a source in `interlinks.sources` also declares the alias, your own project keeps it and the +build log notes the clash. ## When a Short Name Is Ambiguous diff --git a/great_docs/_interlinks/index.py b/great_docs/_interlinks/index.py index ce12add6..90752bc5 100644 --- a/great_docs/_interlinks/index.py +++ b/great_docs/_interlinks/index.py @@ -5,7 +5,7 @@ from __future__ import annotations from collections import Counter -from collections.abc import Iterable, Sequence +from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass, field from typing import TYPE_CHECKING from urllib.parse import urljoin @@ -239,7 +239,7 @@ def build_index( claims: AliasClaims, external: Sequence[tuple[Source, Inventory]], *, - aliases: Sequence[str] = (), + aliases: Sequence[str] | Mapping[str, str] = (), add_function_parentheses: bool = True, ) -> Index: """ @@ -250,8 +250,8 @@ def build_index( exactly one object is added as a candidate ranked below this project's real names and above any other project's; ambiguous ones are reported instead. - An alias of this project stands for the modules its own inventory - documents, and replaces a source's alias of the same name. + A local alias stands for the project's root modules or a specific module + named in the configuration. It replaces a source's alias of the same name. Parameters ---------- @@ -262,7 +262,8 @@ def build_index( external : Each source and the inventory read for it. aliases : - The names prose uses for this project's package. + The names prose uses for this project's package, or a mapping from each + alias to the full module path it stands for. add_function_parentheses : Whether a link to a function or method shows a trailing `()`. @@ -306,12 +307,15 @@ def add(name: str, rank: int, priority: int, entry: IndexEntry) -> None: for alias in source.aliases: prefixes[alias] = roots - local_roots = root_modules(local) - for alias in aliases: - # An alias spelt like a documented module adds nothing: the name as - # written already resolves. - if local_roots and alias not in local_roots: - prefixes[alias] = local_roots + if isinstance(aliases, Mapping): + prefixes.update({alias: (module,) for alias, module in aliases.items()}) + else: + local_roots = root_modules(local) + for alias in aliases: + # An alias spelt like a documented module adds nothing: the name as + # written already resolves. + if local_roots and alias not in local_roots: + prefixes[alias] = local_roots ordered = { name: tuple(entry for _, entry in sorted(items, key=lambda pair: pair[0])) diff --git a/great_docs/_interlinks/project.py b/great_docs/_interlinks/project.py index 17b19c72..9660b28d 100644 --- a/great_docs/_interlinks/project.py +++ b/great_docs/_interlinks/project.py @@ -33,8 +33,8 @@ def build_project_index( Read the project's `objects.inv` when available, merge it with the sources declared in `config.interlinks_sources`, and write the result to `project_path/_inv/index.lua` for the interlinks filter. An alias in - `config.interlinks_aliases` names this project, even when a source declares - it too. + `config.interlinks_aliases` names this project's package or a specific + module, even when a source declares it too. Parameters ---------- diff --git a/great_docs/config.py b/great_docs/config.py index 4c6882c1..3c1219bd 100644 --- a/great_docs/config.py +++ b/great_docs/config.py @@ -1691,9 +1691,22 @@ def jupyter(self) -> str: return self["jupyter"] @property - def interlinks_aliases(self) -> list[str]: - """The names prose uses for this project's own package.""" - return YamlMapping(self["interlinks"]).strings("aliases") + def interlinks_aliases(self) -> list[str] | dict[str, str]: + """ + Import aliases for the project's package or its modules + + A single string or a list names the package. A mapping gives the + full module path for each alias. + """ + interlinks = YamlMapping(self["interlinks"]) + aliases = interlinks.get("aliases") + if isinstance(aliases, dict): + return { + alias: module + for alias, module in aliases.items() + if isinstance(alias, str) and isinstance(module, str) + } + return interlinks.strings("aliases") @property def interlinks_sources(self) -> ConfigDict: diff --git a/tests/test_interlinks.py b/tests/test_interlinks.py index 82957a5e..48dd31c0 100644 --- a/tests/test_interlinks.py +++ b/tests/test_interlinks.py @@ -791,3 +791,25 @@ def test_write_index_removes_a_stale_compiled_index(tmp_path): write_index(Index(), path) assert not compiled.exists() + + +@pytest.mark.parametrize( + ("aliases", "prefix"), + [("[s]", "demo"), ("s", "demo"), ("{s: demo.tools}", "demo.tools")], +) +def test_project_aliases_accept_a_module_mapping(tmp_path, aliases: str, prefix: str) -> None: + local = Inventory( + "demo", + "1", + ( + InventoryEntry("demo.run", "py", "function", 1, "run.html", "-"), + InventoryEntry("demo.tools.run", "py", "function", 1, "tools/run.html", "-"), + ), + ) + (tmp_path / "objects.inv").write_bytes(encode(local)) + (tmp_path / "great-docs.yml").write_text(f"interlinks:\n aliases: {aliases}\n") + + index, _ = build_project_index(tmp_path, Config(tmp_path), "demo", AliasClaims()) + + assert index.prefixes == {"s": (prefix,)} + assert index.resolves("s.run") diff --git a/tests/test_interlinks_filter.py b/tests/test_interlinks_filter.py index 8291a6dd..a66c4697 100644 --- a/tests/test_interlinks_filter.py +++ b/tests/test_interlinks_filter.py @@ -9,7 +9,7 @@ import pytest -from great_docs._interlinks import AliasClaims, Index, IndexEntry, build_index, write_index +from great_docs._interlinks import AliasClaims, Index, IndexEntry, Source, build_index, write_index from great_docs._interlinks.sphinx_inventory import Inventory, InventoryEntry _FILTER = ( @@ -496,3 +496,34 @@ def test_an_alias_of_this_project_links_a_package_level_name(tmp_path): assert out.count(f"/{uri}") == 2 assert '"p.findinds()"' in out + + +def test_subpackage_alias_links_code_and_explicit_references(tmp_path: Path) -> None: + local = Inventory( + "pkg", + "1", + ( + InventoryEntry("pkg.SIR", "py", "class", 1, "root.html", "-"), + InventoryEntry("pkg.library.SIR", "py", "class", 1, "submodule.html", "-"), + InventoryEntry("pkg.library.Other", "py", "class", 1, "mapped.html", "-"), + InventoryEntry("ssl.Other", "py", "class", 1, "exact.html", "-"), + ), + ) + external = Inventory( + "external", + "1", + (InventoryEntry("ext.SIR", "py", "class", 1, "external.html", "-"),), + ) + source = Source(name="external", url="https://example.com", aliases=("ssl",)) + index = build_index(local, AliasClaims(), [(source, external)], aliases={"ssl": "pkg.library"}) + + out = _run_filter_over_written_index( + "`ssl.SIR` and [](`ssl.SIR`) and [](`ssl.Other`)\n", index, tmp_path + ) + + assert index.resolves("ssl.SIR") + assert out.count('"/submodule.html"') == 2 + assert '"/exact.html"' in out + assert '"/mapped.html"' not in out + assert '"/root.html"' not in out + assert "https://example.com/external.html" not in out diff --git a/tests/test_lint.py b/tests/test_lint.py index 75330df8..8cc6c4e7 100644 --- a/tests/test_lint.py +++ b/tests/test_lint.py @@ -11,7 +11,6 @@ from great_docs._checks.lint import ( LintIssue, LintResult, - check_config_keys, _check_cross_references, _check_directive_consistency, _check_docstring_style, @@ -20,6 +19,7 @@ _lost_sections, _section_kinds, _version_distance, + check_config_keys, run_lint, ) from great_docs._interlinks import Source @@ -2470,3 +2470,30 @@ def test_parameter_directive_errors_do_not_abort_lint( assert any( issue.check == "missing-docstring" and issue.symbol == "g" for issue in result.issues ) + + +def test_lint_resolves_a_seealso_reference_to_a_subpackage_alias( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + package = tmp_path / "aliaslint" + package.mkdir() + (package / "__init__.py").write_text( + 'def read():\n """Read an item.\n\n %seealso tools.Item\n' + ' %seealso tools.Absent\n """\n' + ) + (package / "tools.py").write_text('class Item:\n """An item."""\n') + write_pyproject(tmp_path, "aliaslint") + (tmp_path / "great-docs.yml").write_text( + "dynamic: false\n" + "reference:\n" + " sections:\n" + " - contents: [read, tools.Item]\n" + "interlinks:\n" + " aliases: {tools: aliaslint.tools}\n" + ) + monkeypatch.syspath_prepend(str(tmp_path)) + + result = run_lint(tmp_path, checks={"cross-refs"}, quiet=True) + + [issue] = result.issues + assert "tools.Absent" in issue.message