MartinPdeS-docs 0.3.2__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MartinPdeS-docs
3
- Version: 0.3.2
3
+ Version: 0.5.0
4
4
  Summary: Shared Sphinx configuration for MartinPdeS scientific Python packages.
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -11,6 +11,8 @@ Requires-Dist: sphinx-design>=0.6
11
11
  Requires-Dist: sphinx-gallery>=0.16
12
12
  Requires-Dist: numpydoc<2,>=1.8
13
13
  Requires-Dist: pytest>=7
14
+ Provides-Extra: release
15
+ Requires-Dist: martinpdes-maintenance==0.2.2; extra == "release"
14
16
  Dynamic: license-file
15
17
 
16
18
  # MartinPdeS-docs
@@ -43,6 +45,24 @@ globals().update(
43
45
  Project-specific values can be assigned below this call to override any
44
46
  shared default.
45
47
 
48
+ Set `version="auto"` to read `__version__` from the importable package's
49
+ `_version.py` without importing its `__init__.py`. This sets both Sphinx's
50
+ `version` and `release` fields and the version switcher, and takes precedence
51
+ over the `tag` environment variable. The package must be importable and its
52
+ `_version.py` must provide a non-empty version string. With
53
+ `prefer_installed_package=True`, discovery follows the same package search
54
+ order used for documentation imports. Omitting `version` retains the existing
55
+ environment and distribution-metadata fallback.
56
+
57
+ Pass `docs_root` when assets or gallery data live outside the current working
58
+ directory. The optional `profile` argument accepts `"default"`,
59
+ `"scientific-gallery"`, or `"minimal"`; the minimal profile disables
60
+ Sphinx-Gallery while retaining the shared theme and autodoc defaults.
61
+
62
+ Theme options and autodoc options are merged recursively, so a project can
63
+ override one nested value without replacing shared defaults. Repository values
64
+ must use the `owner/name` GitHub form.
65
+
46
66
  For a multi-section Sphinx-Gallery, pass the section names instead of
47
67
  repeating the directory mappings:
48
68
 
@@ -4,3 +4,6 @@ sphinx-design>=0.6
4
4
  sphinx-gallery>=0.16
5
5
  numpydoc<2,>=1.8
6
6
  pytest>=7
7
+
8
+ [release]
9
+ martinpdes-maintenance==0.2.2
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MartinPdeS-docs
3
- Version: 0.3.2
3
+ Version: 0.5.0
4
4
  Summary: Shared Sphinx configuration for MartinPdeS scientific Python packages.
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -11,6 +11,8 @@ Requires-Dist: sphinx-design>=0.6
11
11
  Requires-Dist: sphinx-gallery>=0.16
12
12
  Requires-Dist: numpydoc<2,>=1.8
13
13
  Requires-Dist: pytest>=7
14
+ Provides-Extra: release
15
+ Requires-Dist: martinpdes-maintenance==0.2.2; extra == "release"
14
16
  Dynamic: license-file
15
17
 
16
18
  # MartinPdeS-docs
@@ -43,6 +45,24 @@ globals().update(
43
45
  Project-specific values can be assigned below this call to override any
44
46
  shared default.
45
47
 
48
+ Set `version="auto"` to read `__version__` from the importable package's
49
+ `_version.py` without importing its `__init__.py`. This sets both Sphinx's
50
+ `version` and `release` fields and the version switcher, and takes precedence
51
+ over the `tag` environment variable. The package must be importable and its
52
+ `_version.py` must provide a non-empty version string. With
53
+ `prefer_installed_package=True`, discovery follows the same package search
54
+ order used for documentation imports. Omitting `version` retains the existing
55
+ environment and distribution-metadata fallback.
56
+
57
+ Pass `docs_root` when assets or gallery data live outside the current working
58
+ directory. The optional `profile` argument accepts `"default"`,
59
+ `"scientific-gallery"`, or `"minimal"`; the minimal profile disables
60
+ Sphinx-Gallery while retaining the shared theme and autodoc defaults.
61
+
62
+ Theme options and autodoc options are merged recursively, so a project can
63
+ override one nested value without replacing shared defaults. Repository values
64
+ must use the `owner/name` GitHub form.
65
+
46
66
  For a multi-section Sphinx-Gallery, pass the section names instead of
47
67
  repeating the directory mappings:
48
68
 
@@ -28,6 +28,24 @@ globals().update(
28
28
  Project-specific values can be assigned below this call to override any
29
29
  shared default.
30
30
 
31
+ Set `version="auto"` to read `__version__` from the importable package's
32
+ `_version.py` without importing its `__init__.py`. This sets both Sphinx's
33
+ `version` and `release` fields and the version switcher, and takes precedence
34
+ over the `tag` environment variable. The package must be importable and its
35
+ `_version.py` must provide a non-empty version string. With
36
+ `prefer_installed_package=True`, discovery follows the same package search
37
+ order used for documentation imports. Omitting `version` retains the existing
38
+ environment and distribution-metadata fallback.
39
+
40
+ Pass `docs_root` when assets or gallery data live outside the current working
41
+ directory. The optional `profile` argument accepts `"default"`,
42
+ `"scientific-gallery"`, or `"minimal"`; the minimal profile disables
43
+ Sphinx-Gallery while retaining the shared theme and autodoc defaults.
44
+
45
+ Theme options and autodoc options are merged recursively, so a project can
46
+ override one nested value without replacing shared defaults. Repository values
47
+ must use the `owner/name` GitHub form.
48
+
31
49
  For a multi-section Sphinx-Gallery, pass the section names instead of
32
50
  repeating the directory mappings:
33
51
 
@@ -1,7 +1,9 @@
1
1
  """Configurable defaults for the shared project documentation sites."""
2
2
 
3
3
  import os
4
+ import runpy
4
5
  from collections.abc import Mapping, Sequence
6
+ from importlib.util import find_spec
5
7
  import sys
6
8
  from importlib.metadata import (
7
9
  PackageNotFoundError,
@@ -9,9 +11,29 @@ from importlib.metadata import (
9
11
  version as distribution_version,
10
12
  )
11
13
  from pathlib import Path
14
+ import warnings
12
15
 
13
16
 
14
- def _raster_thumbnail_path(logo: str, favicon: str) -> str | None:
17
+ def _deep_merge(base: dict, override: Mapping) -> dict:
18
+ """Merge nested mappings without mutating either input mapping."""
19
+ merged = dict(base)
20
+ for key, value in override.items():
21
+ if isinstance(merged.get(key), Mapping) and isinstance(value, Mapping):
22
+ merged[key] = _deep_merge(dict(merged[key]), value)
23
+ else:
24
+ merged[key] = value
25
+ return merged
26
+
27
+
28
+ def _parse_repository(repository: str) -> tuple[str, str]:
29
+ """Validate and split a ``owner/repository`` GitHub identifier."""
30
+ parts = repository.split("/")
31
+ if len(parts) != 2 or not all(parts) or any(part.strip() != part for part in parts):
32
+ raise ValueError("repository must be a GitHub identifier in the form 'owner/name'.")
33
+ return parts[0], parts[1]
34
+
35
+
36
+ def _raster_thumbnail_path(logo: str, favicon: str, docs_root: Path | None = None) -> str | None:
15
37
  """Choose a Sphinx-Gallery-compatible fallback thumbnail.
16
38
 
17
39
  Sphinx-Gallery requires a raster image for ``default_thumb_file``. SVG
@@ -21,20 +43,17 @@ def _raster_thumbnail_path(logo: str, favicon: str) -> str | None:
21
43
  raster_suffixes = {".png", ".jpg", ".jpeg", ".gif"}
22
44
  for candidate in (logo, favicon):
23
45
  if Path(candidate).suffix.lower() in raster_suffixes:
24
- return _resolve_doc_asset(candidate)
46
+ return _resolve_doc_asset(candidate, docs_root)
25
47
  return None
26
48
 
27
49
 
28
- def _resolve_doc_asset(path: str) -> str:
50
+ def _resolve_doc_asset(path: str, docs_root: Path | None = None) -> str:
29
51
  """Resolve a documentation asset relative to common Sphinx build roots."""
30
52
  candidate = Path(path)
31
53
  if candidate.is_absolute():
32
54
  return str(candidate)
33
55
 
34
- roots = (
35
- Path.cwd(),
36
- Path.cwd() / "docs" / "source",
37
- )
56
+ roots = tuple(root for root in (docs_root, Path.cwd(), Path.cwd() / "docs" / "source") if root is not None)
38
57
  for root in roots:
39
58
  resolved = root / candidate
40
59
  if resolved.is_file():
@@ -44,6 +63,19 @@ def _resolve_doc_asset(path: str) -> str:
44
63
 
45
64
  def _resolve_version(package: str, version: str | None) -> str:
46
65
  """Resolve the documentation version without importing the package."""
66
+ if version == "auto":
67
+ spec = find_spec(package)
68
+ locations = spec.submodule_search_locations if spec is not None else None
69
+ if locations is None:
70
+ raise ValueError(f"Cannot find package {package!r} to read its _version.py.")
71
+ for location in locations:
72
+ version_file = Path(location) / "_version.py"
73
+ if version_file.is_file():
74
+ resolved = runpy.run_path(str(version_file)).get("__version__")
75
+ if not isinstance(resolved, str) or not resolved:
76
+ raise ValueError(f"{version_file} must define a non-empty __version__ string.")
77
+ return resolved
78
+ raise ValueError(f"Cannot find _version.py in package {package!r}.")
47
79
  if version is not None:
48
80
  return version
49
81
 
@@ -54,6 +86,12 @@ def _resolve_version(package: str, version: str | None) -> str:
54
86
  try:
55
87
  return distribution_version(package)
56
88
  except PackageNotFoundError:
89
+ warnings.warn(
90
+ f"Could not resolve an installed distribution for {package!r}; using 'latest'. "
91
+ "Pass version= explicitly or use version='auto' for published documentation.",
92
+ RuntimeWarning,
93
+ stacklevel=2,
94
+ )
57
95
  return "latest"
58
96
 
59
97
 
@@ -62,6 +100,12 @@ def _prefer_installed_package(package: str) -> None:
62
100
  try:
63
101
  installed_site = str(distribution(package).locate_file(""))
64
102
  except PackageNotFoundError:
103
+ warnings.warn(
104
+ f"prefer_installed_package=True but distribution {package!r} is not installed; "
105
+ "documentation imports may resolve to the source checkout.",
106
+ RuntimeWarning,
107
+ stacklevel=2,
108
+ )
65
109
  return
66
110
 
67
111
  sys.path[:] = [entry for entry in sys.path if entry != installed_site]
@@ -91,6 +135,8 @@ def configure(
91
135
  prefer_installed_package: bool = False,
92
136
  include_gallery: bool = True,
93
137
  version: str | None = None,
138
+ docs_root: str | Path | None = None,
139
+ profile: str = "default",
94
140
  source_suffix: str = ".rst",
95
141
  master_doc: str = "index",
96
142
  ) -> dict:
@@ -102,8 +148,17 @@ def configure(
102
148
  directories; use ``gallery_default_thumb`` for a project-specific raster
103
149
  fallback; use ``gallery_options`` for less common Sphinx-Gallery settings;
104
150
  and set ``prefer_installed_package`` for projects whose documentation must
105
- import a built wheel instead of the source checkout.
151
+ import a built wheel instead of the source checkout. Set ``version="auto"``
152
+ to read ``__version__`` from the importable package's ``_version.py`` and
153
+ use it for both Sphinx version fields and the version switcher.
106
154
  """
155
+ if profile not in {"default", "scientific-gallery", "minimal"}:
156
+ raise ValueError("profile must be one of 'default', 'scientific-gallery', or 'minimal'.")
157
+ if profile == "minimal":
158
+ include_gallery = False
159
+
160
+ resolved_docs_root = Path(docs_root).resolve() if docs_root is not None else None
161
+
107
162
  if prefer_installed_package:
108
163
  _prefer_installed_package(package)
109
164
 
@@ -127,7 +182,7 @@ def configure(
127
182
  if logo_alt_text is not None:
128
183
  options["logo"]["alt_text"] = logo_alt_text
129
184
  if repository:
130
- owner, repo = repository.split("/", 1)
185
+ owner, repo = _parse_repository(repository)
131
186
  options["icon_links"] = [
132
187
  {
133
188
  "name": "GitHub",
@@ -141,7 +196,7 @@ def configure(
141
196
  },
142
197
  {
143
198
  "name": "Anaconda",
144
- "url": f"https://anaconda.org/{repository.split('/')[0]}/{package}",
199
+ "url": f"https://anaconda.org/{owner}/{package}",
145
200
  "icon": "fa-brands fa-python",
146
201
  },
147
202
  ]
@@ -155,7 +210,7 @@ def configure(
155
210
  "default_mode": "dark",
156
211
  }
157
212
  if repository:
158
- owner, repo = repository.split("/", 1)
213
+ owner, repo = _parse_repository(repository)
159
214
  ref_name = os.getenv("GITHUB_REF_NAME", "master")
160
215
  context.update(
161
216
  {
@@ -167,7 +222,7 @@ def configure(
167
222
  if html_context:
168
223
  context.update(html_context)
169
224
  if html_theme_options:
170
- options.update(html_theme_options)
225
+ options = _deep_merge(options, html_theme_options)
171
226
 
172
227
  default_extensions = [
173
228
  "sphinx.ext.autodoc",
@@ -201,7 +256,7 @@ def configure(
201
256
  # Use the project's favicon for examples that do not create a figure.
202
257
  # The path is interpreted relative to the documentation source tree,
203
258
  # just like ``html_favicon``.
204
- "default_thumb_file": _raster_thumbnail_path(logo, favicon),
259
+ "default_thumb_file": _raster_thumbnail_path(logo, favicon, resolved_docs_root),
205
260
  "line_numbers": False,
206
261
  "remove_config_comments": True,
207
262
  "capture_repr": ("_repr_html_", "__repr__"),
@@ -215,7 +270,7 @@ def configure(
215
270
  gallery["gallery_dirs"] = [f"gallery/{section}" for section in sections]
216
271
  if gallery is not None:
217
272
  if gallery_default_thumb is not None:
218
- gallery["default_thumb_file"] = _resolve_doc_asset(gallery_default_thumb)
273
+ gallery["default_thumb_file"] = _resolve_doc_asset(gallery_default_thumb, resolved_docs_root)
219
274
  if gallery_options:
220
275
  gallery.update(gallery_options)
221
276
  if sphinx_gallery_conf:
@@ -235,6 +290,8 @@ def configure(
235
290
  configuration = {
236
291
  "project": project,
237
292
  "package": package,
293
+ "version": resolved_version,
294
+ "release": resolved_version,
238
295
  "author": author,
239
296
  "copyright": author,
240
297
  "extensions": configured_extensions,
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "MartinPdeS-docs"
7
- version = "0.3.2"
7
+ version = "0.5.0"
8
8
  description = "Shared Sphinx configuration for MartinPdeS scientific Python packages."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -25,3 +25,9 @@ martinpdes_docs = ["static/*.css"]
25
25
 
26
26
  [tool.pytest.ini_options]
27
27
  testpaths = ["tests"]
28
+
29
+ [project.optional-dependencies]
30
+ release = ["martinpdes-maintenance==0.2.2"]
31
+
32
+ [tool.mps-maintenance]
33
+ conda-recipe = "conda.recipe/meta.yaml"
@@ -2,6 +2,8 @@ from importlib.metadata import distribution
2
2
  from pathlib import Path
3
3
  import sys
4
4
 
5
+ import pytest
6
+
5
7
  from martinpdes_docs import configure
6
8
 
7
9
 
@@ -91,6 +93,16 @@ def test_custom_extensions_and_theme_options_are_preserved():
91
93
  "image": "_static/logo.svg",
92
94
  "alt_text": "Example logo",
93
95
  }
96
+
97
+ nested = configure(
98
+ project="Example",
99
+ package="example",
100
+ html_theme_options={"logo": {"text": "Custom"}},
101
+ )
102
+ assert nested["html_theme_options"]["logo"] == {
103
+ "text": "Custom",
104
+ "image": "_static/logo.svg",
105
+ }
94
106
  assert additions["autodoc_default_options"]["members"] is True
95
107
 
96
108
  no_gallery = configure(
@@ -127,6 +139,44 @@ def test_gallery_thumbnail_paths_are_resolved_from_docs_source(tmp_path, monkeyp
127
139
  assert config["sphinx_gallery_conf"]["default_thumb_file"] == str(asset)
128
140
 
129
141
 
142
+ def test_docs_root_resolves_gallery_assets(tmp_path):
143
+ asset = tmp_path / "gallery-default.png"
144
+ asset.write_bytes(b"png")
145
+
146
+ config = configure(
147
+ project="Example",
148
+ package="example",
149
+ docs_root=tmp_path,
150
+ gallery_default_thumb="gallery-default.png",
151
+ )
152
+
153
+ assert config["sphinx_gallery_conf"]["default_thumb_file"] == str(asset)
154
+
155
+
156
+ def test_repository_identifier_is_validated():
157
+ with pytest.raises(ValueError, match="owner/name"):
158
+ configure(project="Example", package="example", repository="github.com/owner/name")
159
+
160
+
161
+ def test_minimal_profile_disables_gallery():
162
+ config = configure(project="Example", package="example", profile="minimal")
163
+
164
+ assert "sphinx_gallery.gen_gallery" not in config["extensions"]
165
+ assert "sphinx_gallery_conf" not in config
166
+
167
+
168
+ def test_missing_distribution_warns_when_preferred():
169
+ with pytest.warns(RuntimeWarning, match="not installed"):
170
+ configure(project="Example", package="missing_example", prefer_installed_package=True)
171
+
172
+
173
+ def test_missing_distribution_version_warns():
174
+ with pytest.warns(RuntimeWarning, match="using 'latest'"):
175
+ config = configure(project="Example", package="missing_example")
176
+
177
+ assert config["version"] == "latest"
178
+
179
+
130
180
  def test_version_can_be_resolved_from_the_environment(monkeypatch):
131
181
  monkeypatch.setenv("tag", "v2.3.4")
132
182
 
@@ -139,6 +189,37 @@ def test_version_can_be_resolved_from_the_environment(monkeypatch):
139
189
  assert config["html_theme_options"]["switcher"]["version_match"] == "v2.3.4"
140
190
 
141
191
 
192
+ def test_auto_version_reads_package_file_without_importing_package(tmp_path, monkeypatch):
193
+ package = tmp_path / "example_auto_version"
194
+ package.mkdir()
195
+ (package / "__init__.py").write_text("raise RuntimeError('package must not be imported')\n")
196
+ (package / "_version.py").write_text('__version__ = version = "1.2.3"\n')
197
+ monkeypatch.syspath_prepend(str(tmp_path))
198
+ monkeypatch.setenv("tag", "v9.9.9")
199
+
200
+ config = configure(
201
+ project="Example", package="example_auto_version",
202
+ repository="MartinPdeS/Example", version="auto",
203
+ )
204
+
205
+ assert config["version"] == config["release"] == "1.2.3"
206
+ assert config["html_theme_options"]["switcher"]["version_match"] == "1.2.3"
207
+ assert "example_auto_version" not in sys.modules
208
+
209
+
210
+ def test_auto_version_rejects_missing_or_invalid_version_file(tmp_path, monkeypatch):
211
+ package = tmp_path / "example_invalid_version"
212
+ package.mkdir()
213
+ (package / "__init__.py").write_text("")
214
+ monkeypatch.syspath_prepend(str(tmp_path))
215
+
216
+ with pytest.raises(ValueError, match="Cannot find _version.py"):
217
+ configure(project="Example", package="example_invalid_version", version="auto")
218
+ (package / "_version.py").write_text("__version__ = None\n")
219
+ with pytest.raises(ValueError, match="non-empty __version__"):
220
+ configure(project="Example", package="example_invalid_version", version="auto")
221
+
222
+
142
223
  def test_installed_package_can_be_preferred(monkeypatch):
143
224
  installed_site = str(distribution("MartinPdeS-docs").locate_file(""))
144
225
  monkeypatch.setattr(sys, "path", ["checkout", installed_site, "other"])
File without changes