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.
Files changed (71) hide show
  1. codehood/__init__.py +0 -0
  2. codehood/__main__.py +4 -0
  3. codehood/actions/__init__.py +0 -0
  4. codehood/actions/base.py +119 -0
  5. codehood/actions/resources.py +30 -0
  6. codehood/api/__init__.py +0 -0
  7. codehood/api/base.py +256 -0
  8. codehood/api/generate.py +1370 -0
  9. codehood/api/generated.py +3818 -0
  10. codehood/api/openapi.py +134 -0
  11. codehood/api/pages.py +53 -0
  12. codehood/cli/__init__.py +64 -0
  13. codehood/cli/api.py +422 -0
  14. codehood/cli/attendance.py +136 -0
  15. codehood/cli/auth.py +106 -0
  16. codehood/cli/base.py +42 -0
  17. codehood/cli/chill.py +52 -0
  18. codehood/cli/exam.py +107 -0
  19. codehood/cli/grades.py +185 -0
  20. codehood/cli/init.py +161 -0
  21. codehood/cli/push.py +609 -0
  22. codehood/cli/show.py +77 -0
  23. codehood/cli/uitils.py +26 -0
  24. codehood/functional.py +40 -0
  25. codehood/globs.py +71 -0
  26. codehood/grades.py +74 -0
  27. codehood/hypothesis.py +274 -0
  28. codehood/models/__init__.py +0 -0
  29. codehood/models/base.py +15 -0
  30. codehood/models/repo.py +187 -0
  31. codehood/models/validators.py +177 -0
  32. codehood/push/__init__.py +225 -0
  33. codehood/push/base.py +216 -0
  34. codehood/push/calendar.py +664 -0
  35. codehood/push/errors.py +136 -0
  36. codehood/push/exam.py +636 -0
  37. codehood/push/exclude.py +60 -0
  38. codehood/push/grades.py +455 -0
  39. codehood/push/hook.py +48 -0
  40. codehood/push/links.py +614 -0
  41. codehood/push/ours.py +78 -0
  42. codehood/push/plan.py +1981 -0
  43. codehood/push/project.py +272 -0
  44. codehood/push/question.py +338 -0
  45. codehood/push/report.py +244 -0
  46. codehood/push/repository.py +326 -0
  47. codehood/push/resource.py +576 -0
  48. codehood/push/run.py +1275 -0
  49. codehood/push/unconsumed.py +208 -0
  50. codehood/push/wire.py +222 -0
  51. codehood/py.typed +0 -0
  52. codehood/repo/__init__.py +62 -0
  53. codehood/repo/_config.py +28 -0
  54. codehood/repo/_layout.py +132 -0
  55. codehood/repo/_scaffold.py +244 -0
  56. codehood/repo/diff.py +71 -0
  57. codehood/repo/file_tracker.py +124 -0
  58. codehood/theme.py +101 -0
  59. codehood/widgets/__init__.py +0 -0
  60. codehood/widgets/mascot.py +76 -0
  61. codehood/widgets/questions/__init__.py +65 -0
  62. codehood/widgets/questions/base.py +119 -0
  63. codehood/widgets/questions/controls.py +194 -0
  64. codehood/widgets/questions/fill_in.py +81 -0
  65. codehood/widgets/questions/responses.py +137 -0
  66. codehood/widgets/questions/simple.py +117 -0
  67. codehood_cli-0.5.0.dist-info/METADATA +294 -0
  68. codehood_cli-0.5.0.dist-info/RECORD +71 -0
  69. codehood_cli-0.5.0.dist-info/WHEEL +4 -0
  70. codehood_cli-0.5.0.dist-info/entry_points.txt +4 -0
  71. codehood_cli-0.5.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1370 @@
