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
codehood/functional.py ADDED
@@ -0,0 +1,40 @@
1
+ from collections.abc import Callable
2
+ from functools import wraps
3
+ from typing import Any, Literal, Protocol, cast, overload
4
+
5
+
6
+ class _Fn[Fst, **P, R](Protocol):
7
+ def __call__(self, x: Fst, /, *args: P.args, **kwds: P.kwargs) -> R: ...
8
+
9
+
10
+ class Curried[Fst, **P, R](Protocol):
11
+ @overload
12
+ def __call__(self, arg: Fst, /, *args: P.args, **kwargs: P.kwargs) -> R: ...
13
+
14
+ @overload
15
+ def __call__(self, /, *args: P.args, **kwargs: P.kwargs) -> Callable[P, R]: ...
16
+
17
+ def __call__(self, /, *args: Any, **kwargs: Any) -> Any: ...
18
+
19
+
20
+ def curry[T, **P, R](
21
+ arity: Literal[1] = 1,
22
+ /,
23
+ ) -> Callable[[_Fn[T, P, R]], Curried[T, P, R]]:
24
+ """
25
+ Curry calling the first argument.
26
+ """
27
+
28
+ if arity != 1:
29
+ raise ValueError("only arity 1 is supported for now.")
30
+
31
+ def decorator(fn: _Fn[T, P, R]) -> Curried[T, P, R]:
32
+ @wraps(fn)
33
+ def wrapped(first: T, /, *args: P.args, **kwargs: P.kwargs):
34
+ if args == (...,):
35
+ return lambda *args, **kw: fn(first, *args, **{**kw, **kwargs})
36
+ return fn(first, *args, **kwargs)
37
+
38
+ return cast("Curried", wrapped)
39
+
40
+ return decorator
codehood/globs.py ADDED
@@ -0,0 +1,71 @@
1
+ """
2
+ Gitignore-like path patterns, as used by `[push] exclude` in `codehood.toml`.
3
+
4
+ Patterns are relative to the repository root, with `/` as the separator:
5
+
6
+ - `*` matches any run of characters inside one path segment, `?` one character.
7
+ - `**` as a whole segment matches any number of directories.
8
+ - A pattern that matches a directory also matches everything under it.
9
+ - A leading or trailing `/` is ignored. There is no negation (`!`).
10
+ - A backslash escapes the next character, so `\\*` is a literal `*`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from collections.abc import Sequence
17
+
18
+ __all__ = ["is_excluded", "pattern_error"]
19
+
20
+
21
+ def is_excluded(path: str, patterns: Sequence[str]) -> bool:
22
+ """
23
+ Tell whether any pattern matches a root-relative, `/`-separated path.
24
+
25
+ @example
26
+ >>> is_excluded("questions/wip/a.mdq", ["questions/wip"])
27
+ True
28
+ """
29
+ return any(_compile(pattern).match(path) for pattern in patterns)
30
+
31
+
32
+ def pattern_error(pattern: str) -> str | None:
33
+ """
34
+ Why a pattern is not acceptable, or `None` when it is.
35
+ """
36
+ body = pattern.strip().strip("/")
37
+ if not body:
38
+ return "pattern is empty"
39
+ if body.startswith("!"):
40
+ return "negated patterns (`!`) are not supported"
41
+ if ".." in body.split("/"):
42
+ return "pattern must stay inside the repository (no `..`)"
43
+ return None
44
+
45
+
46
+ #
47
+ # Utilities
48
+ #
49
+ def _compile(pattern: str) -> re.Pattern[str]:
50
+ segments = pattern.strip().strip("/").split("/")
51
+ regex = ""
52
+ for index, segment in enumerate(segments):
53
+ last = index == len(segments) - 1
54
+ if segment == "**":
55
+ regex += ".+" if last else "(?:[^/]+/)*"
56
+ else:
57
+ regex += _segment_regex(segment) + ("" if last else "/")
58
+ return re.compile(f"{regex}(?:/.*)?$")
59
+
60
+
61
+ def _segment_regex(segment: str) -> str:
62
+ parts = {"*": "[^/]*", "?": "[^/]"}
63
+ regex = ""
64
+ chars = iter(segment)
65
+ for char in chars:
66
+ if char == "\\":
67
+ char = next(chars, "\\")
68
+ regex += re.escape(char)
69
+ else:
70
+ regex += parts.get(char) or re.escape(char)
71
+ return regex
codehood/grades.py ADDED
@@ -0,0 +1,74 @@
1
+ """
2
+ What a course's `grades.py` works with.
3
+
4
+ `codehood push` calls the `grade` function of that file once per enrolled
5
+ student, with a `Student`, and pushes what it returns as grade columns. See
6
+ `dev/specs/to-review/push-grades.md`.
7
+
8
+ ```python
9
+ from codehood.grades import Student
10
+
11
+ def grade(student: Student) -> dict[str, float | str | None]:
12
+ midterm = student.exams["midterm"].score or 0.0
13
+ return {"total": 0.6 * midterm + 0.4 * (student.scores["project"] or 0.0)}
14
+ ```
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Callable, Mapping
20
+ from dataclasses import dataclass, field
21
+ from typing import Literal
22
+
23
+ __all__ = [
24
+ "ExamResult",
25
+ "ExamState",
26
+ "GradeFunction",
27
+ "GradeValue",
28
+ "Student",
29
+ ]
30
+
31
+ #: Why an exam has a score or lacks one: every answer graded, answers still
32
+ #: waiting for a grade, an attempt still open, an exam the student missed,
33
+ #: or an exam with no attempt that has not closed yet.
34
+ type ExamState = Literal["graded", "pending", "in_progress", "missed", "not_held"]
35
+
36
+ #: What one cell of a grade column holds. `None` is no value at all.
37
+ type GradeValue = float | str | None
38
+
39
+ #: The signature of `grades.py`'s `grade`: a student's value for each column
40
+ #: the function computes, keyed by column slug.
41
+ type GradeFunction = Callable[["Student"], Mapping[str, GradeValue]]
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class ExamResult:
46
+ """
47
+ One student's result at one exam.
48
+
49
+ `score` is a percentage from -100 to 100, the scale of the Grades tab,
50
+ and is a number only when `state` is `graded`.
51
+ """
52
+
53
+ score: float | None
54
+ state: ExamState
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class Student:
59
+ """
60
+ One enrolled student, with everything `grade` may compute from.
61
+
62
+ `exams` has one result per exam of the server's Grades tab, by slug, and
63
+ `scores` one entry per score column of `grades.csv`, `None` where the
64
+ student has no row or the cell is empty.
65
+ """
66
+
67
+ username: str
68
+ name: str
69
+ email: str
70
+ school_id: str | None
71
+ github: str | None
72
+ status: Literal["active", "dropped"]
73
+ exams: Mapping[str, ExamResult] = field(default_factory=dict)
74
+ scores: Mapping[str, GradeValue] = field(default_factory=dict)
codehood/hypothesis.py ADDED
@@ -0,0 +1,274 @@
1
+ """
2
+ Hypothesis strategies that generate documents conforming to an OpenAPI schema.
3
+
4
+ `tests/test_api_generate.py` proves the generator emits runnable code against
5
+ a handful of hand-written fixtures. It cannot prove the generated models
6
+ accept every document the server can actually send, since every fixture is
7
+ one a human invented. These strategies read the server's own OpenAPI
8
+ document and draw JSON that the document says is valid, so a property test
9
+ can check the invariant directly: anything the spec permits, the generated
10
+ model must accept.
11
+
12
+ Only the JSON Schema subset that appears in the server's document is
13
+ supported -- see `dev/specs/to-review/api-hypothesis-strategies.md` for the
14
+ survey. A keyword outside that subset (`allOf`, `not`, ...) raises
15
+ `UnsupportedSchemaError` rather than silently generating something the spec
16
+ doesn't actually permit.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Mapping
22
+ from datetime import UTC
23
+ from typing import Any
24
+
25
+ from hypothesis import strategies as st
26
+
27
+ from .api.generate import UnsupportedSchemaError
28
+ from .api.openapi import JSONSchema, OpenAPISpec, load_openapi
29
+
30
+ type JSON = dict[str, Any] | list[Any] | str | int | float | bool | None
31
+
32
+ __all__ = [
33
+ "JSON",
34
+ "json_schema_documents",
35
+ "openapi_endpoint_documents",
36
+ "openapi_response_documents",
37
+ ]
38
+
39
+
40
+ def json_schema_documents(
41
+ schema: JSONSchema, spec: OpenAPISpec | None = None
42
+ ) -> st.SearchStrategy[JSON]:
43
+ """
44
+ Build a strategy that draws JSON documents conforming to `schema`.
45
+
46
+ Args:
47
+ schema: A JSON Schema node (OpenAPI's dialect: `nullable: true`
48
+ rather than a `null` member of `type`).
49
+ spec: The document `schema` came from, needed only to resolve a
50
+ `$ref`. Pass `None` when `schema` is known not to contain one.
51
+
52
+ Returns:
53
+ A strategy drawing values that conform to `schema`.
54
+
55
+ Raises:
56
+ ValueError: `schema` contains a `$ref` but `spec` is `None`.
57
+ UnsupportedSchemaError: `schema` uses a JSON Schema feature outside
58
+ the surveyed subset (`allOf`, `not`, list-valued `type`,
59
+ ...).
60
+ """
61
+ if "$ref" in schema:
62
+ if spec is None:
63
+ raise ValueError(
64
+ f"schema contains $ref {schema['$ref']!r} but no spec was given "
65
+ "to resolve it against"
66
+ )
67
+ _name, resolved = spec.resolve(schema)
68
+ return json_schema_documents(resolved, spec)
69
+
70
+ if "allOf" in schema or "not" in schema or isinstance(schema.get("type"), list):
71
+ raise UnsupportedSchemaError(
72
+ f"cannot build a strategy for this schema yet:\n{schema!r}"
73
+ )
74
+
75
+ enum_values = schema.get("enum")
76
+ if enum_values is not None:
77
+ strategy = st.sampled_from(enum_values)
78
+ elif members := (schema.get("anyOf") or schema.get("oneOf")):
79
+ # `oneOf` draws the same way as `anyOf`: every union in this
80
+ # document is discriminated by a single-valued `type` enum, so a
81
+ # document valid against one member is valid against exactly one.
82
+ strategy = st.one_of(
83
+ *(json_schema_documents(member, spec) for member in members)
84
+ )
85
+ else:
86
+ strategy = _leaf_strategy(schema, spec)
87
+
88
+ if schema.get("nullable"):
89
+ strategy = st.none() | strategy
90
+ return strategy
91
+
92
+
93
+ def openapi_endpoint_documents(
94
+ endpoint: str, openapi_spec: OpenAPISpec | Mapping[str, Any]
95
+ ) -> st.SearchStrategy[JSON]:
96
+ """
97
+ Build a strategy for the JSON request body of one operation.
98
+
99
+ Args:
100
+ endpoint: The operation's `operationId`, the same key `ENDPOINTS`
101
+ and `codehood api` use.
102
+ openapi_spec: The document the operation is defined in, either
103
+ already parsed or as a raw dict (which goes through
104
+ `load_openapi`).
105
+
106
+ Returns:
107
+ A strategy drawing request bodies the operation's spec permits.
108
+
109
+ Raises:
110
+ KeyError: `endpoint` is not an operation in `openapi_spec`.
111
+ ValueError: the operation has no `requestBody`.
112
+ """
113
+ spec = _as_spec(openapi_spec)
114
+ operation = spec.operations()[endpoint].operation
115
+ if operation.request_body is None:
116
+ raise ValueError(f"{endpoint!r} has no requestBody to generate documents for")
117
+ media = operation.request_body.content.get("application/json")
118
+ if media is None:
119
+ raise ValueError(f"{endpoint!r} has no application/json requestBody")
120
+ return json_schema_documents(media.content_schema, spec)
121
+
122
+
123
+ def openapi_response_documents(
124
+ endpoint: str, openapi_spec: OpenAPISpec | Mapping[str, Any], status: int = 200
125
+ ) -> st.SearchStrategy[JSON]:
126
+ """
127
+ Build a strategy for one operation's JSON response body.
128
+
129
+ Args:
130
+ endpoint: The operation's `operationId`.
131
+ openapi_spec: The document the operation is defined in, either
132
+ already parsed or as a raw dict.
133
+ status: The HTTP status whose response to generate documents for.
134
+
135
+ Returns:
136
+ A strategy drawing response bodies the operation's spec permits.
137
+
138
+ Raises:
139
+ KeyError: `endpoint` is not an operation, or has no response
140
+ documented for `status`.
141
+ ValueError: the response has no `application/json` content.
142
+ """
143
+ spec = _as_spec(openapi_spec)
144
+ operation = spec.operations()[endpoint].operation
145
+ response = operation.responses[str(status)]
146
+ media = response.content.get("application/json")
147
+ if media is None:
148
+ raise ValueError(
149
+ f"{endpoint!r}'s {status} response has no application/json content"
150
+ )
151
+ return json_schema_documents(media.content_schema, spec)
152
+
153
+
154
+ #
155
+ # INTERNAL
156
+ #
157
+ def _as_spec(openapi_spec: OpenAPISpec | Mapping[str, Any]) -> OpenAPISpec:
158
+ """
159
+ Accept either a parsed `OpenAPISpec` or the raw dict it comes from.
160
+ """
161
+ if isinstance(openapi_spec, OpenAPISpec):
162
+ return openapi_spec
163
+ return load_openapi(dict(openapi_spec))
164
+
165
+
166
+ def _leaf_strategy(
167
+ schema: JSONSchema, spec: OpenAPISpec | None
168
+ ) -> st.SearchStrategy[JSON]:
169
+ """
170
+ A strategy for a schema known not to be a `$ref`, `enum`, `anyOf`, or
171
+ `oneOf` wrapper -- dispatches on `type`, and free-form values when there is
172
+ none.
173
+ """
174
+ schema_type = schema.get("type")
175
+ if schema_type == "string":
176
+ return _string_strategy(schema)
177
+ if schema_type == "integer":
178
+ return _integer_strategy(schema)
179
+ if schema_type == "number":
180
+ return _number_strategy(schema)
181
+ if schema_type == "boolean":
182
+ return st.booleans()
183
+ if schema_type == "array":
184
+ items = schema.get("items", {})
185
+ return st.lists(json_schema_documents(items, spec), max_size=3)
186
+ if schema_type == "object":
187
+ return _object_strategy(schema, spec)
188
+
189
+ # No `type` and none of the keywords handled above: a free-form leaf,
190
+ # the only shape this document uses for "anything goes".
191
+ return st.none() | st.booleans() | st.integers() | st.text()
192
+
193
+
194
+ def _string_strategy(schema: JSONSchema) -> st.SearchStrategy[str]:
195
+ """
196
+ `pattern` wins over `format`, since a pattern pins the exact shape a
197
+ `format` would otherwise only approximate (see `login`'s username
198
+ branch).
199
+ """
200
+ pattern = schema.get("pattern")
201
+ if pattern is not None:
202
+ # `from_regex` is overloaded on `str` versus `bytes`, and a schema's
203
+ # values are untyped, so the `str` overload has to be picked here.
204
+ return st.from_regex(str(pattern), fullmatch=True)
205
+
206
+ string_format = schema.get("format")
207
+ if string_format == "date-time":
208
+ return st.datetimes(timezones=st.just(UTC)).map(lambda value: value.isoformat())
209
+ if string_format == "email":
210
+ return st.emails()
211
+ if string_format == "binary":
212
+ # The server types `Buffer` as a plain string and the generated
213
+ # model is `str`; a real byte stream is not what round-trips here.
214
+ return _bounded_text(schema)
215
+
216
+ return _bounded_text(schema)
217
+
218
+
219
+ def _bounded_text(schema: JSONSchema) -> st.SearchStrategy[str]:
220
+ return st.text(
221
+ min_size=schema.get("minLength", 0),
222
+ max_size=schema.get("maxLength"),
223
+ )
224
+
225
+
226
+ def _integer_strategy(schema: JSONSchema) -> st.SearchStrategy[int]:
227
+ minimum = schema.get("minimum")
228
+ maximum = schema.get("maximum")
229
+ # OAS 3.0 spells `exclusiveMinimum`/`exclusiveMaximum` as booleans
230
+ # modifying `minimum`/`maximum`, not as standalone bounds.
231
+ if schema.get("exclusiveMinimum") and minimum is not None:
232
+ minimum += 1
233
+ if schema.get("exclusiveMaximum") and maximum is not None:
234
+ maximum -= 1
235
+ return st.integers(min_value=minimum, max_value=maximum)
236
+
237
+
238
+ def _number_strategy(schema: JSONSchema) -> st.SearchStrategy[float]:
239
+ minimum = schema.get("minimum")
240
+ maximum = schema.get("maximum")
241
+ exclude_min = bool(schema.get("exclusiveMinimum")) and minimum is not None
242
+ exclude_max = bool(schema.get("exclusiveMaximum")) and maximum is not None
243
+ return st.floats(
244
+ min_value=minimum,
245
+ max_value=maximum,
246
+ exclude_min=exclude_min,
247
+ exclude_max=exclude_max,
248
+ allow_nan=False,
249
+ allow_infinity=False,
250
+ )
251
+
252
+
253
+ def _object_strategy(
254
+ schema: JSONSchema, spec: OpenAPISpec | None
255
+ ) -> st.SearchStrategy[dict[str, JSON]]:
256
+ """
257
+ Every `required` property always present, every optional property
258
+ present or absent -- never an extra key, `additionalProperties: false`
259
+ or not, since this strategy models valid requests and an unknown key is
260
+ a server-side rejection, not a document the spec permits.
261
+ """
262
+ properties = schema.get("properties", {})
263
+ required = set(schema.get("required", []))
264
+
265
+ fields: dict[str, st.SearchStrategy[JSON]] = {}
266
+ optional: dict[str, st.SearchStrategy[JSON]] = {}
267
+ for name, property_schema in properties.items():
268
+ strategy = json_schema_documents(property_schema, spec)
269
+ if name in required:
270
+ fields[name] = strategy
271
+ else:
272
+ optional[name] = strategy
273
+
274
+ return st.fixed_dictionaries(fields, optional=optional)
File without changes
@@ -0,0 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ from pydantic import BaseModel, ConfigDict
4
+
5
+ __all__ = [
6
+ "Model",
7
+ ]
8
+
9
+
10
+ class Model(BaseModel):
11
+ """
12
+ Base model for all models in the project.
13
+ """
14
+
15
+ model_config = ConfigDict(from_attributes=True)
@@ -0,0 +1,187 @@
1
+ """
2
+ Pydantic models for `codehood.toml`, the course repository's identity file.
3
+
4
+ The file holds a course's identity (`discipline`, `instructor`, `edition`),
5
+ the server it syncs with, and the grade columns it pushes. It never holds a
6
+ secret -- see `dev/specs/to-do/init.md`, "`codehood.toml` is committed and
7
+ holds no secret", for why.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import tomllib
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import Literal, Self
16
+
17
+ from pydantic import ConfigDict, Field, field_validator, model_validator
18
+
19
+ from ..globs import pattern_error
20
+ from .base import Model
21
+ from .validators import (
22
+ DisciplineSlug,
23
+ EditionSlug,
24
+ GradeColumnSlug,
25
+ InstructorUsername,
26
+ ServerUrl,
27
+ )
28
+
29
+ __all__ = [
30
+ "CourseIdentity",
31
+ "CourseKey",
32
+ "GradeColumnConfig",
33
+ "GradesConfig",
34
+ "PushConfig",
35
+ "RepoConfig",
36
+ "ServerConfig",
37
+ ]
38
+
39
+
40
+ class CourseIdentity(Model):
41
+ """
42
+ The `[course]` table: the three values that name a course,
43
+ `(discipline, instructor, edition)`, and an optional description.
44
+ """
45
+
46
+ discipline: DisciplineSlug
47
+ instructor: InstructorUsername
48
+ edition: EditionSlug
49
+ #: Replaces the README's first paragraph as the course description.
50
+ description: str | None = None
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class CourseKey:
55
+ """
56
+ The natural key of a course, and the one place that knows how the server
57
+ addresses it: `/<discipline>/<instructor>_<edition>`.
58
+ """
59
+
60
+ discipline: str
61
+ instructor: str
62
+ edition: str
63
+
64
+ @property
65
+ def slug(self) -> str:
66
+ """
67
+ The course's address within its discipline.
68
+ """
69
+ return f"{self.instructor}_{self.edition}"
70
+
71
+ def url(self, kind: str | None = None, slug: str | None = None) -> str:
72
+ """
73
+ The server path of the course, of a `kind` collection under it
74
+ (`resources`, `repositories`) or of one entry of it.
75
+
76
+ Example:
77
+ >>> CourseKey("cs101", "ada", "2026-1").url("resources", "notes")
78
+ '/cs101/ada_2026-1/resources/notes'
79
+ """
80
+ base = f"/{self.discipline}/{self.slug}"
81
+ if kind is None:
82
+ return base
83
+ return f"{base}/{kind}" if slug is None else f"{base}/{kind}/{slug}"
84
+
85
+
86
+ class ServerConfig(Model):
87
+ """
88
+ The server a course repository syncs with.
89
+ """
90
+
91
+ url: ServerUrl
92
+
93
+
94
+ class GradeColumnConfig(Model):
95
+ """
96
+ One `[[grades.column]]` table: a grade column the course pushes.
97
+ """
98
+
99
+ slug: GradeColumnSlug
100
+ #: Defaults to the slug.
101
+ title: str = Field(default="", max_length=80)
102
+ kind: Literal["number", "label"] = "number"
103
+
104
+ @model_validator(mode="after")
105
+ def title_defaults_to_slug(self) -> Self:
106
+ self.title = self.title.strip() or self.slug
107
+ return self
108
+
109
+
110
+ class GradesConfig(Model):
111
+ """
112
+ The `[grades]` table: the course's grade columns, in table order.
113
+ """
114
+
115
+ column: list[GradeColumnConfig] = Field(default_factory=list)
116
+
117
+ @model_validator(mode="after")
118
+ def slugs_are_unique(self) -> Self:
119
+ seen: set[str] = set()
120
+ for column in self.column:
121
+ if column.slug in seen:
122
+ raise ValueError(f"grade column {column.slug!r} is declared twice")
123
+ seen.add(column.slug)
124
+ return self
125
+
126
+
127
+ class PushConfig(Model):
128
+ """
129
+ The `[push]` table: what `codehood push` leaves out.
130
+ """
131
+
132
+ model_config = ConfigDict(extra="forbid")
133
+
134
+ #: Gitignore-like patterns, relative to the repository root. See
135
+ #: `codehood.globs`.
136
+ exclude: list[str] = Field(default_factory=list)
137
+
138
+ @field_validator("exclude")
139
+ @classmethod
140
+ def patterns_are_valid(cls, patterns: list[str]) -> list[str]:
141
+ for pattern in patterns:
142
+ if (error := pattern_error(pattern)) is not None:
143
+ raise ValueError(f"{pattern!r}: {error}")
144
+ return patterns
145
+
146
+
147
+ class RepoConfig(Model):
148
+ """
149
+ The full contents of `codehood.toml`: course identity, server, the
150
+ grade columns the course pushes and what it leaves out of a push.
151
+ """
152
+
153
+ course: CourseIdentity
154
+ server: ServerConfig
155
+ grades: GradesConfig = Field(default_factory=GradesConfig)
156
+ push: PushConfig = Field(default_factory=PushConfig)
157
+
158
+ @property
159
+ def key(self) -> CourseKey:
160
+ """
161
+ The course's natural key.
162
+ """
163
+ return CourseKey(
164
+ self.course.discipline, self.course.instructor, self.course.edition
165
+ )
166
+
167
+ @classmethod
168
+ def open(cls, path: Path | None = None) -> RepoConfig:
169
+ """
170
+ Open the codehood.toml file and return the corresponding config.
171
+
172
+ Path can be the path to the config file or the base directory where it
173
+ is located. Defaults to CWD.
174
+ """
175
+ if path is None:
176
+ path = Path.cwd()
177
+ if path.is_dir():
178
+ path = path / "codehood.toml"
179
+
180
+ if not path.exists():
181
+ raise FileNotFoundError(f"could not find Codehood config at {path}")
182
+
183
+ # `tomllib`, not `tomlkit`: pydantic reads only the first table out of
184
+ # a `tomlkit` array of tables, which would drop every grade column
185
+ # but one.
186
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
187
+ return RepoConfig.model_validate(data)