Coverage for src/hypra/cli/commands.py: 91.30%
40 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 22:12 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 22:12 +0000
1"""Typer commands for backend discovery and exact expansion."""
3import json
4import sys
5from enum import Enum
6from pathlib import Path
7from typing import Annotated, NoReturn
9import typer
11from ..backend import BackendError
12from ..errors import HypraError
13from .request import ExpansionRequest
16class Backend(str, Enum):
17 """Select the native engine or the optional external comparison bridge."""
19 native = "native"
20 wolfram = "wolfram"
23_ERRORS = (BackendError, HypraError, OSError, ValueError, TypeError, KeyError)
26def _error(exc: Exception) -> NoReturn:
27 print(
28 json.dumps({"status": "error", "type": type(exc).__name__, "message": str(exc)}),
29 file=sys.stderr,
30 )
31 raise typer.Exit(code=2) from exc
34class Commands:
35 """Translate command inputs and outputs around Hypra's Python API."""
37 def __init__(self, get_backend_info, expand):
38 self._get_backend_info = get_backend_info
39 self._expand = expand
41 def backend_info(
42 self,
43 backend: Annotated[
44 Backend, typer.Option(help="Backend whose availability and capabilities to report.")
45 ] = Backend.native,
46 ) -> None:
47 """Report backend capabilities as JSON; exit 2 when unavailable."""
48 try:
49 info = self._get_backend_info(backend=backend.value)
50 print(json.dumps(info, indent=2))
51 if not info["available"]:
52 raise typer.Exit(code=2)
53 except _ERRORS as exc:
54 _error(exc)
56 def expand(
57 self,
58 request: Annotated[
59 Path, typer.Argument(help="JSON file with exact expression and epsilon ASTs.")
60 ],
61 backend: Annotated[
62 Backend, typer.Option(help="Expansion engine; no silent external fallback.")
63 ] = Backend.native,
64 output: Annotated[
65 Path | None, typer.Option(help="Write result JSON here instead of stdout.")
66 ] = None,
67 latex: Annotated[
68 Path | None, typer.Option(help="Also write a LaTeX display equation.")
69 ] = None,
70 ) -> None:
71 """Expand an exact JSON AST request through its inclusive Laurent order.
73 Request keys: expression, epsilon, through (default 3), assumptions.
74 Input is data, never Python or Mathematica source. Errors are JSON on
75 stderr with exit status 2. Successful results retain exact provenance.
76 """
77 try:
78 payload = ExpansionRequest.read(request)
79 result = self._expand(
80 payload.expression,
81 payload.epsilon,
82 through=payload.through,
83 backend=backend.value,
84 assumptions=payload.assumptions,
85 )
86 serialized = json.dumps(result.to_dict(), indent=2) + "\n"
87 if output: 87 ↛ 90line 87 didn't jump to line 90 because the condition on line 87 was always true
88 output.write_text(serialized)
89 else:
90 print(serialized, end="")
91 if latex: 91 ↛ exitline 91 didn't return from function 'expand' because the condition on line 91 was always true
92 latex.write_text(
93 f"% Exact Hypra result; see JSON for provenance.\n\\[\n{result.latex()}\n\\]\n"
94 )
95 except _ERRORS as exc:
96 _error(exc)