chore(release): 0.0.7

Squash-merge lib-standardisation: adopt repo standards across packaging,
tooling, docs, and CI.

- standardize pyproject.toml (canonical packaging, lint config, extras, GSDFC pydoclint)
- add py.typed marker, modernize type hints and Google-style docstrings
- nest generated docs under docs/lib and docs/mcp; add hand-written wiki
- adopt standard Type A PyPI CI pipeline (tag==version guard + quality gate)
- promote generated CHANGELOG.md; bump version to 0.0.7
This commit is contained in:
2026-10-17 02:16:44 +05:30
parent 8253c25928
commit 06ffd2febd
149 changed files with 7132 additions and 4594 deletions

View File

@@ -37,6 +37,4 @@ Example:
from .main import main
__all__ = [
"main"
]
__all__ = ["main"]

View File

@@ -1,5 +1,3 @@
from .main import main
__all__ = [
"main"
]
__all__ = ["main"]

118
docforge/cli/api_utils.py Normal file
View File

@@ -0,0 +1,118 @@
"""
# Summary
Utilities for building API documentation from an OpenAPI specification.
"""
import json
from dataclasses import dataclass
from pathlib import Path
import click
SWAGGER_SPEC_FILENAME = "openapi.json"
@dataclass
class OpenAPIMetadata:
"""
Metadata derived from the ``info`` block of an OpenAPI specification.
Attributes:
site_name: Spec title, used as the MkDocs site name.
site_description: Spec description, used as the site description.
site_author: Contact name (fallback: contact email), used as the
site author.
"""
site_name: str
site_description: str | None
site_author: str | None
def load_openapi_spec(spec_path: Path) -> dict:
"""
Load and validate an OpenAPI specification from a JSON file.
Args:
spec_path (Path):
Path to the OpenAPI JSON specification file.
Returns:
dict:
The parsed OpenAPI specification.
Raises:
click.ClickException:
If the file cannot be read or the ``info`` block is invalid.
"""
if not spec_path.exists():
raise click.ClickException(f"OpenAPI spec not found: {spec_path}")
try:
data = json.loads(spec_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
raise click.ClickException(f"Unable to read OpenAPI spec: {exc}") from exc
if not isinstance(data, dict):
raise click.ClickException("OpenAPI spec must be a JSON mapping")
info = data.get("info")
if not isinstance(info, dict) or not isinstance(info.get("title"), str):
raise click.ClickException("OpenAPI spec missing 'info.title'")
return data
def derive_metadata(spec: dict) -> OpenAPIMetadata:
"""
Derive MkDocs site metadata from an OpenAPI spec ``info`` block.
Args:
spec (dict):
Parsed OpenAPI specification.
Returns:
OpenAPIMetadata:
Site name, description, and author derived from the spec.
"""
info = spec["info"]
contact = info.get("contact")
if isinstance(contact, dict):
author = contact.get("name") or contact.get("email")
else:
author = None
return OpenAPIMetadata(
site_name=info.get("title", ""),
site_description=info.get("description"),
site_author=author,
)
def generate_api_sources(spec: dict, docs_dir: Path) -> None:
"""
Generate swagger-enabled Markdown sources and the spec copy.
The specification is written as ``openapi.json`` inside ``docs_dir`` and
an ``index.md`` embedding the swagger UI is generated alongside it.
Args:
spec (dict):
Parsed OpenAPI specification.
docs_dir (Path):
Directory (for example ``docs/api``) where the swagger
sources are written.
"""
docs_dir.mkdir(parents=True, exist_ok=True)
spec_path = docs_dir / SWAGGER_SPEC_FILENAME
spec_json = json.dumps(spec, indent=2)
if not spec_path.exists() or spec_path.read_text(encoding="utf-8") != spec_json:
spec_path.write_text(spec_json, encoding="utf-8")
index_path = docs_dir / "index.md"
content = "# API Reference\n\n" f'<swagger-ui src="{SWAGGER_SPEC_FILENAME}"/>\n'
if not index_path.exists() or index_path.read_text(encoding="utf-8") != content:
index_path.write_text(content, encoding="utf-8")

View File

@@ -0,0 +1,13 @@
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@dataclass
class OpenAPIMetadata:
site_name: str
site_description: str | None
site_author: str | None
def load_openapi_spec(spec_path: Path) -> dict[Any, Any]: ...
def derive_metadata(spec: dict[Any, Any]) -> OpenAPIMetadata: ...
def generate_api_sources(spec: dict[Any, Any], docs_dir: Path) -> None: ...

View File

@@ -4,14 +4,26 @@
Command definitions for the doc-forge CLI.
Provides the CLI structure using Click, including build, serve, and tree commands.
---
Notes:
- The `build` command validates requested modes before generating anything.
- `--mkdocs`, `--api`, and `--wiki` each emit their own MkDocs config and
build (`docs/mkdocs.{kind}.yml` into `site/{kind}`); `--mcp` generates a
machine-readable bundle independently.
---
"""
import click
import os
from pathlib import Path
from typing import Sequence, Optional
import click
from docforge.cli import api_utils, mcp_utils, mkdocs_utils
from docforge.loaders import GriffeLoader
from docforge.cli import mkdocs_utils
from docforge.cli import mcp_utils
from docforge.models import DocObject
@click.group()
@@ -27,75 +39,143 @@ def cli() -> None:
@cli.command()
@click.option("--mcp", is_flag=True, help="Build MCP resources")
@click.option("--mkdocs", is_flag=True, help="Build MkDocs site")
@click.option("--module-is-source", is_flag=True, help="Module is source folder and to be treated as root folder")
@click.option("--mkdocs", is_flag=True, help="Build the lib MkDocs site")
@click.option("--api", is_flag=True, help="Build API docs from an OpenAPI spec")
@click.option(
"--wiki", is_flag=True, help="Build a hand-written wiki as its own MkDocs site"
)
@click.option(
"--refresh",
is_flag=True,
help="Regenerate existing docs/mkdocs.{kind}.yml configs from templates",
)
@click.option(
"--module-is-source",
is_flag=True,
help="Module is source folder and to be treated as root folder",
)
@click.option("--module", help="Python module to document")
@click.option(
"--openapi-spec",
type=click.Path(path_type=Path),
help="Path to the OpenAPI JSON specification",
)
@click.option("--project-name", help="Project name override")
@click.option("--site-name", help="MkDocs site name")
@click.option("--docs-dir", type=click.Path(path_type=Path), default=Path("docs"), help="Directory for MD sources")
@click.option("--nav", "nav_file", type=click.Path(path_type=Path), default=Path("docforge.nav.yml"),
help="Nav spec path")
@click.option("--template", type=click.Path(path_type=Path), help="MkDocs template path")
@click.option("--mkdocs-yml", type=click.Path(path_type=Path), default=Path("mkdocs.yml"), help="Output config path")
@click.option("--out-dir", type=click.Path(path_type=Path), default=Path("mcp_docs"), help="MCP output directory")
@click.option("--site-name", help="MkDocs site name for lib and wiki sites")
@click.option(
"--docs-dir",
type=click.Path(path_type=Path),
default=Path("docs"),
help="MkDocs documentation root",
)
@click.option(
"--wiki-dir",
type=click.Path(path_type=Path),
default=Path("docs/wiki"),
help="Hand-written wiki directory built as its own MkDocs site",
)
@click.option(
"--nav",
"nav_file",
type=click.Path(path_type=Path),
default=Path("docforge.nav.yml"),
help="Nav spec path",
)
@click.option(
"--template", type=click.Path(path_type=Path), help="MkDocs template path"
)
@click.option(
"--out-dir",
type=click.Path(path_type=Path),
default=Path("docs/mcp"),
help="MCP output directory",
)
def build(
mcp: bool,
mkdocs: bool,
api: bool,
wiki: bool,
refresh: bool,
module_is_source: bool,
module: Optional[str],
project_name: Optional[str],
site_name: Optional[str],
module: str | None,
openapi_spec: Path | None,
project_name: str | None,
site_name: str | None,
docs_dir: Path,
wiki_dir: Path,
nav_file: Path,
template: Optional[Path],
mkdocs_yml: Path,
template: Path | None,
out_dir: Path,
) -> None:
"""
Build documentation artifacts.
This command performs the full documentation build pipeline:
1. Introspects the Python project using Griffe
2. Generates renderer-specific documentation sources
3. Optionally builds the final documentation output
This command runs the full documentation pipeline: it loads Python
modules, generates renderer-specific documentation sources, and
optionally builds the final output.
Depending on the selected options, the build can target:
- MkDocs static documentation sites
- MCP structured documentation resources
- A lib MkDocs site (`--mkdocs`) for library reference docs
- A swagger-enabled API MkDocs site (`--api`) built from an OpenAPI spec
- A wiki MkDocs site (`--wiki`) built from hand-written markdown
- MCP structured documentation resources (`--mcp`)
Each enabled site kind produces its own MkDocs configuration
(`docs/mkdocs.{kind}.yml`) and its own build (`site/{kind}`).
Notes:
- At least one of `--mcp`, `--mkdocs`, `--wiki`, or `--api` must be
provided.
- `--mkdocs`, `--api`, and `--wiki` emit independent MkDocs builds,
while `--mcp` emits a machine-readable bundle.
- Configuration files are generated only when absent; an existing
`docs/mkdocs.{kind}.yml` is used as-is. Pass `--refresh` to
rebaseline it from the templates.
Args:
mcp (bool):
Enable MCP documentation generation.
mkdocs (bool):
Enable MkDocs documentation generation.
Enable the lib MkDocs documentation generation.
api (bool):
Enable API documentation generation from an OpenAPI spec.
wiki (bool):
Build a hand-written wiki directory as its own MkDocs site.
refresh (bool):
Regenerate ``docs/mkdocs.{kind}.yml`` from templates even when
it already exists. By default, existing configs are used as-is.
module_is_source (bool):
Treat the specified module directory as the project root.
module (Optional[str]):
module (str | None):
Python module import path to document.
project_name (Optional[str]):
openapi_spec (Path | None):
Path to the OpenAPI JSON specification used for API docs.
project_name (str | None):
Optional override for the project name.
site_name (Optional[str]):
Display name for the MkDocs site.
site_name (str | None):
Display name for the lib and wiki MkDocs sites.
docs_dir (Path):
Directory where Markdown documentation sources will be generated.
Shared documentation root used for generated sources.
wiki_dir (Path):
Directory containing hand-written wiki markdown files.
nav_file (Path):
Path to the navigation specification file.
template (Optional[Path]):
template (Path | None):
Optional custom MkDocs configuration template.
mkdocs_yml (Path):
Output path for the generated MkDocs configuration.
out_dir (Path):
Output directory for generated MCP resources.
@@ -103,34 +183,102 @@ def build(
click.UsageError:
If required options are missing or conflicting.
"""
if not mcp and not mkdocs:
raise click.UsageError("Must specify either --mcp or --mkdocs")
if not mcp and not mkdocs and not api and not wiki:
raise click.UsageError("Must specify either --mcp, --mkdocs, --wiki, or --api")
if api:
if not openapi_spec:
raise click.UsageError("--openapi-spec is required for API build")
if site_name and not mkdocs and not wiki:
raise click.UsageError(
"--site-name cannot be overridden for API build; "
"the OpenAPI spec provides the site name"
)
if mkdocs and not module:
raise click.UsageError("--module is required for MkDocs build")
if mcp and not module:
raise click.UsageError("--module is required for MCP build")
spec: dict | None = None
if api:
spec = api_utils.load_openapi_spec(openapi_spec)
kinds: list[str] = []
if mkdocs:
if not module:
raise click.UsageError("--module is required for MkDocs build")
if not site_name:
site_name = module
click.echo(f"Generating MkDocs sources in {docs_dir}...")
kinds.append("lib")
lib_dir = docs_dir / "lib"
click.echo(f"Generating MkDocs sources in {lib_dir}...")
mkdocs_utils.generate_sources(
module,
docs_dir,
lib_dir,
project_name,
module_is_source,
readme_dir=Path(".").resolve(),
)
click.echo(f"Generating MkDocs config {mkdocs_yml}...")
mkdocs_utils.generate_config(docs_dir, nav_file, template, mkdocs_yml, site_name)
if api:
kinds.append("api")
api_dir = docs_dir / "api"
click.echo(f"Generating API sources in {api_dir}...")
api_utils.generate_api_sources(spec, api_dir)
click.echo("Running MkDocs build...")
mkdocs_utils.build(mkdocs_yml)
click.echo("MkDocs build completed.")
if wiki:
kinds.append("wiki")
if kinds:
api_metadata: api_utils.OpenAPIMetadata | None = None
if api:
api_metadata = api_utils.derive_metadata(spec)
theme_icon = mkdocs_utils.load_spec_icon(nav_file)
config_paths: list[Path] = []
for kind in kinds:
out = docs_dir / f"mkdocs.{kind}.yml"
if out.exists() and not refresh:
click.echo(
f"Using existing MkDocs config {out} (run --refresh to rebaseline)..."
)
config_paths.append(out)
continue
kind_root = wiki_dir if kind == "wiki" else docs_dir / kind
site_name_kind = site_name or module or Path.cwd().name
site_description: str | None = None
site_author: str | None = None
if kind == "api" and api_metadata:
site_name_kind = api_metadata.site_name
site_description = api_metadata.site_description
site_author = api_metadata.site_author
if kind == "lib":
nav_block, _kind_icon = mkdocs_utils.build_lib_nav(nav_file, docs_dir)
elif kind == "wiki":
nav_block = mkdocs_utils.build_wiki_nav_block(wiki_dir)
else:
nav_block = [{"API Reference": "index.md"}]
click.echo(f"Generating MkDocs config {out}...")
mkdocs_utils.generate_site_config(
kind,
kind_root,
nav_block,
out,
site_name_kind,
Path(os.path.relpath(kind_root, docs_dir)).as_posix(),
Path(os.path.relpath(Path.cwd() / "site" / kind, docs_dir)).as_posix(),
template=template,
site_description=site_description,
site_author=site_author,
theme_icon=theme_icon,
)
config_paths.append(out)
click.echo("Running MkDocs builds...")
mkdocs_utils.build_configs(config_paths)
if mcp:
if not module:
raise click.UsageError("--module is required for MCP build")
click.echo(f"Generating MCP resources in {out_dir}...")
mcp_utils.generate_resources(module, project_name, out_dir)
click.echo("MCP build completed.")
@@ -138,14 +286,30 @@ def build(
@cli.command()
@click.option("--mcp", is_flag=True, help="Serve MCP documentation")
@click.option("--mkdocs", is_flag=True, help="Serve MkDocs site")
@click.option("--mkdocs", is_flag=True, help="Serve an MkDocs site from --mkdocs-yml")
@click.option("--lib", is_flag=True, help="Serve the lib MkDocs site")
@click.option("--api", is_flag=True, help="Serve the API MkDocs site")
@click.option("--wiki", is_flag=True, help="Serve the wiki MkDocs site")
@click.option("--module", help="Python module to serve")
@click.option("--mkdocs-yml", type=click.Path(path_type=Path), default=Path("mkdocs.yml"), help="MkDocs config path")
@click.option("--out-dir", type=click.Path(path_type=Path), default=Path("mcp_docs"), help="MCP root directory")
@click.option(
"--mkdocs-yml",
type=click.Path(path_type=Path),
default=Path("docs/mkdocs.wiki.yml"),
help="MkDocs config path",
)
@click.option(
"--out-dir",
type=click.Path(path_type=Path),
default=Path("docs/mcp"),
help="MCP root directory",
)
def serve(
mcp: bool,
mkdocs: bool,
module: Optional[str],
lib: bool,
api: bool,
wiki: bool,
module: str | None,
mkdocs_yml: Path,
out_dir: Path,
) -> None:
@@ -154,17 +318,30 @@ def serve(
Depending on the selected mode, this command starts either:
- A MkDocs development server for browsing documentation
- A MkDocs development server for browsing a site, or
- An MCP server exposing structured documentation resources
The kind flags (`--lib`, `--api`, `--wiki`) select the generated
per-kind config (`docs/mkdocs.{kind}.yml`); `--mkdocs` serves the config
passed via `--mkdocs-yml`.
Args:
mcp (bool):
Serve documentation using the MCP server.
mkdocs (bool):
Serve the MkDocs development site.
Serve the MkDocs development site from ``--mkdocs-yml``.
module (Optional[str]):
lib (bool):
Serve the lib MkDocs site.
api (bool):
Serve the API MkDocs site.
wiki (bool):
Serve the wiki MkDocs site.
module (str | None):
Python module import path to serve via MCP.
mkdocs_yml (Path):
@@ -177,17 +354,37 @@ def serve(
click.UsageError:
If invalid or conflicting options are provided.
"""
if mcp and mkdocs:
raise click.UsageError("Cannot specify both --mcp and --mkdocs")
if not mcp and not mkdocs:
raise click.UsageError("Must specify either --mcp or --mkdocs")
if mcp and not module:
raise click.UsageError("--module is required for MCP serve")
selected = [
name
for name, enabled in (
("mcp", mcp),
("mkdocs", mkdocs),
("lib", lib),
("api", api),
("wiki", wiki),
)
if enabled
]
if len(selected) != 1:
raise click.UsageError(
"Must specify exactly one of --mcp, --mkdocs, --lib, --api, --wiki"
)
if mkdocs:
mkdocs_utils.serve(mkdocs_yml)
elif mcp:
if mcp:
if not module:
raise click.UsageError("--module is required for MCP serve")
mcp_utils.serve(module, out_dir)
return
config = mkdocs_yml
if lib:
config = Path("docs/mkdocs.lib.yml")
elif api:
config = Path("docs/mkdocs.api.yml")
elif wiki:
config = Path("docs/mkdocs.wiki.yml")
mkdocs_utils.serve(config)
@cli.command()
@@ -202,7 +399,7 @@ def serve(
)
def tree(
module: str,
project_name: Optional[str],
project_name: str | None,
) -> None:
"""
Display the documentation object tree for a module.
@@ -215,7 +412,7 @@ def tree(
module (str):
Python module import path to introspect.
project_name (Optional[str]):
project_name (str | None):
Optional name to display as the project root.
"""
loader = GriffeLoader()
@@ -229,7 +426,7 @@ def tree(
_print_object(obj, indent="│ ")
def _print_object(obj, indent: str) -> None:
def _print_object(obj: DocObject, indent: str) -> None:
"""
Recursively print a documentation object and its members.
@@ -237,7 +434,7 @@ def _print_object(obj, indent: str) -> None:
and prints each object with indentation to represent hierarchy.
Args:
obj:
obj (DocObject):
Documentation object to print.
indent (str):

View File

@@ -1,34 +1,39 @@
from click.core import Group
from pathlib import Path
from typing import Sequence, Optional, Any
from click.core import Group
from docforge.models import DocObject
cli: Group
def build(
mcp: bool,
mkdocs: bool,
api: bool,
wiki: bool,
module_is_source: bool,
module: Optional[str],
project_name: Optional[str],
site_name: Optional[str],
module: str | None,
openapi_spec: Path | None,
project_name: str | None,
site_name: str | None,
docs_dir: Path,
wiki_dir: Path,
nav_file: Path,
template: Optional[Path],
mkdocs_yml: Path,
template: Path | None,
out_dir: Path,
) -> None: ...
def serve(
mcp: bool,
mkdocs: bool,
module: Optional[str],
lib: bool,
api: bool,
wiki: bool,
module: str | None,
mkdocs_yml: Path,
out_dir: Path,
) -> None: ...
def tree(
module: str,
project_name: Optional[str],
project_name: str | None,
) -> None: ...
def _print_object(obj: Any, indent: str) -> None: ...
def _print_object(obj: DocObject, indent: str) -> None: ...

View File

@@ -22,4 +22,4 @@ def main() -> None:
if __name__ == "__main__":
main()
main()

View File

@@ -2,10 +2,22 @@
# Summary
Utilities for working with MCP in the doc-forge CLI.
---
Notes:
- `generate_resources` produces the bundle consumed by `MCPServer`:
`index.json`, `nav.json`, and per-module resources under `modules/`.
- Resource URIs use the `docs://` scheme: `docs://index`, `docs://nav`,
and `docs://modules/{module}`.
---
"""
from pathlib import Path
import click
from docforge.loaders import GriffeLoader, discover_module_paths
from docforge.renderers import MCPRenderer
from docforge.servers import MCPServer
@@ -24,7 +36,7 @@ def generate_resources(module: str, project_name: str | None, out_dir: Path) ->
Python module import path used as the entry point for
documentation generation.
project_name (Optional[str]):
project_name (str | None):
Optional override for the project name used in generated
documentation metadata.
@@ -61,7 +73,7 @@ def serve(module: str, mcp_root: Path) -> None:
If the MCP documentation bundle is missing required files or directories.
"""
if not mcp_root.exists():
raise click.ClickException(f"mcp_docs directory not found: {mcp_root}")
raise click.ClickException(f"MCP docs directory not found: {mcp_root}")
required = [
mcp_root / "index.json",

View File

@@ -1,4 +1,6 @@
from pathlib import Path
def generate_resources(module: str, project_name: str | None, out_dir: Path) -> None: ...
def generate_resources(
module: str, project_name: str | None, out_dir: Path
) -> None: ...
def serve(module: str, mcp_root: Path) -> None: ...

View File

@@ -2,15 +2,35 @@
# Summary
Utilities for working with MkDocs in the doc-forge CLI.
---
Notes:
- A separate `mkdocs.{kind}.yml` configuration and build is emitted per
enabled kind (lib, api, wiki), each scoped to its own `docs_dir` and
written into its own `site_dir` (`site/lib`, `site/api`, `site/wiki`).
- Navigation blocks are re-rooted per kind: the wiki navigation drops its
leading `wiki/` scope and the resolved nav spec drops its `lib/` scope.
---
"""
from pathlib import Path
from collections.abc import Iterable
from importlib import resources
from pathlib import Path
from typing import Any, cast
import click
import yaml
from docforge.loaders import GriffeLoader, discover_module_paths
from docforge.nav import (
MkDocsNavEmitter,
build_wiki_nav,
load_nav_spec,
resolve_nav,
)
from docforge.renderers import MkDocsRenderer
from docforge.nav import load_nav_spec, resolve_nav, MkDocsNavEmitter
def generate_sources(
@@ -18,6 +38,7 @@ def generate_sources(
docs_dir: Path,
project_name: str | None = None,
module_is_source: bool | None = None,
readme_dir: Path | None = None,
) -> None:
"""
Generate MkDocs Markdown sources for a Python module.
@@ -34,12 +55,16 @@ def generate_sources(
docs_dir (Path):
Directory where the generated Markdown files will be written.
project_name (Optional[str]):
project_name (str | None):
Optional override for the project name used in documentation metadata.
module_is_source (Optional[bool]):
module_is_source (bool | None):
If True, treat the specified module directory as the project root
rather than a nested module.
readme_dir (Path | None):
Directory where the generated README.md should be written. If not
provided, defaults to the parent of ``docs_dir``.
"""
loader = GriffeLoader()
discovered_paths = discover_module_paths(module)
@@ -56,92 +81,353 @@ def generate_sources(
project,
docs_dir,
module_is_source,
readme_dir,
)
def generate_config(
docs_dir: Path,
def build_lib_nav(
nav_file: Path,
template: Path | None,
out: Path,
site_name: str,
) -> None:
docs_root: Path,
) -> tuple[list[dict[str, Any]], dict[str, str] | None]:
"""
Generate an `mkdocs.yml` configuration file.
Build the re-rooted navigation block for a lib site.
The configuration is created by combining a template configuration
with a navigation structure derived from the docforge navigation
specification.
The navigation specification is resolved against the shared documentation
root and every resulting path is re-rooted relative to the ``lib``
subdirectory by stripping its leading ``lib/`` scope component.
Args:
docs_dir (Path):
Directory containing generated documentation Markdown files.
nav_file (Path):
Path to the `docforge.nav.yml` navigation specification.
template (Optional[Path]):
Optional path to a custom MkDocs configuration template. If not
provided, a built-in template will be used.
docs_root (Path):
Shared documentation root containing the ``lib`` sources.
out (Path):
Destination path where the generated `mkdocs.yml` file will be written.
site_name (str):
Display name for the generated documentation site.
Returns:
tuple[list[dict[str, Any]], dict[str, str] | None]:
The re-rooted navigation block and the optional theme icon
mapping from the specification.
Raises:
click.FileError:
If the navigation specification or template file cannot be found.
If the navigation specification cannot be found.
"""
if not nav_file.exists():
raise click.FileError(str(nav_file), hint="Nav spec not found")
spec = load_nav_spec(nav_file)
resolved = resolve_nav(spec, docs_dir)
nav_block = MkDocsNavEmitter().emit(resolved)
resolved = resolve_nav(spec, docs_root)
block = MkDocsNavEmitter().emit(resolved)
return cast(list[dict[str, Any]], _strip_scope(block, "lib")), spec.icon
# Load template
if template is not None:
if not template.exists():
raise click.FileError(str(template), hint="Template not found")
data = yaml.safe_load(template.read_text(encoding="utf-8"))
else:
text = (
resources.files("docforge.templates")
.joinpath("mkdocs.sample.yml")
.read_text(encoding="utf-8")
)
data = yaml.safe_load(text)
def build_wiki_nav_block(wiki_dir: Path) -> list[dict[str, Any]]:
"""
Build the re-rooted navigation block for a wiki site.
The wiki navigation derived from the wiki file structure is re-rooted
relative to the wiki directory itself by stripping the leading ``wiki/``
scope component.
Args:
wiki_dir (Path):
Path to the hand-written wiki directory, for example ``docs/wiki``.
Returns:
list[dict[str, Any]]:
Navigation entries relative to the wiki directory.
Raises:
click.FileError:
If the wiki directory does not exist.
"""
if not wiki_dir.exists():
raise click.FileError(str(wiki_dir), hint="Wiki dir not found")
return cast(list[dict[str, Any]], _strip_scope(build_wiki_nav(wiki_dir), "wiki"))
def load_spec_icon(nav_file: Path) -> dict[str, str] | None:
"""
Load the theme icon mapping from a navigation specification.
Args:
nav_file (Path):
Path to the navigation specification file.
Returns:
dict[str, str] | None:
The icon mapping, or ``None`` when the specification file is
absent or cannot be parsed.
"""
if not nav_file.exists():
return None
try:
return load_nav_spec(nav_file).icon
except (ValueError, yaml.YAMLError):
return None
def _strip_scope(value: object, scope: str) -> object:
"""
Re-root navigation paths by removing a leading scope component.
The navigation block is walked recursively and every relative path
string that starts with ``{scope}/`` has that prefix removed, so a lib
or wiki site scoped to its own ``docs_dir`` can reuse paths that were
originally written relative to the shared documentation root.
Args:
value (object):
Navigation block, group list, path string, or scalar value.
scope (str):
Leading path component to strip, for example ``lib`` or ``wiki``.
Returns:
object:
The navigation structure with re-rooted paths.
"""
if isinstance(value, str):
prefix = f"{scope}/"
return value[len(prefix) :] if value.startswith(prefix) else value
if isinstance(value, list):
return [_strip_scope(item, scope) for item in value]
if isinstance(value, dict):
return {key: _strip_scope(val, scope) for key, val in value.items()}
return value
def generate_site_config(
kind: str,
kind_root: Path,
nav_block: list[dict[str, Any]],
out: Path,
site_name: str,
docs_dir: str,
site_dir: str,
template: Path | None = None,
site_description: str | None = None,
site_author: str | None = None,
theme_icon: dict[str, str] | None = None,
) -> None:
"""
Generate a per-kind `mkdocs.{kind}.yml` configuration file.
The configuration is created by merging the shared ``mkdocs.common.yml``
template with the fragment contributed by the kind (``lib``, ``api``, or
``wiki``). Both ``docs_dir`` and ``site_dir`` are written relative to the
configuration file's directory: the kind's sources when expressed as a
sibling path (for example ``lib``) and the per-kind site output (for
example ``../site/lib``).
Args:
kind (str):
Documentation kind, one of ``lib``, ``api``, or ``wiki``.
kind_root (Path):
Directory scoped to the kind (for example ``docs/lib``) that
serves as the MkDocs ``docs_dir``.
nav_block (list[dict[str, Any]]):
Re-rooted navigation entries for the kind's site.
out (Path):
Destination path where the generated ``mkdocs.{kind}.yml`` file
is written.
site_name (str):
Display name for the generated documentation site.
docs_dir (str):
MkDocs ``docs_dir`` value, relative to the configuration
file's directory.
site_dir (str):
MkDocs ``site_dir`` value, relative to the configuration
file's directory.
template (Path | None):
Optional path to a fully custom MkDocs configuration template
that replaces the built-in templates entirely.
site_description (str | None):
Optional site description written into the configuration.
site_author (str | None):
Optional site author written into the configuration.
theme_icon (dict[str, str] | None):
Optional mapping of theme icon entries injected as
``theme.icon``.
"""
data = _load_template(template, [kind])
data["site_name"] = site_name
if site_description:
data["site_description"] = site_description
if site_author:
data["site_author"] = site_author
data["docs_dir"] = docs_dir
data["site_dir"] = site_dir
data["nav"] = nav_block
if theme_icon:
theme = data.setdefault("theme", {})
if not isinstance(theme, dict):
theme = {}
theme["icon"] = theme_icon
data["theme"] = theme
out.write_text(yaml.safe_dump(data, sort_keys=False), encoding="utf-8")
def build(mkdocs_yml: Path) -> None:
def _load_template(
template: Path | None,
modes: Iterable[str] | None,
) -> dict:
"""
Build the MkDocs documentation site.
Load the MkDocs configuration template.
This function loads the MkDocs configuration and runs the MkDocs
build command to generate the final static documentation site.
When a custom template path is provided, it is used as-is. Otherwise the
shared ``mkdocs.common.yml`` template is deep-merged with the fragments
contributed by each enabled mode (``lib``, ``api``, or ``wiki``).
Args:
mkdocs_yml (Path):
Path to the `mkdocs.yml` configuration file.
template (Path | None):
Optional fully custom template that replaces the built-ins.
modes (Iterable[str] | None):
Documentation modes whose template fragments should be merged.
Returns:
dict:
Merged MkDocs configuration mapping.
Raises:
click.FileError:
If a referenced template file cannot be found.
"""
if template is not None:
if not template.exists():
raise click.FileError(str(template), hint="Template not found")
return yaml.safe_load(template.read_text(encoding="utf-8"))
data: dict = {}
active_modes = list(modes) if modes else ["lib"]
parts = ["common", *active_modes]
seen: set[str] = set()
for part_name in parts:
if part_name in seen:
continue
seen.add(part_name)
text = (
resources.files("docforge.templates")
.joinpath(f"mkdocs.{part_name}.yml")
.read_text(encoding="utf-8")
)
part: dict = yaml.safe_load(text)
data = _deep_merge(data, part)
return data
def _item_name(item: object) -> str:
"""
Return the identifying name of a list entry.
String entries identify as themselves; mapping entries identify by their
first key. This is used to deduplicate plugin and extension lists.
Args:
item (object):
List entry, either a string or a single-key mapping.
Returns:
str:
The identifying name of the entry.
"""
if isinstance(item, dict):
return next(iter(item.keys()), "")
return str(item)
def _merge_list(base: list, added: list) -> list:
"""
Merge two lists, preserving order and dropping duplicates by name.
Args:
base (list):
Existing list entries.
added (list):
Entries to append when not already present.
Returns:
list:
Merged list with duplicates removed.
"""
result = list(base)
names = {_item_name(item) for item in result}
for item in added:
name = _item_name(item)
if name not in names:
result.append(item)
names.add(name)
return result
def _deep_merge(base: dict, part: dict) -> dict:
"""
Deep merge a template fragment into a base configuration.
Mappings are merged recursively, while lists are combined by
deduplicating entries by their identifying name. Non-container values in
the fragment override the base.
Args:
base (dict):
Configuration being built up.
part (dict):
Template fragment to merge into the base.
Returns:
dict:
The merged configuration.
"""
for key, value in part.items():
if isinstance(value, dict) and isinstance(base.get(key), dict):
base[key] = _deep_merge(base[key], value)
elif isinstance(value, list) and isinstance(base.get(key), list):
base[key] = _merge_list(base[key], value)
else:
base[key] = value
return base
def build_configs(yml_paths: Iterable[Path]) -> None:
"""
Build the MkDocs documentation site for every given configuration.
Each configuration file is loaded and built in turn, producing the
per-kind static sites (``site/lib``, ``site/api``, ``site/wiki``).
Args:
yml_paths (Iterable[Path]):
Configuration files to build, in order.
Raises:
click.ClickException:
If the configuration file does not exist.
If a configuration file does not exist.
"""
if not mkdocs_yml.exists():
raise click.ClickException(f"mkdocs.yml not found: {mkdocs_yml}")
from mkdocs.config import load_config
from mkdocs.commands.build import build as mkdocs_build
from mkdocs.config import load_config
mkdocs_build(load_config(str(mkdocs_yml)))
for yml in yml_paths:
if not yml.exists():
raise click.ClickException(f"mkdocs.yml not found: {yml}")
mkdocs_build(load_config(str(yml)))
def serve(mkdocs_yml: Path) -> None:
@@ -163,4 +449,5 @@ def serve(mkdocs_yml: Path) -> None:
raise click.ClickException(f"mkdocs.yml not found: {mkdocs_yml}")
from mkdocs.commands.serve import serve as mkdocs_serve
mkdocs_serve(config_file=str(mkdocs_yml))

View File

@@ -1,11 +1,33 @@
from collections.abc import Iterable
from pathlib import Path
from typing import Any
def generate_sources(
module: str,
docs_dir: Path,
project_name: str | None = None,
module_is_source: bool | None = None,
readme_dir: Path | None = None,
) -> None: ...
def generate_config(docs_dir: Path, nav_file: Path, template: Path | None, out: Path, site_name: str) -> None: ...
def build(mkdocs_yml: Path) -> None: ...
def build_lib_nav(
nav_file: Path,
docs_root: Path,
) -> tuple[list[dict[str, Any]], dict[str, str] | None]: ...
def build_wiki_nav_block(wiki_dir: Path) -> list[dict[str, Any]]: ...
def load_spec_icon(nav_file: Path) -> dict[str, str] | None: ...
def _strip_scope(value: object, scope: str) -> object: ...
def generate_site_config(
kind: str,
kind_root: Path,
nav_block: list[dict[str, Any]],
out: Path,
site_name: str,
docs_dir: str,
site_dir: str,
template: Path | None = None,
site_description: str | None = None,
site_author: str | None = None,
theme_icon: dict[str, str] | None = None,
) -> None: ...
def build_configs(yml_paths: Iterable[Path]) -> None: ...
def serve(mkdocs_yml: Path) -> None: ...