rompy-docs 0.1.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.
@@ -0,0 +1,54 @@
1
+ # Publishes rompy-docs to PyPI when a GitHub Release is published,
2
+ # with PyPI trusted publishing (no token).
3
+ name: Upload Python Package
4
+
5
+ on:
6
+ release:
7
+ types: [published]
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ release-build:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.x"
20
+ - name: Run the tests
21
+ run: |
22
+ python -m pip install ".[test]"
23
+ pytest -q tests
24
+ - name: Build release distributions
25
+ run: |
26
+ python -m pip install build twine
27
+ python -m build
28
+ twine check dist/*
29
+ - name: Upload distributions
30
+ uses: actions/upload-artifact@v4
31
+ with:
32
+ name: release-dists
33
+ path: dist/
34
+
35
+ pypi-publish:
36
+ runs-on: ubuntu-latest
37
+ needs:
38
+ - release-build
39
+ permissions:
40
+ # Mandatory for trusted publishing
41
+ id-token: write
42
+ environment:
43
+ name: pypi
44
+ url: https://pypi.org/p/rompy-docs
45
+ steps:
46
+ - name: Retrieve release distributions
47
+ uses: actions/download-artifact@v4
48
+ with:
49
+ name: release-dists
50
+ path: dist/
51
+ - name: Publish release distributions to PyPI
52
+ uses: pypa/gh-action-pypi-publish@release/v1
53
+ with:
54
+ packages-dir: dist/
@@ -0,0 +1,5 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ .venv/
4
+ site/
5
+ .pytest_cache/
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.5
2
+ Name: rompy-docs
3
+ Version: 0.1.0
4
+ Summary: Shared documentation tooling for rompy and its model plugins
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Requires-Dist: griffe-pydantic>=1.3
9
+ Requires-Dist: markdown-exec>=1.12
10
+ Requires-Dist: mkdocs-material>=9.7
11
+ Requires-Dist: mkdocs<2,>=1.6
12
+ Requires-Dist: mkdocstrings[python]>=1.0
13
+ Requires-Dist: properdocs>=1.6.7
14
+ Requires-Dist: pyyaml
15
+ Requires-Dist: ruff
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest; extra == 'test'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # rompy-docs
21
+
22
+ Shared documentation tooling for [rompy](https://github.com/rom-py/rompy) and its model plugins ([rompy-xbeach](https://github.com/rom-py/rompy-xbeach), [rompy-swan](https://github.com/rom-py/rompy-swan), [rompy-schism](https://github.com/rom-py/rompy-schism)) and the [rompy-notebooks](https://github.com/rom-py/rompy-notebooks) site.
23
+
24
+ The sites are built separately, one per repository, and read as one resource:
25
+
26
+ | Layer | Site |
27
+ |---|---|
28
+ | Concepts | [rompy](https://rom-py.github.io/rompy/) |
29
+ | Guide and reference | [rompy-xbeach](https://rom-py.github.io/rompy-xbeach/), [rompy-swan](https://rom-py.github.io/rompy-swan/), [rompy-schism](https://rom-py.github.io/rompy-schism/) |
30
+ | Tutorials and examples | [rompy-notebooks](https://rom-py.github.io/rompy-notebooks/) |
31
+
32
+ This package holds what they share:
33
+
34
+ - **Build stack**: installing `rompy-docs` installs ProperDocs, Material, mkdocstrings, griffe-pydantic and markdown-exec at compatible versions. Sites build with `properdocs build --strict -f mkdocs.yml`.
35
+ - **Theme files**: a bar linking all the sites and shared styles, copied into each site by `rompy-docs sync`.
36
+ - **Configuration template**: [`template.yml`](src/rompy_docs/assets/template.yml) holds the `mkdocs.yml` blocks every site uses. `rompy-docs check` reports where a site differs.
37
+ - **API docs of pydantic models**: the template renders fields with [griffe-pydantic](https://mkdocstrings.github.io/griffe-pydantic/), including the fields a class inherits from rompy. `rompy_docs.griffe:PydanticFieldRules` applies pydantic's field rules that griffe-pydantic's static mode misses.
38
+ - **Notebook links**: `rompy_docs.notebooks` lists notebooks from the inventory the rompy-notebooks site publishes (tutorial tables, example cards, "See it in the notebooks" boxes), so package sites link notebooks without copying them.
39
+ - **Docstring conversion**: `rompy-docs convert` turns Sphinx `.. ipython:: python` and `.. code-block::` directives into Markdown fences. Converted examples run when the docs are built, with their output shown below the code.
40
+
41
+ ## Using it in a site
42
+
43
+ 1. Add `rompy-docs` to the `docs` extra of the package.
44
+ 2. Copy the blocks of `template.yml` into `mkdocs.yml`, then add the site's own settings, including:
45
+
46
+ ```yaml
47
+ extra:
48
+ rompy:
49
+ site: xbeach # rompy, xbeach, swan, schism or notebooks
50
+ ```
51
+
52
+ 3. Run `rompy-docs sync` to copy the theme files into `docs/`, and commit them.
53
+ 4. Build with `properdocs build --strict -f mkdocs.yml`. In CI, also run `rompy-docs check`. The config keeps the `mkdocs.yml` name so that other MkDocs-compatible engines, such as Zensical, can read it.
54
+
55
+ ## Docstring examples
56
+
57
+ Docstrings may use numpy or google style (the template sets `docstring_style: auto`). Write examples in the `Examples` section as markdown-exec fences:
58
+
59
+ ````text
60
+ Examples
61
+ --------
62
+ ```python exec="on" source="above" result="text" session="gen3"
63
+ from rompy_swan.components.physics import GEN3
64
+ print(GEN3().render())
65
+ ```
66
+ ````
67
+
68
+ The code runs at build time and its printed output appears below it. With `--strict`, the build fails if an example raises, so the docs build also tests the examples. Use a plain ```` ```python ```` fence for examples that need data files or a model run.
@@ -0,0 +1,49 @@
1
+ # rompy-docs
2
+
3
+ Shared documentation tooling for [rompy](https://github.com/rom-py/rompy) and its model plugins ([rompy-xbeach](https://github.com/rom-py/rompy-xbeach), [rompy-swan](https://github.com/rom-py/rompy-swan), [rompy-schism](https://github.com/rom-py/rompy-schism)) and the [rompy-notebooks](https://github.com/rom-py/rompy-notebooks) site.
4
+
5
+ The sites are built separately, one per repository, and read as one resource:
6
+
7
+ | Layer | Site |
8
+ |---|---|
9
+ | Concepts | [rompy](https://rom-py.github.io/rompy/) |
10
+ | Guide and reference | [rompy-xbeach](https://rom-py.github.io/rompy-xbeach/), [rompy-swan](https://rom-py.github.io/rompy-swan/), [rompy-schism](https://rom-py.github.io/rompy-schism/) |
11
+ | Tutorials and examples | [rompy-notebooks](https://rom-py.github.io/rompy-notebooks/) |
12
+
13
+ This package holds what they share:
14
+
15
+ - **Build stack**: installing `rompy-docs` installs ProperDocs, Material, mkdocstrings, griffe-pydantic and markdown-exec at compatible versions. Sites build with `properdocs build --strict -f mkdocs.yml`.
16
+ - **Theme files**: a bar linking all the sites and shared styles, copied into each site by `rompy-docs sync`.
17
+ - **Configuration template**: [`template.yml`](src/rompy_docs/assets/template.yml) holds the `mkdocs.yml` blocks every site uses. `rompy-docs check` reports where a site differs.
18
+ - **API docs of pydantic models**: the template renders fields with [griffe-pydantic](https://mkdocstrings.github.io/griffe-pydantic/), including the fields a class inherits from rompy. `rompy_docs.griffe:PydanticFieldRules` applies pydantic's field rules that griffe-pydantic's static mode misses.
19
+ - **Notebook links**: `rompy_docs.notebooks` lists notebooks from the inventory the rompy-notebooks site publishes (tutorial tables, example cards, "See it in the notebooks" boxes), so package sites link notebooks without copying them.
20
+ - **Docstring conversion**: `rompy-docs convert` turns Sphinx `.. ipython:: python` and `.. code-block::` directives into Markdown fences. Converted examples run when the docs are built, with their output shown below the code.
21
+
22
+ ## Using it in a site
23
+
24
+ 1. Add `rompy-docs` to the `docs` extra of the package.
25
+ 2. Copy the blocks of `template.yml` into `mkdocs.yml`, then add the site's own settings, including:
26
+
27
+ ```yaml
28
+ extra:
29
+ rompy:
30
+ site: xbeach # rompy, xbeach, swan, schism or notebooks
31
+ ```
32
+
33
+ 3. Run `rompy-docs sync` to copy the theme files into `docs/`, and commit them.
34
+ 4. Build with `properdocs build --strict -f mkdocs.yml`. In CI, also run `rompy-docs check`. The config keeps the `mkdocs.yml` name so that other MkDocs-compatible engines, such as Zensical, can read it.
35
+
36
+ ## Docstring examples
37
+
38
+ Docstrings may use numpy or google style (the template sets `docstring_style: auto`). Write examples in the `Examples` section as markdown-exec fences:
39
+
40
+ ````text
41
+ Examples
42
+ --------
43
+ ```python exec="on" source="above" result="text" session="gen3"
44
+ from rompy_swan.components.physics import GEN3
45
+ print(GEN3().render())
46
+ ```
47
+ ````
48
+
49
+ The code runs at build time and its printed output appears below it. With `--strict`, the build fails if an example raises, so the docs build also tests the examples. Use a plain ```` ```python ```` fence for examples that need data files or a model run.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "rompy-docs"
7
+ version = "0.1.0"
8
+ description = "Shared documentation tooling for rompy and its model plugins"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "properdocs>=1.6.7",
14
+ "mkdocs>=1.6,<2",
15
+ "mkdocs-material>=9.7",
16
+ "mkdocstrings[python]>=1.0",
17
+ "griffe-pydantic>=1.3",
18
+ "markdown-exec>=1.12",
19
+ "pyyaml",
20
+ "ruff", # formats signatures (separate_signature)
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest"]
25
+
26
+ [project.scripts]
27
+ rompy-docs = "rompy_docs.cli:main"
28
+
29
+ [tool.hatch.build.targets.wheel]
30
+ packages = ["src/rompy_docs"]
@@ -0,0 +1,3 @@
1
+ """Shared documentation tooling for rompy and its model plugins."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,7 @@
1
+ {#- Managed by rompy-docs: do not edit. Site-specific overrides go in extra templates. -#}
2
+ {% extends "base.html" %}
3
+
4
+ {% block header %}
5
+ {% include "partials/rompy-sites.html" %}
6
+ {{ super() }}
7
+ {% endblock %}
@@ -0,0 +1,21 @@
1
+ {#- Bar linking the rompy documentation sites. Managed by rompy-docs: do not edit. -#}
2
+ {%- set sites = [
3
+ ("rompy", "rompy", "https://rom-py.github.io/rompy/"),
4
+ ("xbeach", "XBeach", "https://rom-py.github.io/rompy-xbeach/"),
5
+ ("swan", "SWAN", "https://rom-py.github.io/rompy-swan/"),
6
+ ("schism", "SCHISM", "https://rom-py.github.io/rompy-schism/"),
7
+ ("notebooks", "Notebooks", "https://rom-py.github.io/rompy-notebooks/"),
8
+ ] -%}
9
+ {%- set rompy = config.extra.rompy or {} -%}
10
+ {%- set current = rompy.site -%}
11
+ {%- set model = page.meta.rompy_model if page and page.meta and page.meta.rompy_model else none -%}
12
+ <nav class="rompy-sites" aria-label="rompy documentation sites">
13
+ <div class="rompy-sites__inner md-grid">
14
+ {%- for key, label, url in sites %}
15
+ {%- set classes = ["rompy-sites__link"] -%}
16
+ {%- if key == current or key == model %}{% set _ = classes.append("rompy-sites__link--active") %}{% endif -%}
17
+ <a class="{{ classes | join(' ') }}" href="{{ url }}"
18
+ {%- if key == current %} aria-current="true"{% endif %}>{{ label }}</a>
19
+ {%- endfor %}
20
+ </div>
21
+ </nav>
@@ -0,0 +1,58 @@
1
+ /* Shared styles for the rompy documentation sites. Managed by rompy-docs: do not edit. */
2
+
3
+ /* Bar linking the rompy sites, above the Material header. */
4
+ .rompy-sites {
5
+ background-color: var(--md-primary-fg-color--dark);
6
+ font-size: 0.65rem;
7
+ line-height: 1.8rem;
8
+ }
9
+
10
+ .rompy-sites__inner {
11
+ display: flex;
12
+ flex-wrap: wrap;
13
+ gap: 0 1.2rem;
14
+ padding: 0 0.8rem;
15
+ }
16
+
17
+ .rompy-sites__link,
18
+ .rompy-sites__link:visited {
19
+ color: var(--md-primary-bg-color--light);
20
+ text-decoration: none;
21
+ }
22
+
23
+ .rompy-sites__link:hover {
24
+ color: var(--md-primary-bg-color);
25
+ }
26
+
27
+ .rompy-sites__link--active {
28
+ color: var(--md-primary-bg-color);
29
+ font-weight: 700;
30
+ box-shadow: inset 0 -2px 0 var(--md-accent-fg-color);
31
+ }
32
+
33
+ /* Cards listing notebooks (generated by rompy_docs.notebooks). */
34
+ .rompy-cards {
35
+ display: grid;
36
+ grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr));
37
+ gap: 0.8rem;
38
+ margin: 1em 0;
39
+ }
40
+
41
+ .rompy-card {
42
+ border: 1px solid var(--md-default-fg-color--lightest);
43
+ border-radius: 0.2rem;
44
+ padding: 0.6rem 0.8rem;
45
+ }
46
+
47
+ .rompy-card:hover {
48
+ border-color: var(--md-accent-fg-color);
49
+ }
50
+
51
+ .rompy-card p {
52
+ margin: 0.3em 0;
53
+ }
54
+
55
+ .rompy-card__meta {
56
+ color: var(--md-default-fg-color--light);
57
+ font-size: 0.7rem;
58
+ }
@@ -0,0 +1,95 @@
1
+ # Shared mkdocs.yml settings for the rompy documentation sites.
2
+ #
3
+ # Every site copies these blocks into its mkdocs.yml and adds its own site_name,
4
+ # site_url, repo, nav, `extra.rompy.site` and, for mkdocstrings, `paths` and
5
+ # extra `inventories`. `rompy-docs check` reports where a site differs.
6
+ #
7
+ # Model sites also set `preload_modules: [rompy]` in the mkdocstrings options, so
8
+ # that classes show the fields they inherit from rompy. The rompy site must not:
9
+ # griffe-pydantic skips the models of a preloaded package that is also documented.
10
+
11
+ theme:
12
+ name: material
13
+ custom_dir: docs/overrides
14
+ palette:
15
+ - media: "(prefers-color-scheme: light)"
16
+ scheme: default
17
+ primary: indigo
18
+ accent: indigo
19
+ toggle:
20
+ icon: material/brightness-7
21
+ name: Switch to dark mode
22
+ - media: "(prefers-color-scheme: dark)"
23
+ scheme: slate
24
+ primary: indigo
25
+ accent: indigo
26
+ toggle:
27
+ icon: material/brightness-4
28
+ name: Switch to light mode
29
+ features:
30
+ - navigation.tabs
31
+ - navigation.sections
32
+ - navigation.indexes
33
+ - navigation.top
34
+ - navigation.footer
35
+ - toc.follow
36
+ - search.suggest
37
+ - search.highlight
38
+ - content.code.copy
39
+ - content.code.annotate
40
+ - content.tabs.link
41
+
42
+ extra_css:
43
+ - stylesheets/rompy.css
44
+
45
+ plugins:
46
+ - search
47
+ - markdown-exec
48
+ - mkdocstrings:
49
+ handlers:
50
+ python:
51
+ inventories:
52
+ - https://docs.python.org/3/objects.inv
53
+ - https://docs.pydantic.dev/latest/objects.inv
54
+ options:
55
+ docstring_style: auto # detects numpy or google style per docstring
56
+ docstring_section_style: table
57
+ inherited_members: true
58
+ show_bases: true
59
+ show_root_heading: true
60
+ show_root_full_path: false
61
+ show_symbol_type_heading: true
62
+ show_symbol_type_toc: true
63
+ show_if_no_docstring: true # list every public field and method, documented or not
64
+ show_source: false
65
+ separate_signature: true
66
+ show_signature_annotations: true
67
+ signature_crossrefs: true
68
+ merge_init_into_class: true
69
+ members_order: source
70
+ group_by_category: true
71
+ summary: false
72
+ filters: ["!^_", "!^model_(?!type$)"] # hide pydantic's model_* methods, keep model_type
73
+ extensions:
74
+ - griffe_pydantic: {schema: false}
75
+ - rompy_docs.griffe:PydanticFieldRules
76
+
77
+ markdown_extensions:
78
+ - admonition
79
+ - attr_list
80
+ - md_in_html
81
+ - tables
82
+ - toc:
83
+ permalink: true
84
+ - pymdownx.details
85
+ - pymdownx.highlight:
86
+ anchor_linenums: true
87
+ - pymdownx.inlinehilite
88
+ - pymdownx.snippets
89
+ - pymdownx.superfences:
90
+ custom_fences:
91
+ - name: mermaid
92
+ class: mermaid
93
+ format: !!python/name:pymdownx.superfences.fence_code_format
94
+ - pymdownx.tabbed:
95
+ alternate_style: true
@@ -0,0 +1,55 @@
1
+ """Command line: `rompy-docs sync|check|convert`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from rompy_docs import config, convert
10
+
11
+
12
+ def main(argv: list[str] | None = None) -> int:
13
+ parser = argparse.ArgumentParser(prog="rompy-docs", description=__doc__)
14
+ sub = parser.add_subparsers(dest="command", required=True)
15
+
16
+ p_sync = sub.add_parser("sync", help="copy the shared theme files into a site")
17
+ p_sync.add_argument("-f", "--config-file", type=Path, default=Path("mkdocs.yml"))
18
+
19
+ p_check = sub.add_parser("check", help="compare a site with the shared template")
20
+ p_check.add_argument("-f", "--config-file", type=Path, default=Path("mkdocs.yml"))
21
+
22
+ p_conv = sub.add_parser(
23
+ "convert", help="convert Sphinx directives in docstrings to Markdown fences"
24
+ )
25
+ p_conv.add_argument("paths", nargs="+", type=Path, help="Python files or directories")
26
+ p_conv.add_argument("--check", action="store_true", help="only report files to convert")
27
+
28
+ args = parser.parse_args(argv)
29
+
30
+ if args.command == "sync":
31
+ site = config.load_yaml(args.config_file)
32
+ docs_dir = args.config_file.parent / site.get("docs_dir", "docs")
33
+ for path in config.sync(docs_dir):
34
+ print(f"updated {path}")
35
+ return 0
36
+
37
+ if args.command == "check":
38
+ report = config.check(args.config_file)
39
+ for problem in report.problems:
40
+ print(f"{args.config_file}: {problem}")
41
+ if report.ok:
42
+ print(f"{args.config_file}: matches the rompy-docs template")
43
+ return 0 if report.ok else 1
44
+
45
+ if args.command == "convert":
46
+ changed = convert.convert_paths(args.paths, write=not args.check)
47
+ for path, count in changed:
48
+ print(f"{path}: {count} block(s)")
49
+ return 1 if (args.check and changed) else 0
50
+
51
+ return 2
52
+
53
+
54
+ if __name__ == "__main__":
55
+ sys.exit(main())
@@ -0,0 +1,148 @@
1
+ """Shared site configuration: sync the managed files and check mkdocs.yml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import filecmp
6
+ import shutil
7
+ from dataclasses import dataclass, field
8
+ from importlib import resources
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import yaml
13
+
14
+ SITES = ("rompy", "xbeach", "swan", "schism", "notebooks")
15
+ MODEL_SITES = ("xbeach", "swan", "schism")
16
+
17
+ # Managed files: path in the package assets -> path relative to the site's docs_dir.
18
+ MANAGED_FILES = {
19
+ "overrides/main.html": "overrides/main.html",
20
+ "overrides/partials/rompy-sites.html": "overrides/partials/rompy-sites.html",
21
+ "stylesheets/rompy.css": "stylesheets/rompy.css",
22
+ }
23
+
24
+
25
+ class _Loader(yaml.SafeLoader):
26
+ """YAML loader that keeps the `!!python/...` tags used in mkdocs.yml as strings."""
27
+
28
+
29
+ def _python_tag(loader, suffix, node):
30
+ return f"!!python/{suffix}:{node.value}" if isinstance(node, yaml.ScalarNode) else None
31
+
32
+
33
+ _Loader.add_multi_constructor("tag:yaml.org,2002:python/", _python_tag)
34
+ _Loader.add_multi_constructor("!", lambda loader, suffix, node: None)
35
+
36
+
37
+ def load_yaml(path: Path | str) -> dict[str, Any]:
38
+ with open(path) as stream:
39
+ return yaml.load(stream, Loader=_Loader) or {}
40
+
41
+
42
+ def assets() -> Path:
43
+ return Path(str(resources.files("rompy_docs") / "assets"))
44
+
45
+
46
+ def template() -> dict[str, Any]:
47
+ return load_yaml(assets() / "template.yml")
48
+
49
+
50
+ def sync(docs_dir: Path) -> list[Path]:
51
+ """Copy the managed files into a site's docs_dir, returning the files changed."""
52
+ changed = []
53
+ for source, target in MANAGED_FILES.items():
54
+ src = assets() / source
55
+ dst = docs_dir / target
56
+ if dst.exists() and filecmp.cmp(src, dst, shallow=False):
57
+ continue
58
+ dst.parent.mkdir(parents=True, exist_ok=True)
59
+ shutil.copyfile(src, dst)
60
+ changed.append(dst)
61
+ return changed
62
+
63
+
64
+ def _named(items: list) -> dict[str, Any]:
65
+ """Map a mkdocs list of plugins or extensions to {name: config}."""
66
+ out = {}
67
+ for item in items or []:
68
+ if isinstance(item, str):
69
+ out[item] = {}
70
+ else:
71
+ ((name, conf),) = item.items()
72
+ out[name] = conf or {}
73
+ return out
74
+
75
+
76
+ @dataclass
77
+ class Report:
78
+ problems: list[str] = field(default_factory=list)
79
+
80
+ def add(self, message: str) -> None:
81
+ self.problems.append(message)
82
+
83
+ @property
84
+ def ok(self) -> bool:
85
+ return not self.problems
86
+
87
+
88
+ def check(config_file: Path) -> Report:
89
+ """Compare a site's mkdocs.yml and managed files with the shared template."""
90
+ report = Report()
91
+ site = load_yaml(config_file)
92
+ tmpl = template()
93
+ docs_dir = config_file.parent / site.get("docs_dir", "docs")
94
+
95
+ rompy = (site.get("extra") or {}).get("rompy") or {}
96
+ key = rompy.get("site")
97
+ if key not in SITES:
98
+ report.add(f"extra.rompy.site must be one of {', '.join(SITES)} (got {key!r})")
99
+
100
+ theme, ttheme = site.get("theme") or {}, tmpl["theme"]
101
+ for name in ("name", "custom_dir", "palette"):
102
+ if theme.get(name) != ttheme[name]:
103
+ report.add(f"theme.{name} differs from the template")
104
+ missing = [f for f in ttheme["features"] if f not in (theme.get("features") or [])]
105
+ if missing:
106
+ report.add(f"theme.features missing: {', '.join(missing)}")
107
+
108
+ for css in tmpl["extra_css"]:
109
+ if css not in (site.get("extra_css") or []):
110
+ report.add(f"extra_css missing: {css}")
111
+
112
+ plugins, tplugins = _named(site.get("plugins")), _named(tmpl["plugins"])
113
+ for name in tplugins:
114
+ if name not in plugins:
115
+ report.add(f"plugin missing: {name}")
116
+ if "mkdocs-jupyter" in plugins and key != "notebooks":
117
+ report.add("mkdocs-jupyter is only used on the notebooks site")
118
+
119
+ python = (((plugins.get("mkdocstrings") or {}).get("handlers") or {}).get("python")) or {}
120
+ tpython = tplugins["mkdocstrings"]["handlers"]["python"]
121
+ options = python.get("options") or {}
122
+ for name, value in tpython["options"].items():
123
+ if options.get(name) != value:
124
+ report.add(f"mkdocstrings option {name}: {options.get(name)!r} != {value!r}")
125
+ preload = options.get("preload_modules")
126
+ if key == "rompy" and preload:
127
+ report.add("the rompy site must not preload rompy (griffe-pydantic then skips its models)")
128
+ elif key in MODEL_SITES and "rompy" not in (preload or []):
129
+ report.add("model sites must set preload_modules: [rompy] to show inherited fields")
130
+ inventories = [i if isinstance(i, str) else i.get("url") for i in python.get("inventories") or []]
131
+ for inv in tpython["inventories"]:
132
+ if inv not in inventories:
133
+ report.add(f"mkdocstrings inventory missing: {inv}")
134
+
135
+ extensions, textensions = _named(site.get("markdown_extensions")), _named(tmpl["markdown_extensions"])
136
+ for name, value in textensions.items():
137
+ if name not in extensions:
138
+ report.add(f"markdown extension missing: {name}")
139
+ elif value and extensions[name] != value:
140
+ report.add(f"markdown extension {name} settings differ from the template")
141
+
142
+ for source, target in MANAGED_FILES.items():
143
+ dst = docs_dir / target
144
+ if not dst.exists():
145
+ report.add(f"managed file missing: {dst} (run rompy-docs sync)")
146
+ elif not filecmp.cmp(assets() / source, dst, shallow=False):
147
+ report.add(f"managed file out of date: {dst} (run rompy-docs sync)")
148
+ return report
@@ -0,0 +1,121 @@
1
+ """Convert Sphinx code directives in docstrings to Markdown fences.
2
+
3
+ * ``.. ipython:: python`` becomes an executed markdown-exec fence, so the code runs
4
+ when the docs are built and its printed output is shown below it. Top-level bare
5
+ expressions are wrapped in ``print()``, since IPython showed their values
6
+ (``:verbatim:`` blocks become plain Python fences);
7
+ * ``.. code-block:: <lang>`` becomes a plain ``<lang>`` fence.
8
+
9
+ The fences keep the directive's indentation, so they stay inside the docstring
10
+ section (e.g. numpy ``Examples``) they were written in.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ import re
17
+ from pathlib import Path
18
+
19
+ DIRECTIVE = re.compile(r"^(?P<indent>[ \t]*)\.\. (?P<name>ipython|code-block|code)::[ \t]*(?P<arg>\S*)[ \t]*$")
20
+ OPTION = re.compile(r"^[ \t]*:(?P<name>[\w-]+):")
21
+ DEFINITION = re.compile(r"^[ \t]*(?:async[ \t]+)?(?:def|class)[ \t]+(?P<name>\w+)")
22
+
23
+ EXEC_FENCE = '```python exec="on" source="above" result="text" session="{session}"'
24
+
25
+
26
+ def _indent(line: str) -> int:
27
+ return len(line) - len(line.lstrip())
28
+
29
+
30
+ def _echo_expressions(code: str) -> str:
31
+ """Wrap top-level bare expressions in print(), as IPython shows their values.
32
+
33
+ markdown-exec shows what the code prints, while the ipython directive also
34
+ showed the value of each bare expression. Calls to print are left alone.
35
+ """
36
+ try:
37
+ tree = ast.parse(code)
38
+ except SyntaxError:
39
+ return code
40
+ lines = code.splitlines(keepends=True)
41
+ for node in reversed(tree.body):
42
+ if not isinstance(node, ast.Expr) or isinstance(node.value, ast.Constant):
43
+ continue
44
+ call = node.value
45
+ if isinstance(call, ast.Call) and isinstance(call.func, ast.Name) and call.func.id == "print":
46
+ continue
47
+ first, last = node.lineno - 1, node.end_lineno - 1
48
+ start, end = node.col_offset, node.end_col_offset
49
+ lines[last] = lines[last][:end] + ")" + lines[last][end:]
50
+ lines[first] = lines[first][:start] + "print(" + lines[first][start:]
51
+ return "".join(lines)
52
+
53
+
54
+ def convert_text(text: str, module: str = "doc") -> tuple[str, int]:
55
+ """Return the converted text and the number of directives converted."""
56
+ lines = text.splitlines(keepends=True)
57
+ out: list[str] = []
58
+ count = 0
59
+ owner = module
60
+ i = 0
61
+ while i < len(lines):
62
+ line = lines[i]
63
+ definition = DEFINITION.match(line)
64
+ if definition:
65
+ owner = definition["name"]
66
+ match = DIRECTIVE.match(line.rstrip("\n"))
67
+ if not match:
68
+ out.append(line)
69
+ i += 1
70
+ continue
71
+
72
+ indent = match["indent"]
73
+ base = _indent(line)
74
+ i += 1
75
+ options = set()
76
+ while i < len(lines) and lines[i].strip() and _indent(lines[i]) > base and OPTION.match(lines[i]):
77
+ options.add(OPTION.match(lines[i])["name"])
78
+ i += 1
79
+ body: list[str] = []
80
+ while i < len(lines) and (not lines[i].strip() or _indent(lines[i]) > base):
81
+ body.append(lines[i])
82
+ i += 1
83
+ while body and not body[-1].strip():
84
+ body.pop()
85
+ while body and not body[0].strip():
86
+ body.pop(0)
87
+ dedent = min((_indent(b) for b in body if b.strip()), default=0)
88
+
89
+ if match["name"] == "ipython" and "verbatim" not in options:
90
+ fence = EXEC_FENCE.format(session=f"{module}-{owner}".lower())
91
+ code = _echo_expressions("".join(b[dedent:] if b.strip() else "\n" for b in body))
92
+ body = code.splitlines(keepends=True)
93
+ dedent = 0
94
+ else:
95
+ lang = "python" if match["name"] == "ipython" else (match["arg"] or "text")
96
+ fence = f"```{lang}"
97
+ out.append(f"{indent}{fence}\n")
98
+ for b in body:
99
+ out.append(f"{indent}{b[dedent:]}" if b.strip() else "\n")
100
+ out.append(f"{indent}```\n")
101
+ # Keep a blank line after the block when the source had one.
102
+ if i < len(lines) and lines[i].strip():
103
+ out.append("\n")
104
+ count += 1
105
+ return "".join(out), count
106
+
107
+
108
+ def convert_paths(paths: list[Path], write: bool = True) -> list[tuple[Path, int]]:
109
+ """Convert every Python file under `paths`, returning (file, blocks) changed."""
110
+ files: list[Path] = []
111
+ for path in paths:
112
+ files.extend(sorted(path.rglob("*.py")) if path.is_dir() else [path])
113
+ changed = []
114
+ for file in files:
115
+ text = file.read_text()
116
+ new, count = convert_text(text, module=file.stem)
117
+ if count:
118
+ changed.append((file, count))
119
+ if write:
120
+ file.write_text(new)
121
+ return changed
@@ -0,0 +1,61 @@
1
+ """Griffe extensions for the rompy documentation sites.
2
+
3
+ Use them in `mkdocs.yml` after `griffe_pydantic`::
4
+
5
+ extensions:
6
+ - griffe_pydantic: {schema: false}
7
+ - rompy_docs.griffe:PydanticFieldRules
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import griffe
13
+
14
+ FIELD_LABEL = "pydantic-field"
15
+ MODEL_LABEL = "pydantic-model"
16
+
17
+
18
+ def is_pydantic_field(name: str, annotation) -> bool:
19
+ """Apply pydantic's rules for which class attributes are model fields.
20
+
21
+ Pydantic never treats a name starting with an underscore as a field, nor an
22
+ attribute without an annotation.
23
+ """
24
+ return not name.startswith("_") and annotation is not None
25
+
26
+
27
+ class PydanticFieldRules(griffe.Extension):
28
+ """Remove the pydantic field label from attributes that are not fields.
29
+
30
+ In static mode, griffe-pydantic 1.3.1 labels every attribute of a model as a
31
+ field, including private attributes, dunder attributes and attributes without
32
+ an annotation (e.g. ``_validate_crs = field_validator(...)(...)``). With
33
+ ``inherited_members`` and ``preload_modules`` this pulls attributes from rompy
34
+ base classes into the fields list, and their missing annotation breaks the
35
+ griffe-pydantic template.
36
+ """
37
+
38
+ def on_package(self, *, pkg: griffe.Module, **kwargs) -> None:
39
+ self._walk(pkg)
40
+
41
+ def _walk(self, obj: griffe.Object) -> None:
42
+ for member in list(obj.members.values()):
43
+ if member.is_alias:
44
+ continue
45
+ if member.is_class:
46
+ if MODEL_LABEL in member.labels:
47
+ self._clean(member)
48
+ self._walk(member)
49
+ elif member.is_module:
50
+ self._walk(member)
51
+
52
+ @staticmethod
53
+ def _clean(cls: griffe.Class) -> None:
54
+ for name, attr in cls.all_members.items():
55
+ try:
56
+ labels = attr.labels
57
+ annotation = attr.annotation if attr.is_attribute else None
58
+ except griffe.AliasResolutionError:
59
+ continue
60
+ if FIELD_LABEL in labels and not is_pydantic_field(name, annotation):
61
+ labels.discard(FIELD_LABEL)
@@ -0,0 +1,98 @@
1
+ """Link the rompy-notebooks collection from the package documentation sites.
2
+
3
+ The notebooks are rendered once, on the rompy-notebooks site. Package sites list
4
+ them with these helpers, called from markdown-exec blocks, e.g.::
5
+
6
+ ```python exec="on" html="1"
7
+ from rompy_docs.notebooks import cards
8
+ print(cards("xbeach", kind="example"))
9
+ ```
10
+
11
+ The list comes from the inventory the notebook site publishes, so it follows the
12
+ collection without copying notebooks. Set ``ROMPY_NOTEBOOKS_INVENTORY`` to a local
13
+ file or another URL to build against an unpublished collection.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ from functools import lru_cache
22
+ from html import escape
23
+ from pathlib import Path
24
+ from urllib.request import urlopen
25
+
26
+ SITE_URL = "https://rom-py.github.io/rompy-notebooks/"
27
+ INVENTORY_URL = SITE_URL + "generated/notebook-inventory.json"
28
+ LEVELS = {"beginner": 0, "intermediate": 1, "advanced": 2}
29
+
30
+
31
+ @lru_cache
32
+ def load_inventory(source: str | None = None) -> tuple[dict, ...]:
33
+ """Return the published notebooks in the inventory."""
34
+ source = source or os.environ.get("ROMPY_NOTEBOOKS_INVENTORY") or INVENTORY_URL
35
+ if re.match(r"^https?://", source):
36
+ with urlopen(source, timeout=30) as response:
37
+ payload = json.load(response)
38
+ else:
39
+ payload = json.loads(Path(source).read_text())
40
+ return tuple(r for r in payload["notebooks"] if r.get("published", True))
41
+
42
+
43
+ def notebook_url(record: dict) -> str:
44
+ """URL of a notebook on the rompy-notebooks site."""
45
+ return SITE_URL + record["path"].removesuffix(".ipynb") + "/"
46
+
47
+
48
+ def title(record: dict) -> str:
49
+ """Notebook title, from the inventory or else from the file name."""
50
+ if record.get("title"):
51
+ return record["title"]
52
+ stem = Path(record["path"]).stem
53
+ stem = re.sub(r"^\d+_", "", stem).replace("_", " ")
54
+ return stem[:1].upper() + stem[1:]
55
+
56
+
57
+ def select(model: str, kind: str | None = None, topics: list[str] | None = None) -> list[dict]:
58
+ """Notebooks for a model, optionally of one kind or sharing any of `topics`."""
59
+ records = [r for r in load_inventory() if r["model"] == model]
60
+ if kind:
61
+ records = [r for r in records if r["kind"] == kind]
62
+ if topics:
63
+ records = [r for r in records if set(topics) & set(r.get("topics", []))]
64
+ return sorted(
65
+ records,
66
+ key=lambda r: (r["kind"] != "tutorial", r.get("tutorial", 0), LEVELS.get(r["level"], 9), title(r)),
67
+ )
68
+
69
+
70
+ def tutorial_table(model: str) -> str:
71
+ """Markdown table of the ordered tutorial lessons for a model."""
72
+ lines = ["| # | Lesson | Level |", "|---|---|---|"]
73
+ for r in select(model, kind="tutorial"):
74
+ lines.append(f"| {r.get('tutorial', '')} | [{title(r)}]({notebook_url(r)}) | {r['level']} |")
75
+ return "\n".join(lines)
76
+
77
+
78
+ def cards(model: str, kind: str | None = None, topics: list[str] | None = None) -> str:
79
+ """HTML cards for notebooks (print from a markdown-exec block with html="1")."""
80
+ items = []
81
+ for r in select(model, kind=kind, topics=topics):
82
+ summary = f"<p>{escape(r['summary'])}</p>" if r.get("summary") else ""
83
+ meta = " · ".join([r["kind"], r["level"], *r.get("topics", [])])
84
+ items.append(
85
+ f'<a class="rompy-card" href="{notebook_url(r)}">'
86
+ f"<p><strong>{escape(title(r))}</strong></p>{summary}"
87
+ f'<p class="rompy-card__meta">{escape(meta)}</p></a>'
88
+ )
89
+ return '<div class="rompy-cards">' + "".join(items) + "</div>"
90
+
91
+
92
+ def see_also(model: str, topics: list[str]) -> str:
93
+ """Markdown admonition linking the notebooks on `topics`."""
94
+ records = select(model, topics=topics)
95
+ if not records:
96
+ raise ValueError(f"No {model} notebooks on topics {topics}")
97
+ links = "\n".join(f" - [{title(r)}]({notebook_url(r)}) ({r['kind']})" for r in records)
98
+ return f'!!! example "See it in the notebooks"\n\n{links}\n'
@@ -0,0 +1,71 @@
1
+ from rompy_docs.convert import convert_text
2
+
3
+ SWAN_STYLE = '''
4
+ class GEN3(BaseComponent):
5
+ """Third generation physics.
6
+
7
+ .. code-block:: text
8
+
9
+ GEN3 [source_terms]
10
+
11
+ Examples
12
+ --------
13
+
14
+ .. ipython:: python
15
+ :okwarning:
16
+
17
+ from rompy_swan.components.physics import GEN3
18
+ gen = GEN3()
19
+ print(gen.render())
20
+
21
+ """
22
+ '''
23
+
24
+
25
+ def test_ipython_becomes_exec_fence():
26
+ text, count = convert_text(SWAN_STYLE, module="physics")
27
+ assert count == 2
28
+ assert ' ```python exec="on" source="above" result="text" session="physics-gen3"\n' in text
29
+ assert " from rompy_swan.components.physics import GEN3\n gen = GEN3()\n" in text
30
+ assert ":okwarning:" not in text
31
+ assert ".. ipython" not in text
32
+
33
+
34
+ def test_code_block_becomes_plain_fence():
35
+ text, _ = convert_text(SWAN_STYLE, module="physics")
36
+ assert " ```text\n GEN3 [source_terms]\n ```\n" in text
37
+ assert ".. code-block" not in text
38
+
39
+
40
+ def test_verbatim_is_not_executed():
41
+ src = " .. ipython:: python\n :verbatim:\n\n run_model()\n"
42
+ text, count = convert_text(src)
43
+ assert count == 1
44
+ assert text == " ```python\n run_model()\n ```\n"
45
+
46
+
47
+ def test_text_without_directives_is_unchanged():
48
+ src = 'def f():\n """Nothing here."""\n'
49
+ assert convert_text(src) == (src, 0)
50
+
51
+
52
+ def test_block_followed_by_text_keeps_a_blank_line():
53
+ src = " .. code-block:: text\n\n A B\n Next paragraph.\n"
54
+ text, _ = convert_text(src)
55
+ assert text == " ```text\n A B\n ```\n\n Next paragraph.\n"
56
+
57
+
58
+ def test_bare_expressions_are_printed():
59
+ src = (
60
+ " .. ipython:: python\n\n"
61
+ " from x import F\n"
62
+ " f = F()\n"
63
+ " f\n"
64
+ " f.render(\n indent=2,\n )\n"
65
+ " print(f)\n"
66
+ " \"a string\"\n"
67
+ )
68
+ text, _ = convert_text(src)
69
+ assert " f = F()\n print(f)\n" in text
70
+ assert " print(f.render(\n indent=2,\n ))\n" in text
71
+ assert " print(f)\n \"a string\"\n" in text
@@ -0,0 +1,48 @@
1
+ import griffe
2
+ import pytest
3
+
4
+ pytest.importorskip("griffe_pydantic")
5
+
6
+ BASE = '''
7
+ from pydantic import BaseModel, Field, field_validator
8
+
9
+
10
+ class Base(BaseModel):
11
+ """Base."""
12
+
13
+ source: str = Field(description="Where the data come from.")
14
+
15
+ def __init__(self, **data):
16
+ super().__init__(**data)
17
+ self._original_inputs = data
18
+ '''
19
+
20
+ CHILD = '''
21
+ from pydantic import Field, field_validator
22
+ from base_pkg import Base
23
+
24
+
25
+ class Child(Base):
26
+ """Child."""
27
+
28
+ dx: float = Field(1.0, description="Spacing.")
29
+ _check = field_validator("dx")(lambda cls, v: v)
30
+ '''
31
+
32
+
33
+ def test_inherited_fields_without_private_attributes(tmp_path):
34
+ (tmp_path / "base_pkg").mkdir()
35
+ (tmp_path / "base_pkg" / "__init__.py").write_text(BASE)
36
+ (tmp_path / "child_pkg").mkdir()
37
+ (tmp_path / "child_pkg" / "__init__.py").write_text(CHILD)
38
+
39
+ extensions = griffe.load_extensions(
40
+ {"griffe_pydantic": {"schema": False}}, "rompy_docs.griffe:PydanticFieldRules"
41
+ )
42
+ loader = griffe.GriffeLoader(extensions=extensions, search_paths=[str(tmp_path)])
43
+ loader.load("base_pkg")
44
+ child = loader.load("child_pkg")
45
+ loader.resolve_aliases(external=True, implicit=False)
46
+
47
+ fields = child["Child"].extra["griffe_pydantic"]["fields"]()
48
+ assert list(fields) == ["source", "dx"]
@@ -0,0 +1,58 @@
1
+ import json
2
+
3
+ import pytest
4
+
5
+ from rompy_docs import notebooks
6
+
7
+
8
+ @pytest.fixture(autouse=True)
9
+ def inventory(tmp_path, monkeypatch):
10
+ records = [
11
+ {"path": "notebooks/xbeach/tutorial/02_model_grid.ipynb", "model": "xbeach", "kind": "tutorial",
12
+ "tutorial": 2, "level": "beginner", "topics": ["grid"], "published": True},
13
+ {"path": "notebooks/xbeach/tutorial/01_first_model.ipynb", "model": "xbeach", "kind": "tutorial",
14
+ "tutorial": 1, "level": "beginner", "topics": ["workflow"], "published": True},
15
+ {"path": "notebooks/xbeach/examples/wind.ipynb", "model": "xbeach", "kind": "example",
16
+ "level": "intermediate", "topics": ["wind", "forcing"], "published": True,
17
+ "title": "Wind forcing", "summary": "Wind <from> a reanalysis."},
18
+ {"path": "notebooks/xbeach/examples/draft.ipynb", "model": "xbeach", "kind": "example",
19
+ "level": "advanced", "topics": ["wind"], "published": False, "exclusion_reason": "draft"},
20
+ {"path": "notebooks/swan/examples/wind.ipynb", "model": "swan", "kind": "example",
21
+ "level": "beginner", "topics": ["wind"], "published": True},
22
+ ]
23
+ path = tmp_path / "inventory.json"
24
+ path.write_text(json.dumps({"version": 1, "notebooks": records}))
25
+ monkeypatch.setenv("ROMPY_NOTEBOOKS_INVENTORY", str(path))
26
+ notebooks.load_inventory.cache_clear()
27
+ yield
28
+ notebooks.load_inventory.cache_clear()
29
+
30
+
31
+ def test_url_and_title():
32
+ record = notebooks.select("xbeach", kind="tutorial")[0]
33
+ assert notebooks.notebook_url(record) == (
34
+ "https://rom-py.github.io/rompy-notebooks/notebooks/xbeach/tutorial/01_first_model/"
35
+ )
36
+ assert notebooks.title(record) == "First model"
37
+
38
+
39
+ def test_tutorial_table_is_ordered():
40
+ table = notebooks.tutorial_table("xbeach")
41
+ assert table.index("First model") < table.index("Model grid")
42
+
43
+
44
+ def test_cards_skip_unpublished_and_escape():
45
+ html = notebooks.cards("xbeach", kind="example")
46
+ assert "Draft" not in html
47
+ assert "Wind forcing" in html and "Wind &lt;from&gt; a reanalysis." in html
48
+
49
+
50
+ def test_see_also_by_topic():
51
+ box = notebooks.see_also("xbeach", ["wind"])
52
+ assert box.startswith('!!! example "See it in the notebooks"')
53
+ assert "[Wind forcing](" in box and "swan" not in box
54
+
55
+
56
+ def test_see_also_without_matches_raises():
57
+ with pytest.raises(ValueError):
58
+ notebooks.see_also("xbeach", ["sediment"])