codehood-cli 0.5.0__py3-none-any.whl
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.
- codehood/__init__.py +0 -0
- codehood/__main__.py +4 -0
- codehood/actions/__init__.py +0 -0
- codehood/actions/base.py +119 -0
- codehood/actions/resources.py +30 -0
- codehood/api/__init__.py +0 -0
- codehood/api/base.py +256 -0
- codehood/api/generate.py +1370 -0
- codehood/api/generated.py +3818 -0
- codehood/api/openapi.py +134 -0
- codehood/api/pages.py +53 -0
- codehood/cli/__init__.py +64 -0
- codehood/cli/api.py +422 -0
- codehood/cli/attendance.py +136 -0
- codehood/cli/auth.py +106 -0
- codehood/cli/base.py +42 -0
- codehood/cli/chill.py +52 -0
- codehood/cli/exam.py +107 -0
- codehood/cli/grades.py +185 -0
- codehood/cli/init.py +161 -0
- codehood/cli/push.py +609 -0
- codehood/cli/show.py +77 -0
- codehood/cli/uitils.py +26 -0
- codehood/functional.py +40 -0
- codehood/globs.py +71 -0
- codehood/grades.py +74 -0
- codehood/hypothesis.py +274 -0
- codehood/models/__init__.py +0 -0
- codehood/models/base.py +15 -0
- codehood/models/repo.py +187 -0
- codehood/models/validators.py +177 -0
- codehood/push/__init__.py +225 -0
- codehood/push/base.py +216 -0
- codehood/push/calendar.py +664 -0
- codehood/push/errors.py +136 -0
- codehood/push/exam.py +636 -0
- codehood/push/exclude.py +60 -0
- codehood/push/grades.py +455 -0
- codehood/push/hook.py +48 -0
- codehood/push/links.py +614 -0
- codehood/push/ours.py +78 -0
- codehood/push/plan.py +1981 -0
- codehood/push/project.py +272 -0
- codehood/push/question.py +338 -0
- codehood/push/report.py +244 -0
- codehood/push/repository.py +326 -0
- codehood/push/resource.py +576 -0
- codehood/push/run.py +1275 -0
- codehood/push/unconsumed.py +208 -0
- codehood/push/wire.py +222 -0
- codehood/py.typed +0 -0
- codehood/repo/__init__.py +62 -0
- codehood/repo/_config.py +28 -0
- codehood/repo/_layout.py +132 -0
- codehood/repo/_scaffold.py +244 -0
- codehood/repo/diff.py +71 -0
- codehood/repo/file_tracker.py +124 -0
- codehood/theme.py +101 -0
- codehood/widgets/__init__.py +0 -0
- codehood/widgets/mascot.py +76 -0
- codehood/widgets/questions/__init__.py +65 -0
- codehood/widgets/questions/base.py +119 -0
- codehood/widgets/questions/controls.py +194 -0
- codehood/widgets/questions/fill_in.py +81 -0
- codehood/widgets/questions/responses.py +137 -0
- codehood/widgets/questions/simple.py +117 -0
- codehood_cli-0.5.0.dist-info/METADATA +294 -0
- codehood_cli-0.5.0.dist-info/RECORD +71 -0
- codehood_cli-0.5.0.dist-info/WHEEL +4 -0
- codehood_cli-0.5.0.dist-info/entry_points.txt +4 -0
- codehood_cli-0.5.0.dist-info/licenses/LICENSE +21 -0
codehood/api/openapi.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Typed access to a Codehood server's OpenAPI document.
|
|
3
|
+
|
|
4
|
+
Models only what `codehood api` and `api.generate` actually read: each
|
|
5
|
+
operation's identity, summary, parameters, request/response bodies, and
|
|
6
|
+
declared security, plus the named schemas in `components.schemas` those
|
|
7
|
+
bodies reference. A schema's
|
|
8
|
+
own shape (`properties`, `enum`, `$ref`, ...) is kept as a raw dict rather
|
|
9
|
+
than modeled field-by-field -- `api.generate`'s type mapper is what
|
|
10
|
+
interprets it, and it only needs to understand the JSON Schema subset the
|
|
11
|
+
server actually emits.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import Any, Literal, NamedTuple
|
|
17
|
+
|
|
18
|
+
from pydantic import Field
|
|
19
|
+
|
|
20
|
+
from ..models.base import Model
|
|
21
|
+
|
|
22
|
+
type JSONSchema = dict[str, Any]
|
|
23
|
+
|
|
24
|
+
#: One entry of a `security` array: scheme name -> required scopes (empty
|
|
25
|
+
#: for an API-key-style scheme like `BearerAuth`, non-empty for OAuth2).
|
|
26
|
+
type SecurityRequirement = dict[str, list[str]]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MediaType(Model):
|
|
30
|
+
content_schema: JSONSchema = Field(alias="schema", default_factory=dict)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class RequestBody(Model):
|
|
34
|
+
content: dict[str, MediaType] = Field(default_factory=dict)
|
|
35
|
+
required: bool = False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Response(Model):
|
|
39
|
+
description: str = ""
|
|
40
|
+
content: dict[str, MediaType] = Field(default_factory=dict)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Parameter(Model):
|
|
44
|
+
name: str
|
|
45
|
+
location: Literal["path", "query", "header", "cookie"] = Field(alias="in")
|
|
46
|
+
required: bool = False
|
|
47
|
+
content_schema: JSONSchema = Field(alias="schema", default_factory=dict)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Operation(Model):
|
|
51
|
+
operation_id: str = Field(alias="operationId")
|
|
52
|
+
summary: str = ""
|
|
53
|
+
description: str = ""
|
|
54
|
+
tags: list[str] = Field(default_factory=list)
|
|
55
|
+
parameters: list[Parameter] = Field(default_factory=list)
|
|
56
|
+
request_body: RequestBody | None = Field(alias="requestBody", default=None)
|
|
57
|
+
responses: dict[str, Response] = Field(default_factory=dict)
|
|
58
|
+
#: `None` means "use the document's default security" (see
|
|
59
|
+
#: `OpenAPISpec.requires_auth`); `[]` is an explicit override to none.
|
|
60
|
+
security: list[SecurityRequirement] | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Info(Model):
|
|
64
|
+
title: str
|
|
65
|
+
version: str
|
|
66
|
+
description: str = ""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Components(Model):
|
|
70
|
+
schemas: dict[str, JSONSchema] = Field(default_factory=dict)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class OpenAPISpec(Model):
|
|
74
|
+
openapi: str
|
|
75
|
+
info: Info
|
|
76
|
+
components: Components = Field(default_factory=Components)
|
|
77
|
+
paths: dict[str, dict[str, Operation]] = Field(default_factory=dict)
|
|
78
|
+
#: The document-wide default security requirement, in effect for any
|
|
79
|
+
#: operation that doesn't declare its own `security`.
|
|
80
|
+
security: list[SecurityRequirement] = Field(default_factory=list)
|
|
81
|
+
|
|
82
|
+
def requires_auth(self, operation: Operation) -> bool:
|
|
83
|
+
"""
|
|
84
|
+
Whether calling `operation` needs credentials.
|
|
85
|
+
|
|
86
|
+
An operation's own `security` overrides the document's default when
|
|
87
|
+
present (even an explicit `[]`, meaning "this one doesn't need it");
|
|
88
|
+
otherwise the document's default applies.
|
|
89
|
+
"""
|
|
90
|
+
security = (
|
|
91
|
+
operation.security if operation.security is not None else self.security
|
|
92
|
+
)
|
|
93
|
+
return bool(security)
|
|
94
|
+
|
|
95
|
+
def operations(self) -> dict[str, Endpoint]:
|
|
96
|
+
"""
|
|
97
|
+
Flatten `paths` into `operationId -> Endpoint`.
|
|
98
|
+
|
|
99
|
+
Every schema in the document assigns each operation a unique
|
|
100
|
+
`operationId`, which is what `ENDPOINTS` (in `api.generate`) and
|
|
101
|
+
`codehood api`'s listing key off -- not `(method, path)`, since a
|
|
102
|
+
server-side rename would silently break a hand-written pair but
|
|
103
|
+
leaves the id alone.
|
|
104
|
+
"""
|
|
105
|
+
return {
|
|
106
|
+
operation.operation_id: Endpoint(method.upper(), path, operation)
|
|
107
|
+
for path, methods in self.paths.items()
|
|
108
|
+
for method, operation in methods.items()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
def resolve(self, schema: JSONSchema) -> tuple[str, JSONSchema]:
|
|
112
|
+
"""
|
|
113
|
+
Follow a `$ref` to its schema in `components.schemas`.
|
|
114
|
+
|
|
115
|
+
Returns the schema's name and its body. Raises `KeyError` if `schema`
|
|
116
|
+
is not a `$ref`, or points at a name `components.schemas` doesn't
|
|
117
|
+
have -- both are a malformed document, not a recoverable case.
|
|
118
|
+
"""
|
|
119
|
+
ref = schema["$ref"]
|
|
120
|
+
name = ref.rsplit("/", 1)[-1]
|
|
121
|
+
return name, self.components.schemas[name]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class Endpoint(NamedTuple):
|
|
125
|
+
method: str
|
|
126
|
+
path: str
|
|
127
|
+
operation: Operation
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def load_openapi(data: dict[str, Any]) -> OpenAPISpec:
|
|
131
|
+
"""
|
|
132
|
+
Parse a raw OpenAPI document into an `OpenAPISpec`.
|
|
133
|
+
"""
|
|
134
|
+
return OpenAPISpec.model_validate(data)
|
codehood/api/pages.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Read a whole listing from a REST list route, page by page.
|
|
3
|
+
|
|
4
|
+
Every `GET` list route answers an envelope, `{"items": [...], "next": ...}`:
|
|
5
|
+
`items` is one page and `next` is the cursor of the following one, sent back
|
|
6
|
+
as `after`, or `null` on the last page. A route that does not paginate
|
|
7
|
+
answers everything at once with `next: null`, so following `next` is correct
|
|
8
|
+
on every list route, paginated or not.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections.abc import Callable, Sequence
|
|
14
|
+
from typing import Protocol, cast
|
|
15
|
+
|
|
16
|
+
__all__ = ["Page", "read_all"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Page[T](Protocol):
|
|
20
|
+
"""
|
|
21
|
+
One page of a list route: the generated `List*Response` models.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def items(self) -> Sequence[T]: ...
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def next(self) -> str | None: ...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def read_all[**P, T](
|
|
32
|
+
fetch: Callable[P, Page[T]], *args: P.args, **kwargs: P.kwargs
|
|
33
|
+
) -> list[T]:
|
|
34
|
+
"""
|
|
35
|
+
Call a list function with `args` and `kwargs`, following `next` until the last page.
|
|
36
|
+
|
|
37
|
+
The first page is fetched without `after`; each following one passes the
|
|
38
|
+
previous page's `next` as `after`. The page size is left to the server.
|
|
39
|
+
|
|
40
|
+
Example:
|
|
41
|
+
>>> read_all(generated.list_course, edition="2026-1") # doctest: +SKIP
|
|
42
|
+
|
|
43
|
+
Raises:
|
|
44
|
+
TypeError: When the server pages a route whose `fetch` takes no
|
|
45
|
+
`after`, i.e. the generated client is older than the server.
|
|
46
|
+
"""
|
|
47
|
+
page = fetch(*args, **kwargs)
|
|
48
|
+
items = list(page.items)
|
|
49
|
+
paged = cast(Callable[..., Page[T]], fetch)
|
|
50
|
+
while page.next is not None:
|
|
51
|
+
page = paged(*args, **kwargs, after=page.next)
|
|
52
|
+
items.extend(page.items)
|
|
53
|
+
return items
|
codehood/cli/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import typer
|
|
5
|
+
|
|
6
|
+
from ..api.base import NotLoggedInError
|
|
7
|
+
from .api import api
|
|
8
|
+
from .attendance import attendance
|
|
9
|
+
from .auth import login, logout
|
|
10
|
+
from .base import app as _app
|
|
11
|
+
from .chill import chill
|
|
12
|
+
from .exam import exam
|
|
13
|
+
from .grades import grades
|
|
14
|
+
from .init import init
|
|
15
|
+
from .push import push
|
|
16
|
+
from .show import show
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
#: Main entry point
|
|
20
|
+
"main",
|
|
21
|
+
#: Subcommands
|
|
22
|
+
"api",
|
|
23
|
+
"attendance",
|
|
24
|
+
"chill",
|
|
25
|
+
"exam",
|
|
26
|
+
"grades",
|
|
27
|
+
"init",
|
|
28
|
+
"login",
|
|
29
|
+
"logout",
|
|
30
|
+
"push",
|
|
31
|
+
"show",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def main() -> None:
|
|
36
|
+
"""
|
|
37
|
+
Run the Codehood CLI, turning failures every command shares into one error line.
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
SystemExit: With code 1 when no login is stored for the server or the
|
|
41
|
+
server cannot be reached.
|
|
42
|
+
"""
|
|
43
|
+
try:
|
|
44
|
+
_app()
|
|
45
|
+
except NotLoggedInError as exc:
|
|
46
|
+
typer.echo(f"error: {exc}", err=True)
|
|
47
|
+
raise SystemExit(1) from exc
|
|
48
|
+
except httpx.TransportError as exc:
|
|
49
|
+
typer.echo(f"error: could not reach {server_of(exc)}: {exc}", err=True)
|
|
50
|
+
raise SystemExit(1) from exc
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
#
|
|
54
|
+
# Utilities
|
|
55
|
+
#
|
|
56
|
+
def server_of(exc: httpx.TransportError) -> str:
|
|
57
|
+
"""
|
|
58
|
+
The scheme and host `exc`'s request was sent to, or "the server" if unknown.
|
|
59
|
+
"""
|
|
60
|
+
try:
|
|
61
|
+
url = exc.request.url
|
|
62
|
+
except RuntimeError:
|
|
63
|
+
return "the server"
|
|
64
|
+
return f"{url.scheme}://{url.netloc.decode()}"
|
codehood/cli/api.py
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`codehood api`: browse the endpoints the CLI knows about, and call the ones
|
|
3
|
+
that don't require auth, straight from a server's OpenAPI document. See
|
|
4
|
+
`dev/specs/to-review/api.md`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
from typing import Annotated, Any
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
import typer
|
|
14
|
+
from rich import markup
|
|
15
|
+
from rich.console import Group, RenderableType
|
|
16
|
+
from rich.padding import Padding
|
|
17
|
+
from rich.style import Style
|
|
18
|
+
from rich.syntax import Syntax
|
|
19
|
+
from rich.text import Text
|
|
20
|
+
from textual import work
|
|
21
|
+
from textual.app import ComposeResult
|
|
22
|
+
from textual.containers import Vertical
|
|
23
|
+
from textual.screen import ModalScreen
|
|
24
|
+
from textual.widgets import Button, DataTable, Footer, Header, Input, Label, Static
|
|
25
|
+
|
|
26
|
+
from ..api import generated
|
|
27
|
+
from ..api.base import CodehoodAPIError, get_client
|
|
28
|
+
from ..api.generate import ENDPOINTS, arg_name, snake_case
|
|
29
|
+
from ..api.openapi import Endpoint, JSONSchema, OpenAPISpec, Operation, load_openapi
|
|
30
|
+
from ..theme import CodehoodApp, role_style
|
|
31
|
+
from .base import app
|
|
32
|
+
|
|
33
|
+
__all__ = ["api"]
|
|
34
|
+
|
|
35
|
+
#: (field name, required, mask input) triples, in schema order.
|
|
36
|
+
FieldSpec = tuple[str, bool, bool]
|
|
37
|
+
|
|
38
|
+
METHOD_ROLE = {
|
|
39
|
+
"GET": "success",
|
|
40
|
+
"POST": "primary",
|
|
41
|
+
"PUT": "warning",
|
|
42
|
+
"PATCH": "accent",
|
|
43
|
+
"DELETE": "error",
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@app.command()
|
|
48
|
+
def api(
|
|
49
|
+
server: Annotated[
|
|
50
|
+
str | None,
|
|
51
|
+
typer.Option(
|
|
52
|
+
"--server",
|
|
53
|
+
help="Codehood server URL. Defaults to the current repository's codehood.toml.",
|
|
54
|
+
),
|
|
55
|
+
] = None,
|
|
56
|
+
) -> None:
|
|
57
|
+
"""
|
|
58
|
+
Browse the REST API endpoints `codehood` knows about.
|
|
59
|
+
"""
|
|
60
|
+
try:
|
|
61
|
+
spec_data = fetch_spec(server)
|
|
62
|
+
except httpx.HTTPError as exc:
|
|
63
|
+
typer.echo(f"error: could not fetch the OpenAPI spec: {exc}", err=True)
|
|
64
|
+
raise typer.Exit(code=1) from exc
|
|
65
|
+
|
|
66
|
+
spec = load_openapi(spec_data)
|
|
67
|
+
all_endpoints = spec.operations()
|
|
68
|
+
missing = ENDPOINTS - all_endpoints.keys()
|
|
69
|
+
if missing:
|
|
70
|
+
typer.echo(
|
|
71
|
+
f"error: server spec is missing registered endpoints: {sorted(missing)}",
|
|
72
|
+
err=True,
|
|
73
|
+
)
|
|
74
|
+
raise typer.Exit(code=1)
|
|
75
|
+
|
|
76
|
+
endpoints = {
|
|
77
|
+
operation_id: all_endpoints[operation_id] for operation_id in ENDPOINTS
|
|
78
|
+
}
|
|
79
|
+
# Same `server` the spec was just fetched from, so a call from the
|
|
80
|
+
# browser targets that server too -- `--server` shouldn't stop applying
|
|
81
|
+
# once you press enter on a row.
|
|
82
|
+
ApiBrowser(endpoints, spec, get_client(server)).run()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ApiBrowser(CodehoodApp[None]):
|
|
86
|
+
"""
|
|
87
|
+
Lists the endpoints in `ENDPOINTS`; every detail shown is read live from
|
|
88
|
+
the parsed spec, never hardcoded.
|
|
89
|
+
|
|
90
|
+
Pressing enter on a row calls that endpoint, unless the spec says it
|
|
91
|
+
needs auth we don't have.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
CSS = """
|
|
95
|
+
#detail {
|
|
96
|
+
height: 1fr;
|
|
97
|
+
border: solid $accent;
|
|
98
|
+
padding: 1 2;
|
|
99
|
+
}
|
|
100
|
+
"""
|
|
101
|
+
BINDINGS = [("q", "quit", "Quit")]
|
|
102
|
+
TITLE = "codehood api"
|
|
103
|
+
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
endpoints: dict[str, Endpoint],
|
|
107
|
+
spec: OpenAPISpec,
|
|
108
|
+
client: httpx.Client | None = None,
|
|
109
|
+
) -> None:
|
|
110
|
+
super().__init__()
|
|
111
|
+
self.endpoints = endpoints
|
|
112
|
+
self.spec = spec
|
|
113
|
+
#: Reused for every call so it targets the same server browsing did
|
|
114
|
+
#: -- `--server` shouldn't stop applying once you press enter.
|
|
115
|
+
self.client = client if client is not None else get_client()
|
|
116
|
+
|
|
117
|
+
def compose(self) -> ComposeResult:
|
|
118
|
+
yield Header()
|
|
119
|
+
table: DataTable[str] = DataTable(id="endpoints")
|
|
120
|
+
table.cursor_type = "row"
|
|
121
|
+
table.add_columns("operationId", "method", "path", "summary")
|
|
122
|
+
for operation_id, endpoint in sorted(self.endpoints.items()):
|
|
123
|
+
table.add_row(
|
|
124
|
+
operation_id,
|
|
125
|
+
endpoint.method,
|
|
126
|
+
endpoint.path,
|
|
127
|
+
endpoint.operation.summary,
|
|
128
|
+
key=operation_id,
|
|
129
|
+
)
|
|
130
|
+
yield table
|
|
131
|
+
yield Static(id="detail")
|
|
132
|
+
yield Footer()
|
|
133
|
+
|
|
134
|
+
def on_mount(self) -> None:
|
|
135
|
+
self.query_one(DataTable).focus()
|
|
136
|
+
if self.endpoints:
|
|
137
|
+
self.show_detail(sorted(self.endpoints)[0])
|
|
138
|
+
|
|
139
|
+
def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
|
|
140
|
+
if event.row_key.value is not None:
|
|
141
|
+
self.show_detail(event.row_key.value)
|
|
142
|
+
|
|
143
|
+
def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
|
|
144
|
+
if event.row_key.value is not None:
|
|
145
|
+
self._call_endpoint(event.row_key.value)
|
|
146
|
+
|
|
147
|
+
def show_detail(self, operation_id: str) -> None:
|
|
148
|
+
endpoint = self.endpoints[operation_id]
|
|
149
|
+
operation = endpoint.operation
|
|
150
|
+
renderables: list[RenderableType] = []
|
|
151
|
+
|
|
152
|
+
def render_schema(
|
|
153
|
+
schema: JSONSchema, title: str | None = None
|
|
154
|
+
) -> RenderableType:
|
|
155
|
+
if "$ref" in schema:
|
|
156
|
+
name, schema = self.spec.resolve(schema)
|
|
157
|
+
source = dump_schema_as_yaml(schema)
|
|
158
|
+
group: list[RenderableType] = [Padding(Syntax(source, "yaml"), (0, 2))]
|
|
159
|
+
|
|
160
|
+
if title is not None:
|
|
161
|
+
group = [markup.render(title), *group]
|
|
162
|
+
return Padding(Group(*group), (1, 0, 0, 2))
|
|
163
|
+
|
|
164
|
+
# Head
|
|
165
|
+
renderables.append(
|
|
166
|
+
Text.assemble(
|
|
167
|
+
(
|
|
168
|
+
endpoint.method,
|
|
169
|
+
role_style(METHOD_ROLE.get(endpoint.method, "muted"))
|
|
170
|
+
+ Style(bold=True),
|
|
171
|
+
),
|
|
172
|
+
(f" {endpoint.path}", "bold"),
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
title_style = "bold underline"
|
|
177
|
+
if operation.parameters:
|
|
178
|
+
renderables.append(Text("\nPARAMETERS", style=title_style))
|
|
179
|
+
for parameter in operation.parameters:
|
|
180
|
+
mark = "*" if parameter.required else ""
|
|
181
|
+
schema = render_schema(parameter.content_schema)
|
|
182
|
+
renderables.append(
|
|
183
|
+
f" {parameter.name} ({parameter.location}){mark}: {schema}"
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
if operation.request_body is not None:
|
|
187
|
+
renderables.append(Text("\nBODY", style=title_style))
|
|
188
|
+
for media_type, media in operation.request_body.content.items():
|
|
189
|
+
data = render_schema(
|
|
190
|
+
media.content_schema, title=f"Request Body ({media_type})"
|
|
191
|
+
)
|
|
192
|
+
renderables.append(data)
|
|
193
|
+
|
|
194
|
+
renderables.append(Text("\nRESPONSES", style=title_style))
|
|
195
|
+
for status, response in sorted(operation.responses.items()):
|
|
196
|
+
response_media = response.content.get("application/json")
|
|
197
|
+
if response_media is not None:
|
|
198
|
+
renderables.append(
|
|
199
|
+
render_schema(
|
|
200
|
+
response_media.content_schema,
|
|
201
|
+
title=f"[b]{status}:[/b] {response.description}",
|
|
202
|
+
)
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
self.query_one("#detail", Static).update(Group(*renderables))
|
|
206
|
+
|
|
207
|
+
@work
|
|
208
|
+
async def _call_endpoint(self, operation_id: str) -> None:
|
|
209
|
+
"""
|
|
210
|
+
Runs as a Textual worker: `push_screen_wait` below requires one, and
|
|
211
|
+
it keeps a slow call from blocking the row-selected handler.
|
|
212
|
+
"""
|
|
213
|
+
endpoint = self.endpoints[operation_id]
|
|
214
|
+
operation = endpoint.operation
|
|
215
|
+
|
|
216
|
+
if self.spec.requires_auth(operation):
|
|
217
|
+
self._show_result(
|
|
218
|
+
f"{operation_id} requires authentication, which `codehood login` "
|
|
219
|
+
"doesn't support yet -- refusing rather than sending a request "
|
|
220
|
+
"that would just fail server-side.",
|
|
221
|
+
is_error=True,
|
|
222
|
+
)
|
|
223
|
+
return
|
|
224
|
+
|
|
225
|
+
field_specs = self._field_specs(operation)
|
|
226
|
+
values: dict[str, str] = {}
|
|
227
|
+
if field_specs:
|
|
228
|
+
result = await self.push_screen_wait(CallForm(field_specs))
|
|
229
|
+
if result is None:
|
|
230
|
+
return
|
|
231
|
+
values = result
|
|
232
|
+
|
|
233
|
+
function = getattr(generated, snake_case(operation_id))
|
|
234
|
+
kwargs = self._build_kwargs(operation, values)
|
|
235
|
+
try:
|
|
236
|
+
outcome = await asyncio.to_thread(function, client=self.client, **kwargs)
|
|
237
|
+
except CodehoodAPIError as exc:
|
|
238
|
+
self._show_result(
|
|
239
|
+
f"{type(exc).__name__} (HTTP {exc.status}): {exc.payload}",
|
|
240
|
+
is_error=True,
|
|
241
|
+
)
|
|
242
|
+
except httpx.HTTPError as exc:
|
|
243
|
+
self._show_result(f"request failed: {exc}", is_error=True)
|
|
244
|
+
else:
|
|
245
|
+
self._show_result(str(outcome), is_error=False)
|
|
246
|
+
|
|
247
|
+
def _field_specs(self, operation: Operation) -> list[FieldSpec]:
|
|
248
|
+
specs = [
|
|
249
|
+
(parameter.name, parameter.required, "password" in parameter.name.lower())
|
|
250
|
+
for parameter in operation.parameters
|
|
251
|
+
]
|
|
252
|
+
body_schema = self._body_schema(operation)
|
|
253
|
+
if body_schema is not None:
|
|
254
|
+
required = set(body_schema.get("required", []))
|
|
255
|
+
for field_name in body_schema.get("properties", {}):
|
|
256
|
+
specs.append(
|
|
257
|
+
(
|
|
258
|
+
field_name,
|
|
259
|
+
field_name in required,
|
|
260
|
+
"password" in field_name.lower(),
|
|
261
|
+
)
|
|
262
|
+
)
|
|
263
|
+
return specs
|
|
264
|
+
|
|
265
|
+
def _body_schema(self, operation: Operation) -> JSONSchema | None:
|
|
266
|
+
if operation.request_body is None:
|
|
267
|
+
return None
|
|
268
|
+
media = operation.request_body.content.get("application/json")
|
|
269
|
+
if media is None or "$ref" not in media.content_schema:
|
|
270
|
+
return None
|
|
271
|
+
_name, schema = self.spec.resolve(media.content_schema)
|
|
272
|
+
return schema
|
|
273
|
+
|
|
274
|
+
def _build_kwargs(
|
|
275
|
+
self, operation: Operation, values: dict[str, str]
|
|
276
|
+
) -> dict[str, Any]:
|
|
277
|
+
# The form collects values under each parameter's wire name (what
|
|
278
|
+
# the detail pane shows); the generated function takes them under
|
|
279
|
+
# the snake_cased argument name.
|
|
280
|
+
kwargs: dict[str, Any] = {
|
|
281
|
+
arg_name(parameter.name): values[parameter.name]
|
|
282
|
+
for parameter in operation.parameters
|
|
283
|
+
if parameter.name in values
|
|
284
|
+
}
|
|
285
|
+
if operation.request_body is not None:
|
|
286
|
+
media = operation.request_body.content.get("application/json")
|
|
287
|
+
if media is not None and "$ref" in media.content_schema:
|
|
288
|
+
model_name, schema = self.spec.resolve(media.content_schema)
|
|
289
|
+
body_values = {
|
|
290
|
+
name: values[name]
|
|
291
|
+
for name in schema.get("properties", {})
|
|
292
|
+
if name in values
|
|
293
|
+
}
|
|
294
|
+
body_model = getattr(generated, model_name)
|
|
295
|
+
kwargs["body"] = body_model(**body_values)
|
|
296
|
+
return kwargs
|
|
297
|
+
|
|
298
|
+
def _show_result(self, text: str, *, is_error: bool) -> None:
|
|
299
|
+
style = role_style("error" if is_error else "success") + Style(bold=True)
|
|
300
|
+
self.query_one("#detail", Static).update(Text(text, style=style))
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
class CallForm(ModalScreen[dict[str, str] | None]):
|
|
304
|
+
"""
|
|
305
|
+
One text `Input` per field an operation's call needs (its request body's
|
|
306
|
+
fields, plus any path/query parameters). Dismisses with `None` on
|
|
307
|
+
cancel, or `{field_name: value}` on submit.
|
|
308
|
+
"""
|
|
309
|
+
|
|
310
|
+
BINDINGS = [("escape", "cancel", "Cancel")]
|
|
311
|
+
|
|
312
|
+
CSS = """
|
|
313
|
+
CallForm {
|
|
314
|
+
align: center middle;
|
|
315
|
+
}
|
|
316
|
+
#form {
|
|
317
|
+
width: 60;
|
|
318
|
+
height: auto;
|
|
319
|
+
border: solid $accent;
|
|
320
|
+
padding: 1 2;
|
|
321
|
+
background: $surface;
|
|
322
|
+
}
|
|
323
|
+
"""
|
|
324
|
+
|
|
325
|
+
def __init__(self, fields: list[FieldSpec]) -> None:
|
|
326
|
+
super().__init__()
|
|
327
|
+
self.fields = fields
|
|
328
|
+
|
|
329
|
+
def compose(self) -> ComposeResult:
|
|
330
|
+
with Vertical(id="form"):
|
|
331
|
+
for name, required, secret in self.fields:
|
|
332
|
+
yield Label(f"{name}{'*' if required else ''}")
|
|
333
|
+
yield Input(password=secret, id=f"field-{name}")
|
|
334
|
+
yield Button("Submit", id="submit", variant="primary")
|
|
335
|
+
|
|
336
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
337
|
+
if event.button.id == "submit":
|
|
338
|
+
self._submit()
|
|
339
|
+
|
|
340
|
+
def on_input_submitted(self, event: Input.Submitted) -> None:
|
|
341
|
+
self._submit()
|
|
342
|
+
|
|
343
|
+
def _submit(self) -> None:
|
|
344
|
+
values: dict[str, str] = {}
|
|
345
|
+
for name, required, _secret in self.fields:
|
|
346
|
+
value = self.query_one(f"#field-{name}", Input).value
|
|
347
|
+
if required and not value:
|
|
348
|
+
self.notify(f"{name} is required", severity="error")
|
|
349
|
+
return
|
|
350
|
+
values[name] = value
|
|
351
|
+
self.dismiss(values)
|
|
352
|
+
|
|
353
|
+
def action_cancel(self) -> None:
|
|
354
|
+
self.dismiss(None)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
#
|
|
358
|
+
# Utilities
|
|
359
|
+
#
|
|
360
|
+
def dump_schema_as_yaml(schema: JSONSchema, inline_threshold: int = 40) -> str:
|
|
361
|
+
"""
|
|
362
|
+
Render a JSON schema as YAML, for display in the API browser.
|
|
363
|
+
|
|
364
|
+
The spec's OpenAPI document is JSON, but YAML is more readable for
|
|
365
|
+
humans. This is only used for display, so it doesn't need to be
|
|
366
|
+
round-trippable.
|
|
367
|
+
"""
|
|
368
|
+
|
|
369
|
+
def quote(v: Any) -> str:
|
|
370
|
+
if isinstance(v, str):
|
|
371
|
+
return f'"{v}"'
|
|
372
|
+
return str(v)
|
|
373
|
+
|
|
374
|
+
def label(value: str) -> str:
|
|
375
|
+
# A parameter's own schema (e.g. a query param typed `boolean`) has
|
|
376
|
+
# no `properties` -- it's rendered as its bare type, with no `key:`
|
|
377
|
+
# prefix, rather than assuming every schema describes an object.
|
|
378
|
+
return value if key is None else f"{key}: {value}"
|
|
379
|
+
|
|
380
|
+
properties = schema.get("properties")
|
|
381
|
+
items = properties.items() if properties is not None else [(None, schema)]
|
|
382
|
+
|
|
383
|
+
lines = []
|
|
384
|
+
for key, prop in items:
|
|
385
|
+
prop = prop.copy()
|
|
386
|
+
line = label(prop["type"])
|
|
387
|
+
comments = []
|
|
388
|
+
|
|
389
|
+
if "enum" in prop and len(prop["enum"]) == 1:
|
|
390
|
+
# A single-value enum is a constant, so show it as such.
|
|
391
|
+
line = label(quote(prop["enum"][0]))
|
|
392
|
+
del prop["enum"]
|
|
393
|
+
|
|
394
|
+
if "description" in prop:
|
|
395
|
+
comments.append(prop["description"].removesuffix("."))
|
|
396
|
+
if "enum" in prop:
|
|
397
|
+
cases = " | ".join(quote(case) for case in prop["enum"])
|
|
398
|
+
comments.append(f"enum: {cases}")
|
|
399
|
+
if "minLength" in prop:
|
|
400
|
+
comments.append(f"length >= {prop['minLength']}")
|
|
401
|
+
if "maxLength" in prop:
|
|
402
|
+
comments.append(f"length <= {prop['maxLength']}")
|
|
403
|
+
|
|
404
|
+
if comments:
|
|
405
|
+
comments_data = "; ".join(comments)
|
|
406
|
+
if len(comments_data) > inline_threshold:
|
|
407
|
+
# If the comments are long, put them on a separate line so they
|
|
408
|
+
# don't wrap in the middle of a sentence.
|
|
409
|
+
line = f"# {comments_data}\n{line}"
|
|
410
|
+
else:
|
|
411
|
+
line += " # " + "; ".join(comments)
|
|
412
|
+
|
|
413
|
+
lines.append(line)
|
|
414
|
+
|
|
415
|
+
return "\n".join(lines)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def fetch_spec(server: str | None) -> dict[str, Any]:
|
|
419
|
+
client = get_client(server)
|
|
420
|
+
response = client.get("/openapi.json")
|
|
421
|
+
response.raise_for_status()
|
|
422
|
+
return response.json()
|