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,455 @@
1
+ """
2
+ The pure core of pushing grade columns: `grades.csv`, the students the
3
+ function is called with, and the columns that come out.
4
+
5
+ Nothing here reads a file, imports the instructor's script or touches HTTP.
6
+ `cli/grades.py` gathers the inputs and `run.py` sends the result. See
7
+ `dev/specs/to-review/push-grades.md`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import csv
13
+ import hashlib
14
+ import io
15
+ import json
16
+ import math
17
+ import re
18
+ import traceback
19
+ from collections.abc import Mapping, Sequence
20
+ from dataclasses import dataclass, field
21
+ from typing import Literal
22
+
23
+ from ..grades import ExamResult, GradeFunction, GradeValue, Student
24
+
25
+ __all__ = [
26
+ "ColumnSpec",
27
+ "GradeColumn",
28
+ "GradesCsv",
29
+ "GradesError",
30
+ "Roster",
31
+ "ServerStudent",
32
+ "build_roster",
33
+ "compute_columns",
34
+ "parse_grades_csv",
35
+ ]
36
+
37
+ type GradeKind = Literal["number", "label"]
38
+ type IdField = Literal["school_id", "username", "github", "email"]
39
+
40
+ ID_FIELDS: tuple[IdField, ...] = ("school_id", "username", "github", "email")
41
+
42
+ #: The longest label the server stores.
43
+ MAX_LABEL = 32
44
+
45
+ NUMBER_RE = re.compile(r"^[+-]?\d+([.,]\d+)?$")
46
+
47
+
48
+ class GradesError(Exception):
49
+ """
50
+ The grade columns cannot be computed: `grades.csv`, `grades.py` or the
51
+ declared columns disagree.
52
+
53
+ Refuses the grades part of a push and nothing else. `problems` lists
54
+ every cause found, one line each.
55
+ """
56
+
57
+ def __init__(self, problems: Sequence[str]) -> None:
58
+ self.problems = tuple(problems)
59
+ super().__init__("; ".join(self.problems))
60
+
61
+
62
+ #
63
+ # Inputs
64
+ #
65
+ @dataclass(frozen=True)
66
+ class ColumnSpec:
67
+ """
68
+ One grade column as `codehood.toml` declares it.
69
+ """
70
+
71
+ slug: str
72
+ title: str
73
+ kind: GradeKind
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class GradesCsv:
78
+ """
79
+ `grades.csv`, parsed but not yet matched to students.
80
+
81
+ `rows` maps a student's id, as written in the file, to the raw cell of
82
+ each score column. Cells stay text here: whether `7.5` is a number or a
83
+ label depends on who reads it.
84
+ """
85
+
86
+ id_field: IdField
87
+ headers: tuple[str, ...]
88
+ rows: Mapping[str, Mapping[str, str]]
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class ServerStudent:
93
+ """
94
+ One enrolled student as the server reports them, before `grades.csv`
95
+ is matched in.
96
+ """
97
+
98
+ username: str
99
+ name: str
100
+ email: str
101
+ school_id: str | None
102
+ github: str | None
103
+ status: Literal["active", "dropped"]
104
+ exams: Mapping[str, ExamResult] = field(default_factory=dict)
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class Roster:
109
+ """
110
+ The students `grade` is called with, and what `grades.csv` held for
111
+ each.
112
+
113
+ `cells` maps a username to the raw cells of that student's row.
114
+ `unmatched` lists the ids of the file that belong to no enrolled
115
+ student, which are reported and skipped.
116
+ """
117
+
118
+ students: tuple[Student, ...] = ()
119
+ headers: tuple[str, ...] = ()
120
+ cells: Mapping[str, Mapping[str, str]] = field(default_factory=dict)
121
+ id_field: IdField = "school_id"
122
+ unmatched: tuple[str, ...] = ()
123
+
124
+
125
+ #
126
+ # Output
127
+ #
128
+ @dataclass(frozen=True)
129
+ class GradeColumn:
130
+ """
131
+ One grade column ready to push, whole.
132
+
133
+ `values` holds one `(username, value)` pair per student with a value,
134
+ ordered by username.
135
+ """
136
+
137
+ slug: str
138
+ title: str
139
+ kind: GradeKind
140
+ position: int
141
+ values: tuple[tuple[str, float | str], ...]
142
+
143
+ @property
144
+ def rev(self) -> str:
145
+ """
146
+ The digest the server hands back on the next read, which is what
147
+ makes a second push of an unchanged column a no-op.
148
+ """
149
+ payload = {
150
+ "title": self.title,
151
+ "kind": self.kind.upper(),
152
+ "position": self.position,
153
+ "values": [[username, value] for username, value in self.values],
154
+ }
155
+ serialized = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
156
+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
157
+
158
+
159
+ #
160
+ # grades.csv
161
+ #
162
+ def parse_grades_csv(text: str) -> GradesCsv:
163
+ """
164
+ Parse `grades.csv`: one row per student, the first column their id.
165
+
166
+ The header of the first column says which id it is. The delimiter is
167
+ `;` when the header line has one, `,` otherwise.
168
+
169
+ Raises:
170
+ GradesError: The file is empty, the id header is not one of
171
+ `school_id`, `username`, `github`, `email`, a header repeats, a
172
+ row has no id, or an id appears twice.
173
+ """
174
+ lines = text.removeprefix("").splitlines()
175
+ if not lines or not lines[0].strip():
176
+ raise GradesError(["grades.csv is empty"])
177
+
178
+ delimiter = ";" if ";" in lines[0] else ","
179
+ reader = csv.reader(io.StringIO("\n".join(lines)), delimiter=delimiter)
180
+ header = [cell.strip() for cell in next(reader)]
181
+ id_header, score_headers = header[0], tuple(header[1:])
182
+
183
+ problems: list[str] = []
184
+ if id_header not in ID_FIELDS:
185
+ problems.append(
186
+ f"grades.csv: the first column is {id_header!r}, "
187
+ f"expected one of {', '.join(ID_FIELDS)}"
188
+ )
189
+ repeated = sorted({name for name in score_headers if header.count(name) > 1})
190
+ if repeated:
191
+ problems.append(f"grades.csv: repeated column(s) {', '.join(repeated)}")
192
+ if problems:
193
+ raise GradesError(problems)
194
+
195
+ rows: dict[str, dict[str, str]] = {}
196
+ for number, row in enumerate(reader, start=2):
197
+ if not any(cell.strip() for cell in row):
198
+ continue
199
+ student_id = row[0].strip()
200
+ if not student_id:
201
+ problems.append(f"grades.csv: row {number} has no {id_header}")
202
+ continue
203
+ if student_id in rows:
204
+ problems.append(f"grades.csv: {id_header} {student_id} appears twice")
205
+ continue
206
+ cells = [cell.strip() for cell in row[1:]]
207
+ rows[student_id] = dict(zip(score_headers, cells, strict=False))
208
+ if problems:
209
+ raise GradesError(problems)
210
+
211
+ # `IdField` narrowed by the membership test above.
212
+ id_field: IdField = next(name for name in ID_FIELDS if name == id_header)
213
+ return GradesCsv(id_field=id_field, headers=score_headers, rows=rows)
214
+
215
+
216
+ def build_roster(students: Sequence[ServerStudent], sheet: GradesCsv | None) -> Roster:
217
+ """
218
+ Match `grades.csv` to the enrolled students and build what `grade`
219
+ receives.
220
+
221
+ A student with no row reads `None` for every score. A row whose id
222
+ belongs to no student is listed in `unmatched` rather than refused: a
223
+ class list has students who never joined the course.
224
+ """
225
+ if sheet is None:
226
+ return Roster(students=tuple(to_student(student, {}) for student in students))
227
+
228
+ by_id = {
229
+ normalize_id(sheet.id_field, student_id): cells
230
+ for student_id, cells in sheet.rows.items()
231
+ }
232
+ matched: set[str] = set()
233
+ cells_by_username: dict[str, Mapping[str, str]] = {}
234
+ result: list[Student] = []
235
+ for student in students:
236
+ key = student_key(student, sheet.id_field)
237
+ cells = by_id.get(key, {}) if key is not None else {}
238
+ if key is not None and key in by_id:
239
+ matched.add(key)
240
+ cells_by_username[student.username] = cells
241
+ scores = {
242
+ header: guess_score(cells.get(header, "")) for header in sheet.headers
243
+ }
244
+ result.append(to_student(student, scores))
245
+
246
+ unmatched = tuple(
247
+ student_id
248
+ for student_id in sheet.rows
249
+ if normalize_id(sheet.id_field, student_id) not in matched
250
+ )
251
+ return Roster(
252
+ students=tuple(result),
253
+ headers=sheet.headers,
254
+ cells=cells_by_username,
255
+ id_field=sheet.id_field,
256
+ unmatched=unmatched,
257
+ )
258
+
259
+
260
+ #
261
+ # Columns
262
+ #
263
+ def compute_columns(
264
+ specs: Sequence[ColumnSpec], roster: Roster, grade: GradeFunction | None
265
+ ) -> tuple[GradeColumn, ...]:
266
+ """
267
+ Compute every declared column for every student.
268
+
269
+ A column takes the value `grade` returned for its slug, and for a
270
+ student where `grade` returned none, the `grades.csv` cell under the
271
+ same header.
272
+
273
+ Raises:
274
+ GradesError: `grade` raised, returned something that is not a
275
+ mapping, returned a key that is not a declared column or a
276
+ value that does not fit its column, a `grades.csv` cell does
277
+ not fit its column, or nothing produces a declared column.
278
+ """
279
+ declared = {spec.slug for spec in specs}
280
+ results: dict[str, Mapping[str, GradeValue]] = {}
281
+ problems: list[str] = []
282
+ returned: set[str] = set()
283
+
284
+ if grade is not None:
285
+ for student in roster.students:
286
+ try:
287
+ result = grade(student)
288
+ except Exception:
289
+ raise GradesError(
290
+ [
291
+ f"grades.py raised for {student.username}:\n"
292
+ f"{traceback.format_exc().rstrip()}"
293
+ ]
294
+ ) from None
295
+ if not isinstance(result, Mapping):
296
+ raise GradesError(
297
+ [
298
+ f"grades.py returned {type(result).__name__} for "
299
+ f"{student.username}, expected a dict of column slugs"
300
+ ]
301
+ )
302
+ results[student.username] = result
303
+ returned.update(str(key) for key in result)
304
+
305
+ for key in sorted(returned - declared):
306
+ problems.append(
307
+ f"grades.py returned {key!r}, which is not a column of codehood.toml"
308
+ )
309
+
310
+ if roster.students:
311
+ for spec in specs:
312
+ if spec.slug not in returned and spec.slug not in roster.headers:
313
+ problems.append(
314
+ f"column {spec.slug!r} has no value: grades.py does not "
315
+ "return it and grades.csv has no such column"
316
+ )
317
+
318
+ columns: list[GradeColumn] = []
319
+ for position, spec in enumerate(specs):
320
+ values: list[tuple[str, float | str]] = []
321
+ for student in roster.students:
322
+ result = results.get(student.username, {})
323
+ try:
324
+ if spec.slug in result:
325
+ value = fit_value(spec, result[spec.slug])
326
+ else:
327
+ cells = roster.cells.get(student.username, {})
328
+ value = fit_cell(spec, cells.get(spec.slug, ""))
329
+ except ValueError as exc:
330
+ problems.append(f"{student.username}, column {spec.slug!r}: {exc}")
331
+ continue
332
+ if value is not None:
333
+ values.append((student.username, value))
334
+ columns.append(
335
+ GradeColumn(
336
+ slug=spec.slug,
337
+ title=spec.title,
338
+ kind=spec.kind,
339
+ position=position,
340
+ values=tuple(sorted(values)),
341
+ )
342
+ )
343
+
344
+ if problems:
345
+ raise GradesError(problems)
346
+ return tuple(columns)
347
+
348
+
349
+ #
350
+ # Utilities
351
+ #
352
+ def to_student(student: ServerStudent, scores: Mapping[str, GradeValue]) -> Student:
353
+ """
354
+ The `Student` the instructor's function receives for one server
355
+ student.
356
+ """
357
+ return Student(
358
+ username=student.username,
359
+ name=student.name,
360
+ email=student.email,
361
+ school_id=student.school_id,
362
+ github=student.github,
363
+ status=student.status,
364
+ exams=student.exams,
365
+ scores=scores,
366
+ )
367
+
368
+
369
+ def student_key(student: ServerStudent, id_field: IdField) -> str | None:
370
+ """
371
+ The id `grades.csv` would list this student under, normalized, or
372
+ `None` when the student has no such id.
373
+ """
374
+ raw = {
375
+ "school_id": student.school_id,
376
+ "username": student.username,
377
+ "github": student.github,
378
+ "email": student.email,
379
+ }[id_field]
380
+ return normalize_id(id_field, raw) if raw else None
381
+
382
+
383
+ def normalize_id(id_field: IdField, value: str) -> str:
384
+ """
385
+ An id as it is compared: trimmed, and without regard to case for the
386
+ two kinds of id that have none.
387
+ """
388
+ value = value.strip()
389
+ return value.casefold() if id_field in ("email", "github") else value
390
+
391
+
392
+ def guess_score(cell: str) -> GradeValue:
393
+ """
394
+ A `grades.csv` cell as `Student.scores` holds it: `None` when empty, a
395
+ `float` when it reads as a number, the text otherwise.
396
+
397
+ `,` is accepted as the decimal separator, which is what a spreadsheet
398
+ in a comma-decimal locale exports.
399
+ """
400
+ if not cell:
401
+ return None
402
+ if NUMBER_RE.fullmatch(cell):
403
+ return float(cell.replace(",", "."))
404
+ return cell
405
+
406
+
407
+ def fit_value(spec: ColumnSpec, value: object) -> float | str | None:
408
+ """
409
+ A value `grade` returned, checked against its column.
410
+
411
+ Raises:
412
+ ValueError: The value is not what the column's kind takes.
413
+ """
414
+ if value is None:
415
+ return None
416
+ if spec.kind == "number":
417
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
418
+ raise ValueError(f"{value!r} is not a number")
419
+ if not math.isfinite(value):
420
+ raise ValueError(f"{value!r} is not a finite number")
421
+ return float(value)
422
+ if not isinstance(value, str):
423
+ raise ValueError(f"{value!r} is not a label")
424
+ return fit_label(value)
425
+
426
+
427
+ def fit_cell(spec: ColumnSpec, cell: str) -> float | str | None:
428
+ """
429
+ A `grades.csv` cell, read as its column's kind.
430
+
431
+ Raises:
432
+ ValueError: The cell is not what the column's kind takes.
433
+ """
434
+ if not cell:
435
+ return None
436
+ if spec.kind == "number":
437
+ if not NUMBER_RE.fullmatch(cell):
438
+ raise ValueError(f"{cell!r} in grades.csv is not a number")
439
+ return float(cell.replace(",", "."))
440
+ return fit_label(cell)
441
+
442
+
443
+ def fit_label(value: str) -> str | None:
444
+ """
445
+ A label, trimmed, or `None` when nothing is left of it.
446
+
447
+ Raises:
448
+ ValueError: The label is longer than the server stores.
449
+ """
450
+ label = value.strip()
451
+ if not label:
452
+ return None
453
+ if len(label) > MAX_LABEL:
454
+ raise ValueError(f"label {label!r} is longer than {MAX_LABEL} characters")
455
+ return label
codehood/push/hook.py ADDED
@@ -0,0 +1,48 @@
1
+ """
2
+ Loading the instructor's `grades.py`.
3
+
4
+ The one place `codehood push` runs code that is not its own. The script is
5
+ the instructor's, runs on their machine and reads only their own course --
6
+ see `dev/specs/to-review/push-grades.md`, "The function runs inside the CLI".
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib.util
12
+ import traceback
13
+ from pathlib import Path
14
+
15
+ from ..grades import GradeFunction
16
+ from .grades import GradesError
17
+
18
+ __all__ = ["load_grade_function"]
19
+
20
+ #: The name the instructor's function must have.
21
+ FUNCTION_NAME = "grade"
22
+
23
+
24
+ def load_grade_function(path: Path) -> GradeFunction:
25
+ """
26
+ Import `grades.py` from `path` and return its `grade` function.
27
+
28
+ Raises:
29
+ GradesError: The file does not import, or defines no callable
30
+ named `grade`.
31
+ """
32
+ spec = importlib.util.spec_from_file_location("codehood_course_grades", path)
33
+ if spec is None or spec.loader is None:
34
+ raise GradesError([f"{path} cannot be imported as a Python module"])
35
+
36
+ module = importlib.util.module_from_spec(spec)
37
+ try:
38
+ spec.loader.exec_module(module)
39
+ except Exception:
40
+ raise GradesError(
41
+ [f"{path} failed to import:\n{traceback.format_exc().rstrip()}"]
42
+ ) from None
43
+
44
+ function = getattr(module, FUNCTION_NAME, None)
45
+ if not callable(function):
46
+ raise GradesError([f"{path} defines no function named {FUNCTION_NAME!r}"])
47
+ grade: GradeFunction = function
48
+ return grade