📚 automatic_docs#
Documentation generation utilities.
This subpackage provides a comprehensive set of utilities for automatically generating and managing Sphinx or Zensical documentation for Python projects. It handles the creation of configuration files, index pages, version management, and HTML generation.
Example of usage:
import stouputils as stp
from stouputils.applications import automatic_docs
if __name__ == "__main__":
automatic_docs.sphinx_docs(
root_path=stp.get_root_path(__file__, go_up=1),
project="stouputils",
author="Stoupy",
copyright="2025, Stoupy",
html_logo="https://avatars.githubusercontent.com/u/35665974",
html_favicon="https://avatars.githubusercontent.com/u/35665974",
html_theme="breeze", # Available themes: breeze, furo, pydata_sphinx_theme, sphinx_rtd_theme, or other you installed
github_user="Stoupy51",
github_repo="stouputils",
version="1.2.0",
skip_undocumented=True,
)
Example of GitHub Actions workflow:
name: documentation
on:
push:
tags:
- 'v*'
workflow_dispatch:
permissions:
contents: write
jobs:
docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- name: Install dependencies
run: |
pip install stouputils[docs,data_science]
- name: Build version docs
run: |
python scripts/create_docs.py ${GITHUB_REF#refs/tags/v}
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
publish_branch: gh-pages
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: docs/build/html
keep_files: true
force_orphan: false
common#
Common utilities shared by documentation generators (Sphinx, Zensical, etc.).
This module contains functions and helpers that are used by multiple documentation backends, avoiding code duplication.
- check_base_dependencies() None[source]#
Check for each auto-docs requirement if it is installed.
- Raises:
ImportError – If any requirement from
Cfg.AUTO_DOCS_REQUIREMENTSis not installed
- download_asset(url: str, target_path: str) None[source]#
Download a file from a URL to a local path.
- Parameters:
url – URL to download from
target_path – Local file path to save to
- get_versions_from_github(
- github_user: str,
- github_repo: str,
- recent_minor_versions: int = 2,
Get list of versions from GitHub gh-pages branch. Only shows detailed versions for the last N minor versions, and keeps only the latest patch version for older minor versions.
- Parameters:
github_user – GitHub username
github_repo – GitHub repository name
recent_minor_versions – Number of recent minor versions to show all patches for (-1 for all).
- Returns:
List of versions, with ‘latest’ as first element
- keep_recent_patches(
- versions: list[str],
- recent_minor_versions: int,
Every patch of the most recent minor versions, then only the latest patch of each older minor version.
- Parameters:
versions – Versions sorted newest first, such as
"1.3.1".recent_minor_versions – Number of minor versions keeping all their patches, -1 for all of them.
- generate_version_selector(github_user: str, github_repo: str, get_versions_function: ~collections.abc.Callable[[str, str, int], list[str]] = <functools._lru_cache_wrapper object>, recent_minor_versions: int = 2) str[source]#
Generate the HTML version selector string from GitHub versions.
- Parameters:
github_user – GitHub username
github_repo – GitHub repository name
get_versions_function – Function to get versions from GitHub
recent_minor_versions – Number of recent minor versions to show all patches for. Defaults to 2
- Returns:
Markdown string with version links (e.g.
**Versions**: latest, v1.0.0, ...), empty when no version is known
docstring#
Docstring normalization applied before Sphinx parses the output of autodoc.
reStructuredText only recognizes a doctest block when it starts a new block, which means a blank line
must separate it from the prose introducing it.
A docstring written without that blank line gets folded into the preceding paragraph,
so the >>> lines render as plain text (smart quotes included) instead of a highlighted code block.
fix_doctest_blocks() inserts the missing blank lines and connect_docstring_fixes() wires it
to the autodoc-process-docstring event, so the fix applies to every documented object at once.
- VERBATIM_DIRECTIVES: frozenset[str] = frozenset({'code', 'code-block', 'doctest', 'literalinclude', 'math', 'parsed-literal', 'raw', 'sourcecode', 'testcleanup', 'testcode', 'testsetup'})[source]#
Directives whose body is taken verbatim, so
>>>lines inside them must be left untouched.
- DIRECTIVE_PATTERN: Pattern[str] = re.compile('^\\.\\.[ \\t]+([\\w-]+)::')[source]#
Matches the opening line of a reStructuredText directive, capturing its name.
- fix_doctest_blocks(lines: list[str]) list[str][source]#
Insert the blank line reStructuredText needs before a doctest block that follows prose.
Lines inside a verbatim region (a literal block introduced by
::or a directive fromVERBATIM_DIRECTIVES) are copied as-is, since their>>>already renders correctly and an extra blank line would truncate the block.- Parameters:
lines – Docstring lines, without trailing newlines
- Returns:
The same lines with a blank line before every doctest block that lacked one
>>> fix_doctest_blocks(["Building resource locations", ">>> 1 + 1", "2"]) ['Building resource locations', '', '>>> 1 + 1', '2']
>>> fix_doctest_blocks(["Already fine", "", ">>> 1 + 1", "2"]) ['Already fine', '', '>>> 1 + 1', '2']
>>> fix_doctest_blocks([">>> a = 1", ">>> a", "1"]) ['>>> a = 1', '>>> a', '1']
>>> fix_doctest_blocks(["Intro:", "", ">>> 1", "1", ">>> 2", "2"]) ['Intro:', '', '>>> 1', '1', '>>> 2', '2']
>>> fix_doctest_blocks([".. code-block:: python", "", " Header", " >>> 1 + 1"]) ['.. code-block:: python', '', ' Header', ' >>> 1 + 1']
>>> fix_doctest_blocks(["Sample::", "", " Header", " >>> 1 + 1"]) ['Sample::', '', ' Header', ' >>> 1 + 1']
- opens_verbatim(stripped: str) bool[source]#
Whether a stripped docstring line opens a verbatim region, with a trailing
::or a directive fromVERBATIM_DIRECTIVES.>>> opens_verbatim("Sample::"), opens_verbatim(".. code-block:: python"), opens_verbatim("Plain prose.") (True, True, False)
- leading_emoji(text: str | None) str[source]#
The emoji a text opens with, empty when it opens with anything else.
>>> leading_emoji("🖨️ Printing helpers"), leading_emoji("Printing helpers"), leading_emoji(None) ('🖨️', '', '')
- process_docstring(
- app: Any,
- what: str,
- name: str,
- obj: Any,
- options: Any,
- lines: list[str],
Handler for the
autodoc-process-docstringevent, editinglinesin place as Sphinx requires.The emoji opening a module docstring is dropped, since the title of the module’s page or section already shows it.
- Parameters:
what – The type of the documented object
lines – Docstring lines, modified in place
>>> lines = ["Intro", ">>> 1 + 1", "2"] >>> process_docstring(None, "class", "Demo", None, None, lines) >>> lines ['Intro', '', '>>> 1 + 1', '2'] >>> lines = ["📝 Typing helpers"] >>> process_docstring(None, "module", "typing", None, None, lines) >>> lines ['Typing helpers']
- keep_attribute_docstring_whole(
- app: Any,
- what: str,
- name: str,
- obj: Any,
- options: Any,
- lines: list[str],
Handler for
autodoc-process-docstringkeeping napoleon from reading a type out of an attribute docstring.Napoleon takes whatever precedes the first colon of an attribute docstring as its type,
minecraftin “The ore item,minecraft:emerald”. A leading colon gives it an empty type, and the whole line as description.- Parameters:
what – The type of the documented object
lines – Docstring lines, modified in place
>>> lines = ["The ore item, `minecraft:emerald`"] >>> keep_attribute_docstring_whole(None, "data", "ORE", None, None, lines) >>> lines [': The ore item, `minecraft:emerald`']
- connect_docstring_fixes(app: Any) None[source]#
Register the docstring fixes on a Sphinx application.
keep_attribute_docstring_whole()runs before napoleon, andprocess_docstring()after it, once the Google style sections are expanded into the reStructuredText that actually gets parsed.- Parameters:
app – The Sphinx application to connect the handlers to
zensical#
Zensical documentation generation utilities.
This module provides a comprehensive set of utilities for automatically generating and managing documentation for Python projects using Zensical (a modern static site generator based on MkDocs Material) and mkdocstrings for API reference generation from docstrings.
It handles the creation of configuration files, index pages, API reference pages, version management, and HTML generation.
Example of usage:
import stouputils as stp
from stouputils.applications import automatic_docs
if __name__ == "__main__":
automatic_docs.zensical_docs(
root_path=stp.get_root_path(__file__, go_up=1),
project="stouputils",
author="Stoupy",
copyright="2025, Stoupy",
html_logo="https://avatars.githubusercontent.com/u/35665974",
html_favicon="https://avatars.githubusercontent.com/u/35665974",
github_user="Stoupy51",
github_repo="stouputils",
version="1.2.0",
skip_undocumented=True,
)
- get_zensical_config_content(
- project: str,
- project_dir: str,
- docs_dir: str,
- site_dir: str,
- author: str,
- current_version: str,
- copyright: str,
- html_logo: str,
- html_favicon: str,
- github_user: str = '',
- github_repo: str = '',
- version_list: list[str] | None = None,
- skip_undocumented: bool = True,
- api_pages: list[tuple[str, str]] | None = None,
Get the content of the Zensical configuration file (zensical.toml).
- Parameters:
project – Name of the project
project_dir – Path to the project directory
docs_dir – Path to the docs source directory (relative to root)
site_dir – Path to the build output directory (relative to root)
author – Author of the project
current_version – Current version
copyright – Copyright information
html_logo – Path to the logo image (relative to docs_dir)
html_favicon – Path to the favicon image (relative to docs_dir)
github_user – GitHub username
github_repo – GitHub repository name
version_list – List of versions. Defaults to None
skip_undocumented – Whether to skip undocumented members. Defaults to True
api_pages – List of (module_name, md_filename) tuples for nav
- Returns:
Content of the Zensical configuration file (TOML)
- generate_index_md(readme_path: str, index_path: str, project: str, github_user: str, github_repo: str, get_versions_function: ~collections.abc.Callable[[str, str, int], list[str]] = <functools._lru_cache_wrapper object>, recent_minor_versions: int = 2) None[source]#
Generate
index.mdfrom README.md content.This keeps the README content as Markdown and creates the home page for the Zensical documentation. Navigation to API docs is handled by the Zensical config (nav or auto-discovery).
- Parameters:
readme_path – Path to the README.md file
index_path – Path where index.md should be created
project – Name of the project
github_user – GitHub username
github_repo – GitHub repository name
get_versions_function – Function to get versions from GitHub
recent_minor_versions – Number of recent minor versions to show all patches for. Defaults to 2
- generate_api_pages(
- api_dir: str,
- project: str,
- project_dir: str,
Walk the project directory and generate Markdown pages with
:::directives for mkdocstrings API documentation.- Parameters:
api_dir – Directory where API markdown pages should be written
project – Name of the project (package name)
project_dir – Path to the project directory (Python package root)
- Returns:
List of (module_name, md_filename) tuples
- generate_documentation(
- config_path: str,
- root_path: str,
Generate documentation using Zensical.
- Parameters:
config_path – Path to the zensical.toml configuration file
root_path – Root path of the project (working directory for the build)
- zensical_docs(root_path: str, project: str, project_dir: str = '', author: str = 'Author', copyright: str = '2025, Author', html_logo: str = '', html_favicon: str = '', html_theme: str = '', github_user: str = '', github_repo: str = '', version: str | None = None, skip_undocumented: bool = True, recent_minor_versions: int = 2, get_versions_function: ~collections.abc.Callable[[str, str, int], list[str]] = <functools._lru_cache_wrapper object>, generate_index_function: ~collections.abc.Callable[[...], None] = <function generate_index_md>, generate_api_pages_function: ~collections.abc.Callable[[...], list[tuple[str, str]]] = <function generate_api_pages>, generate_docs_function: ~collections.abc.Callable[[...], None] = <function generate_documentation>, generate_redirect_function: ~collections.abc.Callable[[str], None] = <function generate_redirect_html>, get_config_content_function: ~collections.abc.Callable[[...], str] = <function get_zensical_config_content>) None[source]#
Update the documentation using Zensical and mkdocstrings.
- Parameters:
root_path – Root path of the project
project – Name of the project
project_dir – Path to the project directory (to be used with generate_docs_function)
author – Author of the project
copyright – Copyright information
html_logo – URL or path to the logo image
html_favicon – URL or path to the favicon image
html_theme – Unused (kept for backward compatibility)
github_user – GitHub username
github_repo – GitHub repository name
version – Version to build documentation for (e.g. “1.0.0”, defaults to “latest”)
skip_undocumented – Whether to skip undocumented members. Defaults to True
recent_minor_versions – Number of recent minor versions to show all patches for. Defaults to 2
get_versions_function – Function to get versions from GitHub
generate_index_function – Function to generate index.md
generate_api_pages_function – Function to generate API pages
generate_docs_function – Function to generate documentation
generate_redirect_function – Function to create redirect file
get_config_content_function – Function to get Zensical config content