1
+ """
2
+ `python -m codehood_cli.api.generate`: writes `api/generated.py` from a
3
+ server's OpenAPI document.
4
+
5
+ See `dev/specs/to-do/api.md` for the design this follows -- in short: every
6
+ name in `ENDPOINTS` must exist in the spec as an `operationId`, and each one
7
+ becomes a typed function plus whatever request/response/error models it
8
+ needs, all folded into one generated module.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import keyword
15
+ import re
16
+ import shutil
17
+ import subprocess
18
+ from collections import Counter
19
+ from collections.abc import Callable, Iterable
20
+ from pathlib import Path
21
+ from typing import Annotated, Any, NamedTuple
22
+
23
+ import httpx
24
+ import typer
25
+
26
+ from .openapi import Endpoint, JSONSchema, OpenAPISpec, Operation, load_openapi
27
+
28
+ type JSON = dict[str, Any]
29
+
30
+
31
+ def _crud(name: str) -> set[str]:
32
+ """
33
+ Expand a CRUD operation name to the five standard operations.
34
+ """
35
+ entity = name[:1].upper() + name[1:]
36
+ return {
37
+ f"{op}{entity}"
38
+ for op in ("create", "read", "list", "update", "delete", "upsert")
39
+ }
40
+
41
+
42
+ #: `operationId`s this CLI generates a typed function for. See the spec's
43
+ #: "`ENDPOINTS` is the one hand-maintained list" -- adding an id here that
44
+ #: the spec doesn't define is a generation-time error, not a silent no-op.
45
+ ENDPOINTS = {
46
+ "health",
47
+ "login",
48
+ "logout",
49
+ *_crud("course"),
50
+ *_crud("discipline"),
51
+ *_crud("edition"),
52
+ *_crud("user"),
53
+ *_crud("resource"),
54
+ *_crud("question"),
55
+ *_crud("timeslot"),
56
+ *_crud("calendar-event"),
57
+ *_crud("exam"),
58
+ *_crud("grade-column"),
59
+ "courseGrades",
60
+ "courseAttendance",
61
+ "examRelease",
62
+ "repositoryList",
63
+ "repositoryUpsert",
64
+ "repositoryDelete",
65
+ "blobMissing",
66
+ "rubricRead",
67
+ "rubricUpdate",
68
+ "rubricItemCreate",
69
+ "rubricItemUpdate",
70
+ "rubricItemPut",
71
+ "rubricItemDelete",
72
+ "rubricItemSplit",
73
+ "rubricRenameGroup",
74
+ "rubricPreview",
75
+ "listRoll-call",
76
+ "readRoll-call",
77
+ "updateRoll-call",
78
+ "deleteRoll-call",
79
+ "claimGradingJobs",
80
+ "renewGradingJob",
81
+ "failGradingJob",
82
+ "reportGradingJob",
83
+ # `file` is absent: `/api/file` is not in the document while the
84
+ # multipart upload is being written (see `ROADBLOCKS.md` item 1).
85
+ }
86
+
87
+ GENERATED_HEADER = "# This file is AUTO-GENERATED. DO NOT EDIT!\n"
88
+
89
+ _PRIMITIVE_TYPES = {
90
+ "string": "str",
91
+ "integer": "int",
92
+ "number": "float",
93
+ "boolean": "bool",
94
+ }
95
+
96
+
97
+ class UnsupportedSchemaError(NotImplementedError):
98
+ """
99
+ A schema needs JSON Schema features the type mapper doesn't cover yet.
100
+
101
+ See `dev/specs/to-review/api-nested-schemas.md`, "What still raises
102
+ `UnsupportedSchemaError`": `allOf`, `not`, list-valued `type`, and any
103
+ node with no `type`, `$ref`, or `anyOf`/`oneOf`.
104
+ """
105
+
106
+
107
+ #
108
+ # The generator
109
+ #
110
+ class Generator:
111
+ def __init__(self, spec: JSON) -> None:
112
+ self.spec = load_openapi(spec)
113
+ self.endpoints = self.spec.operations()
114
+ missing = ENDPOINTS - self.endpoints.keys()
115
+ if missing:
116
+ print("COMPLETE LIST OF ENDPOINTS IN SPEC:")
117
+ for endpoint in sorted(self.endpoints.keys()):
118
+ print(f"- {endpoint}")
119
+ raise KeyError(
120
+ f"ENDPOINTS names operations not in the spec: {sorted(missing)}"
121
+ )
122
+
123
+ def generate(self) -> str:
124
+ """
125
+ Generate `api/generated.py`'s full source from the spec.
126
+ """
127
+ needed: dict[str, JSONSchema] = {}
128
+ exceptions_needed: dict[str, JSONSchema] = {}
129
+ shapes = ShapeRegistry(self.spec, ENDPOINTS)
130
+
131
+ functions = [
132
+ render_function(
133
+ operation_id,
134
+ self.endpoints[operation_id],
135
+ TypeCtx(self.spec, needed, shapes),
136
+ TypeCtx(self.spec, exceptions_needed, shapes),
137
+ )
138
+ for operation_id in sorted(ENDPOINTS)
139
+ ]
140
+ needs_auth_headers = any(
141
+ self.spec.requires_auth(self.endpoints[operation_id].operation)
142
+ for operation_id in ENDPOINTS
143
+ )
144
+
145
+ # A schema used as a documented error is rendered only as an
146
+ # exception -- see the spec's "one exception class per schema".
147
+ for name in exceptions_needed:
148
+ needed.pop(name, None)
149
+
150
+ # Exceptions first: their payloads can reach models (a nested shape)
151
+ # that no other operation does, and those must be rendered too.
152
+ exceptions = [
153
+ render_exception(name, schema, TypeCtx(self.spec, needed, shapes))
154
+ for name, schema in sorted(exceptions_needed.items())
155
+ ]
156
+ models = self._render_models(needed, shapes, exclude=exceptions_needed.keys())
157
+
158
+ body = models + exceptions + functions
159
+ imports = self._render_imports(
160
+ needs_literal=any("Literal[" in part for part in body),
161
+ # `dict[str, Any]` is the only place `Any` appears in generated
162
+ # source -- see the spec's "free-form object" rule.
163
+ needs_any=any("dict[str, Any]" in part for part in body),
164
+ pydantic_names={
165
+ name
166
+ for name, marker in [
167
+ ("ConfigDict", "ConfigDict("),
168
+ ("Field", "Field(alias="),
169
+ ("TypeAdapter", "TypeAdapter("),
170
+ ]
171
+ if any(marker in part for part in body)
172
+ },
173
+ needs_auth_headers=needs_auth_headers,
174
+ needs_query_params=any("query_params(" in part for part in body),
175
+ needs_header_params=any("header_params(" in part for part in body),
176
+ )
177
+ parts = [GENERATED_HEADER, imports, *body]
178
+ return "\n\n".join(part.rstrip() for part in parts) + "\n"
179
+
180
+ def _render_models(
181
+ self,
182
+ needed: dict[str, JSONSchema],
183
+ shapes: ShapeRegistry,
184
+ *,
185
+ exclude: Iterable[str],
186
+ ) -> list[str]:
187
+ """
188
+ Render every schema `needed` transitively reaches, as plain models.
189
+
190
+ A worklist rather than a single pass over `needed`, because
191
+ rendering one model can discover another (a field referencing a
192
+ schema nobody had reached yet).
193
+ """
194
+ rendered: dict[str, str] = {}
195
+ dependencies: dict[str, set[str]] = {}
196
+ pending = dict(needed)
197
+ while pending:
198
+ name, schema = pending.popitem()
199
+ if name in rendered or name in exclude:
200
+ continue
201
+ discovered: dict[str, JSONSchema] = {}
202
+ rendered[name] = render_model(
203
+ name, schema, TypeCtx(self.spec, discovered, shapes)
204
+ )
205
+ dependencies[name] = set(discovered) - {name}
206
+ for found_name, found_schema in discovered.items():
207
+ if found_name not in rendered:
208
+ pending[found_name] = found_schema
209
+ return [rendered[name] for name in _dependency_order(dependencies)]
210
+
211
+ def _render_imports(
212
+ self,
213
+ *,
214
+ needs_literal: bool,
215
+ needs_any: bool,
216
+ pydantic_names: set[str],
217
+ needs_auth_headers: bool,
218
+ needs_query_params: bool,
219
+ needs_header_params: bool,
220
+ ) -> str:
221
+ lines = ["from __future__ import annotations", ""]
222
+ typing_names = sorted(
223
+ name
224
+ for name, needed in [("Any", needs_any), ("Literal", needs_literal)]
225
+ if needed
226
+ )
227
+ if typing_names:
228
+ lines += [f"from typing import {', '.join(typing_names)}", ""]
229
+ base_imports = ["CodehoodAPIError"]
230
+ if needs_auth_headers:
231
+ base_imports.append("auth_headers")
232
+ base_imports.append("get_client")
233
+ if needs_header_params:
234
+ base_imports.append("header_params")
235
+ if needs_query_params:
236
+ base_imports.append("query_params")
237
+ lines.append("import httpx")
238
+ if pydantic_names:
239
+ lines.append(f"from pydantic import {', '.join(sorted(pydantic_names))}")
240
+ lines += [
241
+ "",
242
+ "from ..models.base import Model",
243
+ f"from .base import {', '.join(base_imports)}",
244
+ ]
245
+ return "\n".join(lines)
246
+
247
+
248
+ #
249
+ # UTILITIES
250
+ #
251
+ def _unique(items: Iterable[str]) -> list[str]:
252
+ """
253
+ `items` with repeats dropped, first-seen order kept.
254
+ """
255
+ seen: dict[str, None] = {}
256
+ for item in items:
257
+ seen.setdefault(item, None)
258
+ return list(seen)
259
+
260
+
261
+ def _dependency_order(dependencies: dict[str, set[str]]) -> list[str]:
262
+ """
263
+ Model names ordered so a model is defined after everything it names.
264
+
265
+ `from __future__ import annotations` would let pydantic resolve a
266
+ forward reference later, but only by rebuilding the model against its
267
+ module at first use -- which fails outright for anyone who `exec`s the
268
+ source without registering a module. Emitting definitions in
269
+ dependency order costs nothing and makes the file work as plain
270
+ Python. Alphabetical within each layer keeps output deterministic, and
271
+ a `$ref` cycle (nothing in today's spec has one) falls back to
272
+ alphabetical for whatever it can't order.
273
+ """
274
+ ordered: list[str] = []
275
+ remaining = dict(dependencies)
276
+ while remaining:
277
+ ready = sorted(
278
+ name for name, needs in remaining.items() if not needs & remaining.keys()
279
+ ) or sorted(remaining)
280
+ ordered += ready
281
+ for name in ready:
282
+ del remaining[name]
283
+ return ordered
284
+
285
+
286
+ #
287
+ # JSON Schema -> Python type
288
+ #
289
+ def snake_case(identifier: str) -> str:
290
+ """
291
+ `getHealth` -> `get_health`; `instructorUsername` -> `instructor_username`.
292
+
293
+ The second pattern keeps a run of capitals together (`userID` ->
294
+ `user_id`, not `user_i_d`), splitting it only where the last capital
295
+ starts a new word.
296
+ """
297
+ words = re.sub(r"[^0-9a-zA-Z]+", "_", identifier)
298
+ return re.sub(
299
+ r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", words
300
+ ).lower()
301
+
302
+
303
+ #: `render_function` gives every generated function a `client` keyword, so a
304
+ #: parameter of that name would collide with it.
305
+ _RESERVED_ARG_NAMES = {"client", "body"}
306
+
307
+
308
+ def arg_name(parameter_name: str) -> str:
309
+ """
310
+ The Python argument name for a request parameter.
311
+
312
+ The wire name stays whatever the server called it -- only the argument
313
+ a caller types is converted, and only far enough to be a usable
314
+ identifier that doesn't collide with the keywords `render_function`
315
+ adds itself.
316
+ """
317
+ name = snake_case(parameter_name)
318
+ if keyword.iskeyword(name) or name in _RESERVED_ARG_NAMES:
319
+ return f"{name}_"
320
+ if not name.isidentifier():
321
+ return "arg_" + re.sub(r"\W", "_", name)
322
+ return name
323
+
324
+
325
+ def pascal(identifier: str) -> str:
326
+ """
327
+ `readCourse` -> `ReadCourse`; `discipline` -> `Discipline`.
328
+
329
+ Used both for an operation id (naming a top-level minted request/
330
+ response/error model) and a property name (naming a nested one) --
331
+ the server only ever hands us camelCase identifiers, so capitalizing
332
+ the first letter is the whole job.
333
+ """
334
+ return identifier[:1].upper() + identifier[1:]
335
+
336
+
337
+ def py_class_name(name: str) -> str:
338
+ """
339
+ `Calendar Event` -> `CalendarEvent`; `upsertCalendar-event` ->
340
+ `UpsertCalendarEvent`.
341
+
342
+ A schema name and an `operationId` are the server's prose, not Python
343
+ identifiers: the document spells some of them with spaces or hyphens.
344
+ Splitting on anything that is not alphanumeric and capitalizing each
345
+ word is the whole conversion, and it leaves a name that already is an
346
+ identifier untouched.
347
+ """
348
+ words = [word for word in re.split(r"[^0-9a-zA-Z]+", name) if word]
349
+ return "".join(pascal(word) for word in words)
350
+
351
+
352
+ def safe_field_name(property_name: str) -> str:
353
+ """
354
+ A property name pydantic will actually carry as a public field.
355
+
356
+ The server emits `_count` on every list-bearing response, and pydantic
357
+ treats a leading underscore as a *private* attribute -- declaring one
358
+ silently drops the field, taking the server's data with it. Such names
359
+ (and Python keywords) become a plain identifier here; the caller pairs
360
+ the result with `Field(alias=...)` so the wire format is unchanged.
361
+ """
362
+ name = property_name.lstrip("_")
363
+ if keyword.iskeyword(name):
364
+ return f"{name}_"
365
+ if not name.isidentifier():
366
+ return "field_" + re.sub(r"\W", "_", property_name)
367
+ return name
368
+
369
+
370
+ def field_name(property_name: str) -> str:
371
+ """
372
+ The Python attribute name for a JSON property.
373
+
374
+ Snake_cased from the wire name -- the wire name itself is kept as
375
+ `Field(alias=...)` whenever it differs, so the JSON payload is
376
+ unaffected. Built on top of `safe_field_name` for the leading-
377
+ underscore/keyword handling, then re-checked for a keyword collision
378
+ `snake_case` itself can introduce (`Class` -> `class`).
379
+ """
380
+ name = snake_case(safe_field_name(property_name))
381
+ if keyword.iskeyword(name):
382
+ return f"{name}_"
383
+ return name
384
+
385
+
386
+ #: Name-candidate tiers, best first -- see the spec's naming rules.
387
+ #: A tagged union member outranks every other candidate: `DataMd` says what
388
+ #: the shape *is*, where the container's own `Data` says only where it was
389
+ #: found, and all four members of a union are found in the same place. A
390
+ #: projection of a component schema (`_TIER_SUBTYPE`, see
391
+ #: `_projection_name`) comes next: it names the entity the shape is a
392
+ #: cut-down view of, which the property name alone cannot say.
393
+ _TIER_VARIANT = 0
394
+ _TIER_SUBTYPE = 1
395
+ _TIER_PROPERTY = 2
396
+ _TIER_ENTITY = 3
397
+ _TIER_SITE = 4
398
+
399
+ #: CRUD verbs `_crud` builds operation ids from. Stripping one off an
400
+ #: operation id leaves the entity the operation is about, which is the best
401
+ #: available name for the shape that operation returns (`readCourse` ->
402
+ #: `Course`).
403
+ _CRUD_VERBS = ("create", "read", "list", "update", "delete", "upsert")
404
+
405
+
406
+ def shape_id(schema: JSONSchema) -> str:
407
+ """
408
+ An inline object schema's identity for deduplication: its *structure*.
409
+
410
+ The server is TypeScript/zod, i.e. structurally typed, so two inline
411
+ schemas with the same shape are the same type and deserve one generated
412
+ class. Raw JSON is the wrong identity for that: the exam's `duration`
413
+ and the time slot's `duration` differ only by a `nullable` flag and a
414
+ `description`, neither of which `render_model` emits, yet byte
415
+ comparison calls them two types.
416
+
417
+ So the identity is the reduction of a schema to what the generator
418
+ actually renders -- see `_structure`. A node's own `nullable` is
419
+ dropped here because it lands on the *field* that holds the object, not
420
+ on the class.
421
+ """
422
+ structure = _structure(schema)
423
+ if isinstance(structure, dict):
424
+ structure.pop("nullable", None)
425
+ return json.dumps(structure, sort_keys=True)
426
+
427
+
428
+ def _structure(schema: JSONSchema) -> object:
429
+ """
430
+ A schema reduced to the parts that reach generated source.
431
+
432
+ `type`, `enum`, `nullable`, union members, array items, property names
433
+ with their optionality, and `additionalProperties`. Everything else --
434
+ `description`, `minimum`, `pattern`, `examples`, `format` -- is
435
+ documentation the generator drops, so it must not split one class into
436
+ two. A `$ref` reduces to the reference itself: it renders as the target
437
+ class's name, which an inline copy of the same shape would not.
438
+
439
+ Property *order* is kept, since it is the order fields are emitted in.
440
+ """
441
+ if not isinstance(schema, dict):
442
+ return None
443
+ if "$ref" in schema:
444
+ return {"$ref": schema["$ref"]}
445
+
446
+ node: dict[str, object] = {}
447
+ for key in ("type", "enum", "nullable"):
448
+ if key in schema:
449
+ node[key] = schema[key]
450
+ for key in ("anyOf", "oneOf", "allOf"):
451
+ members = schema.get(key)
452
+ if members is not None:
453
+ node[key] = [_structure(member) for member in members]
454
+ if schema.get("type") == "array":
455
+ node["items"] = _structure(schema.get("items", {}))
456
+
457
+ properties = schema.get("properties")
458
+ if properties is not None:
459
+ required = set(schema.get("required", []))
460
+ node["properties"] = [
461
+ [name, name in required, _structure(property_schema)]
462
+ for name, property_schema in properties.items()
463
+ ]
464
+
465
+ additional = schema.get("additionalProperties")
466
+ if isinstance(additional, dict):
467
+ node["additionalProperties"] = _structure(additional)
468
+ elif additional is not None:
469
+ node["additionalProperties"] = bool(additional)
470
+ return node
471
+
472
+
473
+ def _is_projection(schema: JSONSchema, component: JSONSchema) -> bool:
474
+ """
475
+ Whether `schema` is a strictly smaller view of `component`.
476
+
477
+ Every property of `schema` is a property of `component` with the same
478
+ shape, and `component` has at least one more. `required` is compared by
479
+ neither: the same embedded thing is optional at one site and mandatory
480
+ at another, and that says nothing about which type it is.
481
+ """
482
+ properties = schema.get("properties") or {}
483
+ component_properties = component.get("properties") or {}
484
+ if not set(properties) < set(component_properties):
485
+ return False
486
+ return all(
487
+ _structure(property_schema) == _structure(component_properties[name])
488
+ for name, property_schema in properties.items()
489
+ )
490
+
491
+
492
+ class ShapeRegistry:
493
+ """
494
+ Names every inline `object` schema the spec reaches, before any of it
495
+ is rendered.
496
+
497
+ The name a shape deserves depends on every place it appears, not just
498
+ the first one reached -- `discipline` is a better name for the shape
499
+ behind `readDiscipline`'s response than `ReadDisciplineResponse` is,
500
+ and only a whole-spec pass can know a property named `discipline`
501
+ holds it. So collection and naming happen up front, and `py_type`
502
+ later just looks a shape up.
503
+ """
504
+
505
+ def __init__(self, spec: OpenAPISpec, operation_ids: Iterable[str]) -> None:
506
+ self.spec = spec
507
+ #: shape -> {tier: {candidate names}}, filled by `_collect`.
508
+ self._candidates: dict[str, dict[int, set[str]]] = {}
509
+ #: shape -> shapes holding it as a property value, filled by
510
+ #: `_collect`. A contested name is qualified by one of these.
511
+ self._owners: dict[str, set[str]] = {}
512
+ #: shape -> how deeply nested the shallowest occurrence of it is,
513
+ #: counting one per property hop. Used only to pick which owner
514
+ #: qualifies a contested name.
515
+ self._depths: dict[str, int] = {}
516
+ #: Components already walked by `_collect`, by identity.
517
+ self._visited: set[int] = set()
518
+ #: Every `$ref`able object schema, by class name and by shape. An
519
+ #: inline shape that matches one *is* it (`_assign_names`) or is a
520
+ #: projection of it (`_projection_name`).
521
+ self._components = {
522
+ py_class_name(name): schema
523
+ for name, schema in spec.components.schemas.items()
524
+ if isinstance(schema, dict) and schema.get("properties")
525
+ }
526
+ self._component_shapes: dict[str, str] = {}
527
+ for class_name in sorted(self._components):
528
+ self._component_shapes.setdefault(
529
+ shape_id(self._components[class_name]), class_name
530
+ )
531
+ endpoints = spec.operations()
532
+ for operation_id in sorted(operation_ids):
533
+ self._collect_operation(operation_id, endpoints[operation_id].operation)
534
+ self._names = self._assign_names()
535
+
536
+ def name_for(self, schema: JSONSchema) -> str:
537
+ return self._names[shape_id(schema)]
538
+
539
+ #
540
+ # Collection
541
+ #
542
+ def _collect_operation(self, operation_id: str, operation: Operation) -> None:
543
+ op_pascal = py_class_name(operation_id)
544
+ entity = _crud_entity(operation_id)
545
+
546
+ request_body = operation.request_body
547
+ if request_body is not None:
548
+ media = request_body.content.get("application/json")
549
+ if media is not None:
550
+ self._collect(
551
+ media.content_schema,
552
+ [(_TIER_SITE, f"{op_pascal}Request")],
553
+ entity=entity,
554
+ )
555
+
556
+ for status, response in operation.responses.items():
557
+ media = response.content.get("application/json")
558
+ if media is None:
559
+ continue
560
+ if status.startswith("2"):
561
+ candidates = [(_TIER_SITE, f"{op_pascal}Response")]
562
+ if entity is not None:
563
+ candidates.append((_TIER_ENTITY, entity))
564
+ else:
565
+ candidates = [(_TIER_SITE, f"{op_pascal}Error{status}")]
566
+ self._collect(media.content_schema, candidates, entity=entity)
567
+
568
+ def _collect(
569
+ self,
570
+ schema: JSONSchema,
571
+ candidates: list[tuple[int, str]],
572
+ owner: str | None = None,
573
+ depth: int = 0,
574
+ entity: str | None = None,
575
+ ) -> None:
576
+ """
577
+ Walk one schema, recording a name candidate for every inline
578
+ object under it. `candidates` are `(tier, name)` for *this* node;
579
+ a property's shape proposes `Pascal(property)` at `_TIER_PROPERTY`,
580
+ and an array's items propose their container's names with `Item`
581
+ appended.
582
+
583
+ `owner` is the shape of the nearest enclosing object, used to
584
+ qualify a name two shapes fight over. A union member or an array
585
+ item is held by whatever holds its container, so it inherits the
586
+ same owner. `entity` is what the whole operation is about, carried
587
+ all the way down because a projection is named after it -- see
588
+ `_projection_name`.
589
+ """
590
+ if not isinstance(schema, dict):
591
+ return
592
+ if "$ref" in schema:
593
+ # A component that is a bare union has no class of its own (see
594
+ # `py_type`), so its members are named as if it were inlined here.
595
+ _, resolved = self.spec.resolve(schema)
596
+ if _is_union_component(resolved):
597
+ self._collect(resolved, candidates, owner, depth, entity)
598
+ elif id(resolved) not in self._visited:
599
+ # A component that holds inline objects (`Rubric.items`)
600
+ # has them named here, since nothing else walks it.
601
+ self._visited.add(id(resolved))
602
+ self._collect(resolved, [], owner, depth, entity)
603
+ return
604
+
605
+ for member in schema.get("anyOf") or schema.get("oneOf") or []:
606
+ self._collect(
607
+ member, _variant_candidates(member, candidates), owner, depth, entity
608
+ )
609
+
610
+ if schema.get("type") == "array":
611
+ # A site name describes the whole response, so its item is that
612
+ # plus `Item`. An entity name describes the thing itself, and
613
+ # `listCourse` returns a list *of* those -- `Course` is already
614
+ # the item's name, not the list's.
615
+ item_candidates = [
616
+ (tier, name if tier == _TIER_ENTITY else f"{name}Item")
617
+ for tier, name in candidates
618
+ ]
619
+ self._collect(
620
+ schema.get("items", {}), item_candidates, owner, depth, entity
621
+ )
622
+ return
623
+
624
+ if schema.get("type") != "object":
625
+ return
626
+
627
+ additional = schema.get("additionalProperties")
628
+ if isinstance(additional, dict):
629
+ self._collect(additional, [], owner, depth, entity)
630
+
631
+ properties = schema.get("properties")
632
+ if not properties:
633
+ return
634
+
635
+ shape = shape_id(schema)
636
+ tiers = self._candidates.setdefault(shape, {})
637
+ for tier, name in candidates:
638
+ tiers.setdefault(tier, set()).add(name)
639
+ projection = self._projection_name(schema, candidates, entity)
640
+ if projection is not None:
641
+ tiers.setdefault(_TIER_SUBTYPE, set()).add(projection)
642
+ if owner is not None:
643
+ self._owners.setdefault(shape, set()).add(owner)
644
+ self._depths[shape] = min(self._depths.get(shape, depth), depth)
645
+
646
+ for property_name, property_schema in properties.items():
647
+ self._collect(
648
+ property_schema,
649
+ [(_TIER_PROPERTY, pascal(safe_field_name(property_name)))],
650
+ shape,
651
+ depth + 1,
652
+ entity,
653
+ )
654
+
655
+ def _projection_name(
656
+ self,
657
+ schema: JSONSchema,
658
+ candidates: list[tuple[int, str]],
659
+ entity: str | None,
660
+ ) -> str | None:
661
+ """
662
+ `{Component}At{Entity}` when `schema` is a cut-down view of a
663
+ component schema, else `None`.
664
+
665
+ `listCalendarEvent`'s items embed `{slug, day, start, duration}`:
666
+ every property of the `TimeSlot` component except the title and the
667
+ ids, with the same shape on each one. That is a *projection* of a
668
+ time slot, and `TimeSlotAtCalendarEvent` says so. The qualifier is
669
+ the entity the operation is about, never the operation id or the
670
+ site, because being in a list response is noise -- the same
671
+ projection reached from `readCalendarEvent` is the same class.
672
+
673
+ A projection is only offered to a shape whose property is named
674
+ after the component (`timeSlot` -> `TimeSlot`). Subset-of-a-
675
+ component on its own is far too loose to name anything by: on this
676
+ spec a bare `{id}` is a strict subset of eight components, and a
677
+ request body is a strict subset of the entity it writes. The
678
+ property name is what makes the match unambiguous -- exactly one
679
+ component can answer to it -- and a shape the server did not name
680
+ after the component is not being presented as one.
681
+
682
+ Required-ness may differ between the two; that is a presentation
683
+ detail of the site, not evidence of a different thing.
684
+ """
685
+ if entity is None:
686
+ return None
687
+ for tier, name in candidates:
688
+ if tier != _TIER_PROPERTY:
689
+ continue
690
+ component = self._components.get(name)
691
+ if component is not None and _is_projection(schema, component):
692
+ return f"{name}At{entity}"
693
+ return None
694
+
695
+ #
696
+ # Naming
697
+ #
698
+ def _assign_names(self) -> dict[str, str]:
699
+ """
700
+ Give each shape a name that depends only on that shape's own
701
+ candidates and on which names the whole document contests.
702
+
703
+ A shape structurally identical to a `$ref`able component schema is
704
+ that schema: it takes the component's class name and renders once,
705
+ however many inline copies of it the document carries. The server
706
+ inlines the same entity on the read paths that it `$ref`s on the
707
+ create path, so this is what keeps `readExam` and `listExam`
708
+ returning `Exam` rather than a site-named twin of it.
709
+
710
+ Otherwise a shape takes its best *uncontested* candidate: best tier
711
+ first, alphabetical within a tier, skipping any name a `$ref`ed component
712
+ schema already owns or that a second shape also proposes. A bare
713
+ name therefore means "exactly one shape in the spec wants this",
714
+ which is a property a reader can rely on and which no other shape's
715
+ arrival can quietly take away.
716
+
717
+ When every candidate is contested, the shape is named
718
+ `{Owner}{Best}` -- the owner being the object that holds it as a
719
+ property (`QuestionTrueFalseChoicesItem`). Qualifying by owner
720
+ rather than by a counter is what makes the output stable: a counter
721
+ numbers shapes in order of appearance, so adding one endpoint
722
+ renumbers models belonging to another (this is exactly how the time
723
+ slot's `Duration` silently became `Duration2`), while an owner is a
724
+ fact about the shape itself.
725
+ """
726
+ reserved = {py_class_name(name) for name in self.spec.components.schemas}
727
+ ordered = {
728
+ shape: _unique(
729
+ [name for tier in sorted(tiers) for name in sorted(tiers[tier])]
730
+ )
731
+ for shape, tiers in self._candidates.items()
732
+ }
733
+ proposals = Counter(name for names in ordered.values() for name in names)
734
+ # Every name any shape proposes is off limits as a qualified name:
735
+ # whether the proposer actually ends up using it is irrelevant, and
736
+ # ignoring that keeps qualification order-independent too.
737
+ blocked = reserved | set(proposals)
738
+
739
+ names: dict[str, str] = {}
740
+ resolving: set[str] = set()
741
+
742
+ def resolve(shape: str) -> str:
743
+ if shape in names:
744
+ return names[shape]
745
+ if shape in resolving:
746
+ # A shape reachable from itself cannot qualify its own name.
747
+ return ""
748
+ resolving.add(shape)
749
+ component = self._component_shapes.get(shape)
750
+ if component is not None:
751
+ names[shape] = component
752
+ resolving.discard(shape)
753
+ return component
754
+ candidates = ordered[shape]
755
+ free = next(
756
+ (
757
+ name
758
+ for name in candidates
759
+ if name not in reserved and proposals[name] == 1
760
+ ),
761
+ None,
762
+ )
763
+ names[shape] = free or self._qualify(
764
+ candidates, self._owners.get(shape, set()), resolve, blocked, names
765
+ )
766
+ resolving.discard(shape)
767
+ return names[shape]
768
+
769
+ for shape in sorted(ordered):
770
+ resolve(shape)
771
+ return names
772
+
773
+ def _qualify(
774
+ self,
775
+ candidates: list[str],
776
+ owners: set[str],
777
+ resolve: Callable[[str], str],
778
+ blocked: set[str],
779
+ names: dict[str, str],
780
+ ) -> str:
781
+ """
782
+ `{Owner}{Best}` for a shape whose every candidate is contested.
783
+
784
+ A shape can be reached from several owners -- the multiple-choice
785
+ choice appears both under a multiple-choice question and under a
786
+ fill-in blank -- and then the *outermost* owner qualifies it, the
787
+ one closest to the API surface, alphabetically first on a tie. The
788
+ shallow owner is the one a reader meets first, so `Question...` is
789
+ a better prefix than `BlanksItem...` for the same shape.
790
+ """
791
+ base = candidates[0] if candidates else "Shape"
792
+ owner_names = [
793
+ name
794
+ for _depth, name in sorted(
795
+ (self._depths.get(owner, 0), resolve(owner)) for owner in owners
796
+ )
797
+ if name
798
+ ]
799
+ taken = blocked | set(names.values())
800
+ for owner_name in owner_names:
801
+ qualified = f"{owner_name}{base}"
802
+ if qualified not in taken:
803
+ return qualified
804
+
805
+ # Nothing left but a counter: the shape has no owner at all (a
806
+ # response body is held by nothing), or its owner already qualifies
807
+ # a sibling that wants the same name -- two untagged members of one
808
+ # union, which share both owner and base and so cannot be told
809
+ # apart by either. Nothing in today's spec reaches this. The counter
810
+ # still counts onto the owner-qualified name, so at worst one shape
811
+ # of a pair carries a digit rather than both names being positional.
812
+ stem = f"{owner_names[0]}{base}" if owner_names else base
813
+ suffix = 2
814
+ while f"{stem}{suffix}" in taken:
815
+ suffix += 1
816
+ return f"{stem}{suffix}"
817
+
818
+
819
+ def _variant_candidates(
820
+ member: JSONSchema, candidates: list[tuple[int, str]]
821
+ ) -> list[tuple[int, str]]:
822
+ """
823
+ Name candidates for one member of an `anyOf`/`oneOf`.
824
+
825
+ Every member of a union sits at the same site, so inheriting the
826
+ container's candidates unchanged leaves them fighting over one name and
827
+ resolving to `Data`, `Data2`, `Data3`. A member tagged by a
828
+ single-valued `enum` -- the JSON Schema spelling of a discriminated
829
+ union -- proposes `{container}{Tag}` instead, so `data`'s four members
830
+ become `DataLink`, `DataFile`, `DataCode`, and `DataMd`.
831
+
832
+ An untagged member has nothing better to offer and keeps the
833
+ container's candidates as they are.
834
+ """
835
+ tag = _discriminator(member)
836
+ if tag is None:
837
+ return candidates
838
+ suffix = tag_suffix(tag)
839
+ return [(_TIER_VARIANT, f"{name}{suffix}") for _, name in candidates] + candidates
840
+
841
+
842
+ def tag_suffix(tag: str) -> str:
843
+ """
844
+ The class-name suffix a discriminator tag contributes.
845
+
846
+ `FILE` is a tag, not an acronym the reader wants shouted back:
847
+ `DataFile` reads as a class name where `DataFILE` does not. A tag the
848
+ server spells with separators is a phrase, not an identifier, so each
849
+ word is capitalized and the separators dropped -- `multiple-choice`
850
+ gives `QuestionMultipleChoice`, which is a name Python will accept.
851
+ """
852
+ words = [word for word in re.split(r"[^a-zA-Z0-9]+", tag) if word]
853
+ return "".join(word.title() if word.isupper() else pascal(word) for word in words)
854
+
855
+
856
+ def _discriminator(schema: JSONSchema) -> str | None:
857
+ """
858
+ The tag value of a discriminated-union member, if it has one.
859
+
860
+ A property whose schema is a one-value string `enum` is the tag; a
861
+ property literally named `type` wins over any other, since that is what
862
+ the server's own unions use.
863
+ """
864
+ if not isinstance(schema, dict):
865
+ return None
866
+ properties = schema.get("properties")
867
+ if not isinstance(properties, dict):
868
+ return None
869
+
870
+ tags: dict[str, str] = {}
871
+ for name, property_schema in properties.items():
872
+ if not isinstance(property_schema, dict):
873
+ continue
874
+ values = property_schema.get("enum")
875
+ if isinstance(values, list) and len(values) == 1 and isinstance(values[0], str):
876
+ tags[name] = values[0]
877
+
878
+ if "type" in tags:
879
+ return tags["type"]
880
+ return next(iter(tags.values()), None)
881
+
882
+
883
+ def _crud_entity(operation_id: str) -> str | None:
884
+ """`readCourse` -> `Course`; `login` -> `None`."""
885
+ for verb in _CRUD_VERBS:
886
+ if operation_id.startswith(verb) and len(operation_id) > len(verb):
887
+ return py_class_name(operation_id[len(verb) :])
888
+ return None
889
+
890
+
891
+ class TypeCtx(NamedTuple):
892
+ """
893
+ What `py_type` needs besides the schema itself.
894
+
895
+ `needed` accumulates every named schema reached along the way -- both
896
+ `$ref` targets and inline objects the `ShapeRegistry` has minted a name
897
+ for -- so the caller renders exactly the models actually used.
898
+ """
899
+
900
+ spec: OpenAPISpec
901
+ needed: dict[str, JSONSchema]
902
+ shapes: ShapeRegistry
903
+
904
+
905
+ def py_type(schema: JSONSchema, ctx: TypeCtx) -> str:
906
+ """
907
+ Map one JSON Schema node to a Python type annotation.
908
+ """
909
+ if "$ref" in schema:
910
+ ref_name, resolved = ctx.spec.resolve(schema)
911
+ if _is_union_component(resolved):
912
+ return py_type(resolved, ctx)
913
+ name = py_class_name(ref_name)
914
+ ctx.needed[name] = resolved
915
+ return name
916
+
917
+ if "allOf" in schema or "not" in schema or isinstance(schema.get("type"), list):
918
+ raise UnsupportedSchemaError(
919
+ f"cannot map schema to a Python type yet:\n{json.dumps(schema, indent=2)}"
920
+ )
921
+
922
+ members = schema.get("anyOf") or schema.get("oneOf")
923
+ if members is not None:
924
+ parts = [py_type(member, ctx) for member in members]
925
+ else:
926
+ parts = [_resolve_shape(schema, ctx)]
927
+
928
+ if schema.get("nullable"):
929
+ parts.append("None")
930
+
931
+ return dedupe_union(parts)
932
+
933
+
934
+ def _is_union_component(schema: JSONSchema) -> bool:
935
+ """
936
+ Whether a `$ref` target is a union with no properties of its own.
937
+
938
+ Such a component cannot be a model class: it has no fields, only
939
+ members. It maps to the union of its members, exactly as the same
940
+ `anyOf` written inline would.
941
+ """
942
+ return not schema.get("properties") and bool(
943
+ schema.get("anyOf") or schema.get("oneOf")
944
+ )
945
+
946
+
947
+ def dedupe_union(parts: list[str]) -> str:
948
+ """
949
+ Join union members with `|`, dropping repeats but keeping first-seen
950
+ order -- so `nullable` composed with an already-nullable `anyOf`, or an
951
+ `anyOf` of two schemas that map to the same type, don't double up.
952
+ """
953
+ seen: list[str] = []
954
+ for part in parts:
955
+ if part not in seen:
956
+ seen.append(part)
957
+ return " | ".join(seen)
958
+
959
+
960
+ def _resolve_shape(schema: JSONSchema, ctx: TypeCtx) -> str:
961
+ """
962
+ `py_type` for a schema already known not to be a `$ref`, `anyOf`,
963
+ `oneOf`, `allOf`, `not`, or `nullable` wrapper -- enums, primitives,
964
+ arrays, and objects.
965
+ """
966
+ enum_values = schema.get("enum")
967
+ if enum_values and all(
968
+ value is None or isinstance(value, (str, int, bool)) for value in enum_values
969
+ ):
970
+ values = ", ".join(repr(value) for value in enum_values)
971
+ return f"Literal[{values}]"
972
+
973
+ schema_type = schema.get("type")
974
+ if schema_type == "null":
975
+ return "None"
976
+ if schema_type in _PRIMITIVE_TYPES:
977
+ return _PRIMITIVE_TYPES[schema_type]
978
+ if schema_type == "array":
979
+ return f"list[{py_type(schema.get('items', {}), ctx)}]"
980
+ if schema_type == "object":
981
+ return _resolve_object(schema, ctx)
982
+ if schema_type is None:
983
+ # An untyped node -- `{}`, or `{"nullable": true}` as the
984
+ # `additionalProperties` of a free-form `meta` map -- constrains
985
+ # nothing, so any JSON value satisfies it. `object` says that
986
+ # without reaching for `Any`.
987
+ return "object"
988
+
989
+ raise UnsupportedSchemaError(
990
+ f"cannot map schema to a Python type yet:\n{json.dumps(schema, indent=2)}"
991
+ )
992
+
993
+
994
+ def _resolve_object(schema: JSONSchema, ctx: TypeCtx) -> str:
995
+ """
996
+ An inline `object`: the name the registry minted for its shape if it
997
+ has `properties`, otherwise a `dict[...]` -- see the spec's
998
+ "`additionalProperties`" section.
999
+ """
1000
+ if schema.get("properties"):
1001
+ name = ctx.shapes.name_for(schema)
1002
+ ctx.needed[name] = schema
1003
+ return name
1004
+
1005
+ additional = schema.get("additionalProperties")
1006
+ if isinstance(additional, dict):
1007
+ return f"dict[str, {py_type(additional, ctx)}]"
1008
+ return "dict[str, Any]"
1009
+
1010
+
1011
+ def annotated(py_type: str, *, required: bool) -> str:
1012
+ """
1013
+ `py_type` if the field is required, else unioned with `None`.
1014
+
1015
+ `py_type` may already include `None` (a `nullable` field, or a
1016
+ `format`-of-strings `anyOf` with a `{"type": "null"}` member) -- an
1017
+ optional nullable field must not come out `T | None | None`, so this
1018
+ dedupes the same way `py_type`'s own unions do.
1019
+ """
1020
+ if required:
1021
+ return py_type
1022
+ return dedupe_union([*py_type.split(" | "), "None"])
1023
+
1024
+
1025
+ class ParamSpec(NamedTuple):
1026
+ """
1027
+ One request parameter: what the caller types (`name`) and what goes on
1028
+ the wire (`wire_name`) -- see `arg_name`.
1029
+ """
1030
+
1031
+ name: str
1032
+ wire_name: str
1033
+ location: str
1034
+ required: bool
1035
+ py_type: str
1036
+
1037
+
1038
+ class FieldSpec(NamedTuple):
1039
+ py_type: str
1040
+ required: bool
1041
+ #: The wire name, when it differs from the Python field name -- see
1042
+ #: `safe_field_name`. `None` when the two are the same.
1043
+ alias: str | None = None
1044
+
1045
+
1046
+ def get_field_types(schema: JSONSchema, ctx: TypeCtx) -> dict[str, FieldSpec]:
1047
+ """
1048
+ `{field_name: (python_type, required, alias)}` for one object schema.
1049
+ """
1050
+ required = set(schema.get("required", []))
1051
+ fields: dict[str, FieldSpec] = {}
1052
+ for name, field_schema in schema.get("properties", {}).items():
1053
+ py_name = field_name(name)
1054
+ fields[py_name] = FieldSpec(
1055
+ py_type(field_schema, ctx),
1056
+ name in required,
1057
+ alias=None if py_name == name else name,
1058
+ )
1059
+ return fields
1060
+
1061
+
1062
+ def render_field_lines(field_types: dict[str, FieldSpec]) -> list[str]:
1063
+ if not field_types:
1064
+ return [" pass"]
1065
+ lines = []
1066
+ for name, (py_type, required, alias) in field_types.items():
1067
+ annotation = annotated(py_type, required=required)
1068
+ if alias is None:
1069
+ assignment = "" if required else " = None"
1070
+ else:
1071
+ default = "" if required else "default=None, "
1072
+ assignment = f" = Field({default}alias={alias!r})"
1073
+ lines.append(f" {name}: {annotation}{assignment}")
1074
+ return lines
1075
+
1076
+
1077
+ def render_config_lines(field_types: dict[str, FieldSpec]) -> list[str]:
1078
+ """
1079
+ `populate_by_name` for a class that aliases at least one field, so it
1080
+ can still be built from Python with the field's own name.
1081
+ """
1082
+ if not any(spec.alias for spec in field_types.values()):
1083
+ return []
1084
+ return [" model_config = ConfigDict(populate_by_name=True)", ""]
1085
+
1086
+
1087
+ #
1088
+ # Rendering: plain data models
1089
+ #
1090
+ def render_model(name: str, schema: JSONSchema, ctx: TypeCtx) -> str:
1091
+ """
1092
+ Render one `class {name}(Model): ...`. Any inline object it holds is
1093
+ its own top-level model, referred to by the name the `ShapeRegistry`
1094
+ minted -- see the spec's "Inline objects become top-level models".
1095
+ """
1096
+ field_types = get_field_types(schema, ctx)
1097
+ lines = [f"class {name}(Model):"]
1098
+ lines += render_config_lines(field_types)
1099
+ lines += render_field_lines(field_types)
1100
+ return "\n".join(lines) + "\n"
1101
+
1102
+
1103
+ #
1104
+ # Rendering: typed exceptions
1105
+ #
1106
+ #: Names `CodehoodAPIError` itself defines. A payload field with one of
1107
+ #: these names still lands in `.payload` normally, but gets no top-level
1108
+ #: property -- one would silently shadow the base class's own attribute
1109
+ #: (e.g. a payload's `status` field hiding the HTTP status code), which is
1110
+ #: worse than the minor inconsistency of that one field needing
1111
+ #: `.payload.status` instead of `.status`.
1112
+ _RESERVED_EXCEPTION_ATTRS = {"status", "payload"}
1113
+
1114
+
1115
+ def render_exception(name: str, schema: JSONSchema, ctx: TypeCtx) -> str:
1116
+ field_types = get_field_types(schema, ctx)
1117
+ payload_lines = [
1118
+ f" {line}"
1119
+ for line in render_config_lines(field_types) + render_field_lines(field_types)
1120
+ ]
1121
+ payload_body = "\n".join(payload_lines)
1122
+
1123
+ lines = [
1124
+ f"class {name}(CodehoodAPIError):",
1125
+ " class Payload(Model):",
1126
+ payload_body,
1127
+ "",
1128
+ " payload: Payload",
1129
+ ]
1130
+ properties = [
1131
+ "\n".join(
1132
+ [
1133
+ " @property",
1134
+ f" def {field_name}(self) -> {annotated(py_type, required=required)}:",
1135
+ f" return self.payload.{field_name}",
1136
+ ]
1137
+ )
1138
+ for field_name, (py_type, required, _alias) in field_types.items()
1139
+ if field_name not in _RESERVED_EXCEPTION_ATTRS
1140
+ ]
1141
+ blocks = ["\n".join(lines), *properties]
1142
+ return "\n\n".join(blocks) + "\n"
1143
+
1144
+
1145
+ #
1146
+ # Rendering: one generated function per endpoint
1147
+ #
1148
+ def render_parse(py_type: str, expression: str, model_names: Iterable[str]) -> str:
1149
+ """
1150
+ Source that turns a decoded JSON body into `py_type`.
1151
+
1152
+ A generated model validates itself, but a response is not always one:
1153
+ `list[Course]`, `dict[str, Any]` and `str` are all types
1154
+ `X.model_validate(...)` is simply not defined on -- `list[Course]` is a
1155
+ `types.GenericAlias`, so calling it would raise `AttributeError` on the
1156
+ first request. `TypeAdapter` covers every one of those uniformly.
1157
+ """
1158
+ if py_type in model_names:
1159
+ return f"{py_type}.model_validate({expression})"
1160
+ return f"TypeAdapter({py_type}).validate_python({expression})"
1161
+
1162
+
1163
+ def render_function(
1164
+ operation_id: str,
1165
+ endpoint: Endpoint,
1166
+ ctx: TypeCtx,
1167
+ error_ctx: TypeCtx,
1168
+ ) -> str:
1169
+ """
1170
+ `error_ctx` differs from `ctx` only in where it accumulates schemas:
1171
+ one used as a documented error is rendered as an exception class, not
1172
+ a plain model.
1173
+ """
1174
+ operation = endpoint.operation
1175
+ spec = ctx.spec
1176
+ func_name = snake_case(operation_id)
1177
+
1178
+ params = [
1179
+ ParamSpec(
1180
+ arg_name(parameter.name),
1181
+ parameter.name,
1182
+ parameter.location,
1183
+ parameter.required,
1184
+ py_type(parameter.content_schema, ctx),
1185
+ )
1186
+ for parameter in operation.parameters
1187
+ ]
1188
+
1189
+ body_type = None
1190
+ if operation.request_body is not None:
1191
+ media = operation.request_body.content.get("application/json")
1192
+ if media is not None:
1193
+ body_type = py_type(media.content_schema, ctx)
1194
+
1195
+ success_status = next(
1196
+ (status for status in operation.responses if status.startswith("2")), None
1197
+ )
1198
+ if success_status is None:
1199
+ raise UnsupportedSchemaError(f"{operation_id!r} has no documented 2xx response")
1200
+ success_media = operation.responses[success_status].content.get("application/json")
1201
+ success_type = (
1202
+ py_type(success_media.content_schema, ctx) if success_media else "None"
1203
+ )
1204
+
1205
+ error_types: dict[str, str] = {
1206
+ status: py_type(media.content_schema, error_ctx)
1207
+ for status, response in operation.responses.items()
1208
+ if not status.startswith("2")
1209
+ for media in [response.content.get("application/json")]
1210
+ if media is not None
1211
+ }
1212
+ for status, error_type in error_types.items():
1213
+ if error_type not in error_ctx.needed:
1214
+ raise UnsupportedSchemaError(
1215
+ f"{operation_id!r}'s {status} response is {error_type}, which "
1216
+ "has no exception class to carry it -- a documented error "
1217
+ "must be an object schema"
1218
+ )
1219
+
1220
+ signature_parts = [
1221
+ f"{param.name}: {annotated(param.py_type, required=param.required)}"
1222
+ + ("" if param.required else " = None")
1223
+ for param in params
1224
+ ]
1225
+ if body_type is not None:
1226
+ signature_parts.append(f"body: {body_type}")
1227
+ signature_parts.append("client: httpx.Client | None = None")
1228
+
1229
+ path_params = [param for param in params if param.location == "path"]
1230
+ query_params = [param for param in params if param.location == "query"]
1231
+ header_params = [param for param in params if param.location == "header"]
1232
+
1233
+ path_expr = repr(endpoint.path)
1234
+ if path_params:
1235
+ # The placeholder in the path is the server's name for the
1236
+ # parameter, not the argument's.
1237
+ substitutions = ", ".join(
1238
+ f"{param.wire_name}={param.name}" for param in path_params
1239
+ )
1240
+ path_expr = f"{endpoint.path!r}.format({substitutions})"
1241
+
1242
+ call_kwargs = []
1243
+ if query_params:
1244
+ pairs = ", ".join(
1245
+ f"{param.wire_name!r}: {param.name}" for param in query_params
1246
+ )
1247
+ # `query_params` drops the ones the caller left unset; `httpx`
1248
+ # would otherwise send them as `?name=`, which is not the same
1249
+ # thing as not sending them.
1250
+ call_kwargs.append(f"params=query_params({{{pairs}}})")
1251
+ if body_type is not None:
1252
+ call_kwargs.append('json=body.model_dump(mode="json", by_alias=True)')
1253
+ headers = []
1254
+ if spec.requires_auth(operation):
1255
+ headers.append("auth_headers(client)")
1256
+ if header_params:
1257
+ pairs = ", ".join(
1258
+ f"{param.wire_name!r}: {param.name}" for param in header_params
1259
+ )
1260
+ # Same as a query parameter: an unset header is not sent at all.
1261
+ headers.append(f"header_params({{{pairs}}})")
1262
+ if len(headers) == 1:
1263
+ call_kwargs.append(f"headers={headers[0]}")
1264
+ elif headers:
1265
+ call_kwargs.append(f"headers={{{', '.join(f'**{h}' for h in headers)}}}")
1266
+ call_args = path_expr + ("" if not call_kwargs else ", " + ", ".join(call_kwargs))
1267
+
1268
+ lines = [f"def {func_name}(*, {', '.join(signature_parts)}) -> {success_type}:"]
1269
+ doc = operation.summary or operation.description
1270
+ if doc:
1271
+ lines += [' """', f" {doc}", ' """']
1272
+ lines.append(" client = client if client is not None else get_client()")
1273
+ lines.append(f" response = client.{endpoint.method.lower()}({call_args})")
1274
+
1275
+ for status, exception_name in error_types.items():
1276
+ lines.append(f" if response.status_code == {status}:")
1277
+ lines.append(
1278
+ f" raise {exception_name}"
1279
+ f"(response.status_code, {exception_name}.Payload.model_validate(response.json()))"
1280
+ )
1281
+
1282
+ lines.append(f" if response.status_code == {success_status}:")
1283
+ lines.append(
1284
+ " return None"
1285
+ if success_type == "None"
1286
+ else " return "
1287
+ + render_parse(success_type, "response.json()", ctx.needed)
1288
+ )
1289
+ lines.append(" response.raise_for_status()")
1290
+ lines.append(" raise CodehoodAPIError(response.status_code, Model())")
1291
+
1292
+ return "\n".join(lines) + "\n"
1293
+
1294
+
1295
+ def format_source(source: str) -> str:
1296
+ """
1297
+ Format generated source with `ruff format`, using the project's settings.
1298
+
1299
+ The committed `generated.py` is ruff-formatted, so regeneration output
1300
+ must go through here to be committable as is.
1301
+
1302
+ @throws RuntimeError: `ruff` is not on the `PATH` or fails.
1303
+ """
1304
+ ruff = shutil.which("ruff")
1305
+ if ruff is None:
1306
+ raise RuntimeError("`ruff` is required to format the generated client")
1307
+ result = subprocess.run(
1308
+ [ruff, "format", "--stdin-filename", "generated.py", "-"],
1309
+ input=source,
1310
+ capture_output=True,
1311
+ text=True,
1312
+ cwd=Path(__file__).parent,
1313
+ )
1314
+ if result.returncode != 0:
1315
+ raise RuntimeError(f"ruff format failed: {result.stderr.strip()}")
1316
+ return result.stdout
1317
+
1318
+
1319
+ #
1320
+ # CLI
1321
+ #
1322
+ def main() -> None:
1323
+ """
1324
+ Entry point for `python -m codehood.api.generate`.
1325
+ """
1326
+ app = typer.Typer(
1327
+ name="api-codegen",
1328
+ help="Generate API client code from OpenAPI spec.",
1329
+ )
1330
+
1331
+ @app.command()
1332
+ def codegen(
1333
+ path: Annotated[
1334
+ str | None,
1335
+ typer.Argument(
1336
+ help="Path to OpenAPI spec file or URL to a Codehood server."
1337
+ ),
1338
+ ] = None,
1339
+ output: Annotated[
1340
+ Path | None,
1341
+ typer.Argument(help="Path to write the generated module to."),
1342
+ ] = None,
1343
+ ) -> None:
1344
+ """
1345
+ Generate `api/generated.py` from an OpenAPI spec.
1346
+ """
1347
+ if path is None:
1348
+ path = (
1349
+ "openapi.json"
1350
+ if Path("openapi.json").exists()
1351
+ else "http://localhost:4321/openapi.json"
1352
+ )
1353
+
1354
+ if path.startswith("http://") or path.startswith("https://"):
1355
+ response = httpx.get(path)
1356
+ response.raise_for_status()
1357
+ spec = response.json()
1358
+ else:
1359
+ spec = json.loads(Path(path).read_text(encoding="utf-8"))
1360
+
1361
+ output = output or Path(__file__).parent / "generated.py"
1362
+ source = format_source(Generator(spec).generate())
1363
+ output.write_text(source, encoding="utf-8")
1364
+ typer.echo(f"wrote {output}")
1365
+
1366
+ app()
1367
+
1368
+
1369
+ if __name__ == "__main__":
1370
+ main()