mogs 0.7.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.
- mogs/__init__.py +17 -0
- mogs/_assertrewrite.py +44 -0
- mogs/_env.py +26 -0
- mogs/_run.py +111 -0
- mogs/_typst/preview/cmarker/0.1.10/LICENSE +7 -0
- mogs/_typst/preview/cmarker/0.1.10/lib.typ +462 -0
- mogs/_typst/preview/cmarker/0.1.10/plugin.wasm +0 -0
- mogs/_typst/preview/cmarker/0.1.10/typst.toml +11 -0
- mogs/_typst/preview/mitex/0.2.7/LICENSE +176 -0
- mogs/_typst/preview/mitex/0.2.7/lib.typ +1 -0
- mogs/_typst/preview/mitex/0.2.7/mitex.typ +45 -0
- mogs/_typst/preview/mitex/0.2.7/mitex.wasm +0 -0
- mogs/_typst/preview/mitex/0.2.7/specs/latex/standard.typ +1187 -0
- mogs/_typst/preview/mitex/0.2.7/specs/mod.typ +12 -0
- mogs/_typst/preview/mitex/0.2.7/specs/prelude.typ +230 -0
- mogs/_typst/preview/mitex/0.2.7/typst.toml +12 -0
- mogs/assignment.py +172 -0
- mogs/build.py +605 -0
- mogs/check.py +410 -0
- mogs/cli.py +272 -0
- mogs/config.py +619 -0
- mogs/environment.py +118 -0
- mogs/export.py +556 -0
- mogs/grader/__init__.py +1 -0
- mogs/grader/_process.py +383 -0
- mogs/grader/_user.py +7 -0
- mogs/grader/bundle.py +320 -0
- mogs/grader/child.py +317 -0
- mogs/grader/datafiles.py +54 -0
- mogs/grader/main.py +132 -0
- mogs/grader/protocol.py +175 -0
- mogs/grader/results.py +337 -0
- mogs/grader/sandbox.py +462 -0
- mogs/grader/templates/__init__.py +38 -0
- mogs/grader/templates/run_autograder +3 -0
- mogs/grader/templates/setup.sh +28 -0
- mogs/loader.py +260 -0
- mogs/pdf.py +676 -0
- mogs/regrade.py +223 -0
- mogs/requirements.py +232 -0
- mogs/runner.py +281 -0
- mogs/scaffold.py +155 -0
- mogs/selfcheck.py +173 -0
- mogs/source.py +1438 -0
- mogs/transform.py +769 -0
- mogs-0.7.0.dist-info/METADATA +17 -0
- mogs-0.7.0.dist-info/RECORD +49 -0
- mogs-0.7.0.dist-info/WHEEL +4 -0
- mogs-0.7.0.dist-info/entry_points.txt +3 -0
mogs/config.py
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
"""Assignment config from the notebook's calls, and text edits to its PEP 723 header.
|
|
2
|
+
|
|
3
|
+
The config lives in cells of the source notebook: `mogs.assignment(...)` for the assignment,
|
|
4
|
+
and `mogs.grade(...)` for each question. They are read from the AST, so
|
|
5
|
+
their arguments must be literals. The header edits work on the text, so comments and layout
|
|
6
|
+
outside the edited part survive.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import ast
|
|
10
|
+
import copy
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import tomllib
|
|
14
|
+
import unicodedata
|
|
15
|
+
from collections.abc import Iterable
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from enum import StrEnum
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
TOOL = "mogs"
|
|
21
|
+
PACKAGE = "mogs"
|
|
22
|
+
ASSIGNMENT = "mogs.assignment()"
|
|
23
|
+
# Folder next to the student notebook with its public tests, `tests/<qid>.py`.
|
|
24
|
+
TESTS_FOLDER = "tests"
|
|
25
|
+
MIN_MEMORY_MB = 2048
|
|
26
|
+
|
|
27
|
+
# The reference regex from PEP 723, for the `script` block.
|
|
28
|
+
HEADER_RE = re.compile(r"(?m)^# /// script$\s(?P<content>(^#(| .*)$\s)+)^# ///$")
|
|
29
|
+
TABLE_RE = re.compile(r"^\[\[?\s*([A-Za-z0-9_-]+(?:\s*\.\s*[A-Za-z0-9_-]+)*)\s*\]\]?\s*(#.*)?$")
|
|
30
|
+
NAME_RE = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)")
|
|
31
|
+
QID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9]*$")
|
|
32
|
+
# Characters Windows forbids in file names.
|
|
33
|
+
WINDOWS_FORBIDDEN = frozenset('<>:"|?*')
|
|
34
|
+
# Device names Windows reserves in any case, with or without an extension.
|
|
35
|
+
WINDOWS_RESERVED = frozenset(
|
|
36
|
+
{"con", "prn", "aux", "nul", *(f"{port}{n}" for port in ("com", "lpt") for n in range(1, 10))}
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ConfigError(Exception):
|
|
41
|
+
"""The notebook header or its config calls are invalid."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Api(StrEnum):
|
|
45
|
+
"""The functions of this package whose calls hold the config."""
|
|
46
|
+
|
|
47
|
+
ASSIGNMENT = "assignment"
|
|
48
|
+
GRADE = "grade"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True, slots=True)
|
|
52
|
+
class Question:
|
|
53
|
+
"""One graded question.
|
|
54
|
+
|
|
55
|
+
Attributes:
|
|
56
|
+
id: Question id, the `<qid>` in test names `test_<qid>_*`.
|
|
57
|
+
title: Name shown on Gradescope.
|
|
58
|
+
points: Maximum score.
|
|
59
|
+
manual: Graded by hand from the submitted PDF, not by tests.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
id: str
|
|
63
|
+
title: str
|
|
64
|
+
points: float
|
|
65
|
+
manual: bool = False
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True, slots=True)
|
|
69
|
+
class AssignmentConfig:
|
|
70
|
+
"""Assignment settings read from the notebook's config calls.
|
|
71
|
+
|
|
72
|
+
Attributes:
|
|
73
|
+
name: Assignment name. Defaults to the notebook's file stem.
|
|
74
|
+
notebook: File name of the source notebook.
|
|
75
|
+
questions: Questions by id, in notebook order.
|
|
76
|
+
files: Extra files (data) shipped with the notebook, relative to its directory.
|
|
77
|
+
timeout: Seconds allowed per test.
|
|
78
|
+
budget: Seconds allowed for the whole grading run.
|
|
79
|
+
memory_mb: Memory limit for student code, in MB (argument `memory`).
|
|
80
|
+
python: Python version on Gradescope.
|
|
81
|
+
requirements: Requirements file that overrides the header dependencies.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
name: str
|
|
85
|
+
notebook: str
|
|
86
|
+
questions: dict[str, Question]
|
|
87
|
+
files: tuple[str, ...] = ()
|
|
88
|
+
timeout: float = 60
|
|
89
|
+
budget: float = 540
|
|
90
|
+
memory_mb: int = 4096
|
|
91
|
+
python: str = "3.13"
|
|
92
|
+
requirements: Path | None = None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# Text
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def normalize_newlines(text: str) -> str:
|
|
99
|
+
r"""Turn `\r\n` and `\r` line ends into `\n`."""
|
|
100
|
+
|
|
101
|
+
return text.replace("\r\n", "\n").replace("\r", "\n")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def split_lines(text: str) -> list[str]:
|
|
105
|
+
r"""Split `text` into lines the way Python numbers them.
|
|
106
|
+
|
|
107
|
+
Unlike `str.splitlines`, this splits only at line ends, not at characters such as
|
|
108
|
+
`\x0c` or `\u2028`, so index `i` holds AST line `i + 1`.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
return normalize_newlines(text).split("\n")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# Reading
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def read_header(src: str) -> dict:
|
|
118
|
+
"""Parse the PEP 723 `script` header of a notebook.
|
|
119
|
+
|
|
120
|
+
Raises:
|
|
121
|
+
ConfigError: If the header is missing or is not valid TOML.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
_, body, _ = _split(src)
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
return tomllib.loads("\n".join(body))
|
|
128
|
+
except tomllib.TOMLDecodeError as e:
|
|
129
|
+
raise ConfigError(f"The `# /// script` header is not valid TOML: {e}") from e
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def read_config(src: str, path: Path) -> AssignmentConfig:
|
|
133
|
+
"""Read the config calls of the notebook at `path`.
|
|
134
|
+
|
|
135
|
+
The assignment comes from its one `assignment(...)` call. Each `grade(...)` call declares
|
|
136
|
+
a question, in file order. A question with `test_<qid>_*` functions is auto-graded; one
|
|
137
|
+
without is graded by hand.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
src: Notebook source.
|
|
141
|
+
path: Notebook path. Names the notebook and anchors `requirements`.
|
|
142
|
+
|
|
143
|
+
Raises:
|
|
144
|
+
ConfigError: If a call is missing, repeated or has an invalid argument. The message
|
|
145
|
+
names the call.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
src = normalize_newlines(src)
|
|
149
|
+
|
|
150
|
+
try:
|
|
151
|
+
tree = ast.parse(src)
|
|
152
|
+
except SyntaxError as e:
|
|
153
|
+
raise ConfigError(f"The notebook is not valid Python (line {e.lineno}): {e.msg}") from e
|
|
154
|
+
|
|
155
|
+
match api_calls(tree, tree, Api.ASSIGNMENT):
|
|
156
|
+
case [call]:
|
|
157
|
+
config = _assignment(call, path)
|
|
158
|
+
case []:
|
|
159
|
+
raise ConfigError(
|
|
160
|
+
f"The notebook has no `{ASSIGNMENT}` call. Add a cell with "
|
|
161
|
+
f'`mogs.assignment(name="{path.stem}")`.'
|
|
162
|
+
)
|
|
163
|
+
case [_, second, *_]:
|
|
164
|
+
raise ConfigError(
|
|
165
|
+
f"{ASSIGNMENT} (line {second.lineno}): the notebook calls it more than once."
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
tested = {
|
|
169
|
+
question_id(node.name)
|
|
170
|
+
for node in ast.walk(tree)
|
|
171
|
+
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)
|
|
172
|
+
and node.name.startswith("test_")
|
|
173
|
+
}
|
|
174
|
+
questions: dict[str, Question] = {}
|
|
175
|
+
lines: dict[str, int] = {}
|
|
176
|
+
|
|
177
|
+
for call in api_calls(tree, tree, Api.GRADE):
|
|
178
|
+
question = _question(call)
|
|
179
|
+
question = copy.replace(question, manual=question.id not in tested)
|
|
180
|
+
|
|
181
|
+
if question.id in questions:
|
|
182
|
+
raise ConfigError(
|
|
183
|
+
f"{_where(call)}: question `{question.id}` is declared more than once (first at "
|
|
184
|
+
f"line {lines[question.id]})."
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
questions[question.id] = question
|
|
188
|
+
lines[question.id] = call.lineno
|
|
189
|
+
|
|
190
|
+
if not questions:
|
|
191
|
+
raise ConfigError(
|
|
192
|
+
'The notebook has no questions. End each one with a `mogs.grade("q1", points=...)` '
|
|
193
|
+
"cell."
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
_check_file_names(list(questions))
|
|
197
|
+
|
|
198
|
+
return copy.replace(config, questions=questions)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def api_aliases(tree: ast.Module, api: Api) -> tuple[set[str], set[str]]:
|
|
202
|
+
"""Names the notebook's imports bind to this package, and to its function `api`."""
|
|
203
|
+
|
|
204
|
+
modules: set[str] = set()
|
|
205
|
+
functions: set[str] = set()
|
|
206
|
+
|
|
207
|
+
for node in ast.walk(tree):
|
|
208
|
+
match node:
|
|
209
|
+
case ast.Import(names=names):
|
|
210
|
+
modules |= {alias.asname or alias.name for alias in names if alias.name == PACKAGE}
|
|
211
|
+
case ast.ImportFrom(module=module, names=names) if module == PACKAGE:
|
|
212
|
+
functions |= {alias.asname or alias.name for alias in names if alias.name == api}
|
|
213
|
+
|
|
214
|
+
return modules, functions
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def api_calls(tree: ast.Module, node: ast.AST, api: Api) -> list[ast.Call]:
|
|
218
|
+
"""Calls to this package's function `api` inside `node`, in source order.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
tree: The whole notebook, for its imports.
|
|
222
|
+
node: The part to search.
|
|
223
|
+
api: The function.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
modules, functions = api_aliases(tree, api)
|
|
227
|
+
calls: list[ast.Call] = []
|
|
228
|
+
|
|
229
|
+
for call in ast.walk(node):
|
|
230
|
+
match call:
|
|
231
|
+
case ast.Call(func=ast.Attribute(value=ast.Name(id=module), attr=attr)) if (
|
|
232
|
+
module in modules and attr == api
|
|
233
|
+
):
|
|
234
|
+
calls.append(call)
|
|
235
|
+
case ast.Call(func=ast.Name(id=function)) if function in functions:
|
|
236
|
+
calls.append(call)
|
|
237
|
+
|
|
238
|
+
return sorted(calls, key=lambda call: (call.lineno, call.col_offset))
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _where(call: ast.Call) -> str:
|
|
242
|
+
"""`mogs.grade() (line 12)`: the call as written, and its line."""
|
|
243
|
+
|
|
244
|
+
return f"{ast.unparse(call.func)}() (line {call.lineno})"
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _arguments(call: ast.Call, allowed: Iterable[str]) -> dict[str, object]:
|
|
248
|
+
"""The keyword arguments of `call`, as literal values.
|
|
249
|
+
|
|
250
|
+
Raises:
|
|
251
|
+
ConfigError: If a keyword is not in `allowed`, is `**`, or is not a literal.
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
where = _where(call)
|
|
255
|
+
allowed = tuple(allowed)
|
|
256
|
+
values: dict[str, object] = {}
|
|
257
|
+
|
|
258
|
+
for keyword in call.keywords:
|
|
259
|
+
match keyword.arg:
|
|
260
|
+
case None:
|
|
261
|
+
raise ConfigError(f"{where}: write each argument out; `**` is not read.")
|
|
262
|
+
case str() as key if key not in allowed:
|
|
263
|
+
raise ConfigError(
|
|
264
|
+
f"{where}: unknown argument `{key}`. It takes {', '.join(allowed)}."
|
|
265
|
+
)
|
|
266
|
+
case str() as key:
|
|
267
|
+
try:
|
|
268
|
+
values[key] = ast.literal_eval(keyword.value)
|
|
269
|
+
except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError) as e:
|
|
270
|
+
raise ConfigError(
|
|
271
|
+
f"{where}: `{key}` must be a literal value, such as a number or a "
|
|
272
|
+
f"string, got `{ast.unparse(keyword.value)}`. The build reads it "
|
|
273
|
+
"without running the notebook."
|
|
274
|
+
) from e
|
|
275
|
+
|
|
276
|
+
return values
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _assignment(call: ast.Call, path: Path) -> AssignmentConfig:
|
|
280
|
+
"""The assignment settings of an `assignment(...)` call."""
|
|
281
|
+
|
|
282
|
+
where = _where(call)
|
|
283
|
+
|
|
284
|
+
if call.args:
|
|
285
|
+
raise ConfigError(f'{where}: pass each setting as a keyword, e.g. name="HW1".')
|
|
286
|
+
|
|
287
|
+
keys = ("name", "files", "timeout", "budget", "memory", "python", "requirements")
|
|
288
|
+
config = AssignmentConfig(name=path.stem, notebook=path.name, questions={})
|
|
289
|
+
|
|
290
|
+
for key, value in _arguments(call, keys).items():
|
|
291
|
+
match key:
|
|
292
|
+
case "name":
|
|
293
|
+
config = copy.replace(config, name=_string(where, key, value))
|
|
294
|
+
case "python":
|
|
295
|
+
config = copy.replace(config, python=_string(where, key, value))
|
|
296
|
+
case "files":
|
|
297
|
+
config = copy.replace(config, files=_files(where, value))
|
|
298
|
+
case "timeout":
|
|
299
|
+
config = copy.replace(config, timeout=_seconds(where, key, value))
|
|
300
|
+
case "budget":
|
|
301
|
+
config = copy.replace(config, budget=_seconds(where, key, value))
|
|
302
|
+
case "memory":
|
|
303
|
+
config = copy.replace(config, memory_mb=_memory(where, value))
|
|
304
|
+
case "requirements":
|
|
305
|
+
requirements = path.parent / _string(where, key, value)
|
|
306
|
+
config = copy.replace(config, requirements=requirements)
|
|
307
|
+
case _:
|
|
308
|
+
raise AssertionError(f"unhandled argument {key!r}")
|
|
309
|
+
|
|
310
|
+
return copy.replace(config, name=_name(where, config.name))
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _check_file_names(qids: list[str]) -> None:
|
|
314
|
+
"""Question ids name the public test files, `tests/<id>.py`.
|
|
315
|
+
|
|
316
|
+
Raises:
|
|
317
|
+
ConfigError: If an id is a name Windows reserves, or two ids differ only in case. Such
|
|
318
|
+
files would collide on macOS and Windows.
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
seen: dict[str, str] = {}
|
|
322
|
+
|
|
323
|
+
for qid in qids:
|
|
324
|
+
folded = qid.casefold()
|
|
325
|
+
|
|
326
|
+
if folded in WINDOWS_RESERVED:
|
|
327
|
+
raise ConfigError(
|
|
328
|
+
f"Question id `{qid}` is a file name Windows reserves. Its public tests go to "
|
|
329
|
+
f"`tests/{qid}.py`; pick another id."
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
if folded in seen:
|
|
333
|
+
raise ConfigError(
|
|
334
|
+
f"Question ids `{qid}` and `{seen[folded]}` differ only in case. Their public "
|
|
335
|
+
"test files would be the same file on macOS and Windows."
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
seen[folded] = qid
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def question_id(name: str) -> str:
|
|
342
|
+
"""Question id in a test name: `test_q1_norm` → `q1`."""
|
|
343
|
+
|
|
344
|
+
return name.removeprefix("test_").split("_", 1)[0]
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _question(call: ast.Call) -> Question:
|
|
348
|
+
"""The question a `grade(...)` call declares, as auto-graded."""
|
|
349
|
+
|
|
350
|
+
where = _where(call)
|
|
351
|
+
example = f'{ast.unparse(call.func)}("q1", points=10)'
|
|
352
|
+
|
|
353
|
+
match call.args:
|
|
354
|
+
case [ast.Constant(value=str() as qid)]:
|
|
355
|
+
pass
|
|
356
|
+
case [ast.Constant(value=str()), *_]:
|
|
357
|
+
raise ConfigError(f"{where}: pass `points` and `title` as keywords, e.g. {example}.")
|
|
358
|
+
case _:
|
|
359
|
+
raise ConfigError(
|
|
360
|
+
f"{where}: needs the question id as a string literal first argument, "
|
|
361
|
+
f"e.g. {example}."
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
if not QID_RE.match(qid):
|
|
365
|
+
raise ConfigError(
|
|
366
|
+
f"{where}: question id `{qid}` must be letters and digits, starting with a letter "
|
|
367
|
+
"(no `_`, since tests are named `test_<id>_<name>`)."
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
values = _arguments(call, ("points", "title"))
|
|
371
|
+
|
|
372
|
+
if "points" not in values:
|
|
373
|
+
raise ConfigError(f"{where}: needs `points`, e.g. {example}.")
|
|
374
|
+
|
|
375
|
+
title = values.get("title", default_title(qid))
|
|
376
|
+
match title:
|
|
377
|
+
case str():
|
|
378
|
+
pass
|
|
379
|
+
case _:
|
|
380
|
+
raise ConfigError(f"{where}: `title` must be a string, got {title!r}.")
|
|
381
|
+
|
|
382
|
+
return Question(qid, title, _points(where, values["points"]))
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _points(where: str, value: object) -> float:
|
|
386
|
+
match value:
|
|
387
|
+
case bool():
|
|
388
|
+
pass
|
|
389
|
+
case int() | float() if value >= 0:
|
|
390
|
+
return float(value)
|
|
391
|
+
raise ConfigError(f"{where}: `points` must be a number >= 0, got {value!r}.")
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def default_title(qid: str) -> str:
|
|
395
|
+
"""`q1` → `Question 1`, `question_2b` → `Question 2b`, any case; other ids stay as they are."""
|
|
396
|
+
|
|
397
|
+
match = re.fullmatch(r"(?:q|question)_?(\d\w*)", qid, re.IGNORECASE)
|
|
398
|
+
return f"Question {match.group(1)}" if match else qid
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _string(where: str, key: str, value: object) -> str:
|
|
402
|
+
match value:
|
|
403
|
+
case str():
|
|
404
|
+
return value
|
|
405
|
+
raise ConfigError(f"{where}: `{key}` must be a string, got {value!r}.")
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _name(where: str, value: str) -> str:
|
|
409
|
+
"""Check that the assignment name works as a file name, on Windows too.
|
|
410
|
+
|
|
411
|
+
The name names the autograder zip, the student zip and the folder in the student zip.
|
|
412
|
+
"""
|
|
413
|
+
|
|
414
|
+
if (
|
|
415
|
+
not value
|
|
416
|
+
or value.startswith(".")
|
|
417
|
+
or any(char in "/\\" or unicodedata.category(char) == "Cc" for char in value)
|
|
418
|
+
):
|
|
419
|
+
raise ConfigError(
|
|
420
|
+
f"{where}: `name` names the autograder zip, so it must not be empty, start with "
|
|
421
|
+
f"`.`, or hold `/`, `\\` or control characters; got {value!r}."
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
if (
|
|
425
|
+
value.split(".", 1)[0].casefold() in WINDOWS_RESERVED
|
|
426
|
+
or any(char in WINDOWS_FORBIDDEN for char in value)
|
|
427
|
+
or value.endswith((".", " "))
|
|
428
|
+
):
|
|
429
|
+
raise ConfigError(
|
|
430
|
+
f"{where}: `name` {value!r} is not a valid file name on Windows. It names the "
|
|
431
|
+
"student zip and its folder, which students on Windows must be able to unzip. Pick "
|
|
432
|
+
"another `name`, or set one if it comes from the notebook's file name."
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
return value
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def check_name(value: str) -> str:
|
|
439
|
+
"""Check that `value` works as an assignment name; see `_name`.
|
|
440
|
+
|
|
441
|
+
Raises:
|
|
442
|
+
ConfigError: If it does not.
|
|
443
|
+
"""
|
|
444
|
+
|
|
445
|
+
return _name("Assignment name", value)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _files(where: str, value: object) -> tuple[str, ...]:
|
|
449
|
+
match value:
|
|
450
|
+
case list() | tuple() if all(isinstance(item, str) for item in value):
|
|
451
|
+
return tuple(value)
|
|
452
|
+
raise ConfigError(f"{where}: `files` must be a list of paths, got {value!r}.")
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _seconds(where: str, key: str, value: object) -> float:
|
|
456
|
+
match value:
|
|
457
|
+
case bool():
|
|
458
|
+
pass
|
|
459
|
+
case int() | float() if value > 0:
|
|
460
|
+
return float(value)
|
|
461
|
+
raise ConfigError(f"{where}: `{key}` must be a number of seconds > 0, got {value!r}.")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _memory(where: str, value: object) -> int:
|
|
465
|
+
match value:
|
|
466
|
+
case bool():
|
|
467
|
+
pass
|
|
468
|
+
case int() if value >= MIN_MEMORY_MB:
|
|
469
|
+
return value
|
|
470
|
+
raise ConfigError(
|
|
471
|
+
f"{where}: `memory` must be a whole number of MB >= {MIN_MEMORY_MB}, got {value!r}."
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
# Header text edits
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def set_dependency(src: str, requirement: str) -> str:
|
|
479
|
+
"""Replace the header dependency with the same distribution name, or add it.
|
|
480
|
+
|
|
481
|
+
The first matching entry is replaced in place; further matches are removed. The
|
|
482
|
+
`dependencies` array is rewritten one entry per line.
|
|
483
|
+
|
|
484
|
+
Raises:
|
|
485
|
+
ConfigError: If the header is missing or `requirement` has no distribution name.
|
|
486
|
+
"""
|
|
487
|
+
|
|
488
|
+
name = normalized_name(requirement)
|
|
489
|
+
if name is None:
|
|
490
|
+
raise ConfigError(f"Not a requirement: {requirement!r}.")
|
|
491
|
+
|
|
492
|
+
deps = read_header(src).get("dependencies", [])
|
|
493
|
+
new: list[str] = []
|
|
494
|
+
for dep in deps:
|
|
495
|
+
if normalized_name(dep) != name:
|
|
496
|
+
new.append(dep)
|
|
497
|
+
elif requirement not in new:
|
|
498
|
+
new.append(requirement)
|
|
499
|
+
if requirement not in new:
|
|
500
|
+
new.append(requirement)
|
|
501
|
+
|
|
502
|
+
return _write_dependencies(src, new)
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def remove_dependency(src: str, dist_name: str) -> str:
|
|
506
|
+
"""Remove every header dependency on the distribution `dist_name`.
|
|
507
|
+
|
|
508
|
+
Returns `src` unchanged when no dependency matches. Otherwise the `dependencies` array
|
|
509
|
+
is rewritten one entry per line.
|
|
510
|
+
|
|
511
|
+
Raises:
|
|
512
|
+
ConfigError: If the header is missing or `dist_name` is not a distribution name.
|
|
513
|
+
"""
|
|
514
|
+
|
|
515
|
+
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", dist_name):
|
|
516
|
+
raise ConfigError(f"Not a distribution name: {dist_name!r}.")
|
|
517
|
+
|
|
518
|
+
name = normalized_name(dist_name)
|
|
519
|
+
deps = read_header(src).get("dependencies", [])
|
|
520
|
+
kept = [dep for dep in deps if normalized_name(dep) != name]
|
|
521
|
+
if len(kept) == len(deps):
|
|
522
|
+
return src
|
|
523
|
+
|
|
524
|
+
out = _write_dependencies(src, kept)
|
|
525
|
+
if read_header(out).get("dependencies") != kept:
|
|
526
|
+
raise ConfigError(f"Could not remove `{dist_name}` from the header's `dependencies`.")
|
|
527
|
+
|
|
528
|
+
return out
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _write_dependencies(src: str, deps: list[str]) -> str:
|
|
532
|
+
"""Write `deps` as the header's `dependencies` array, adding the array if missing."""
|
|
533
|
+
|
|
534
|
+
before, body, after = _split(src)
|
|
535
|
+
text = "\n".join(body)
|
|
536
|
+
array = ["dependencies = ["] + [f" {json.dumps(dep)}," for dep in deps] + ["]"]
|
|
537
|
+
|
|
538
|
+
span = _dependencies_span(text)
|
|
539
|
+
if span is None:
|
|
540
|
+
text = "\n".join(array + body)
|
|
541
|
+
else:
|
|
542
|
+
text = text[: span[0]] + "\n".join(array) + text[span[1] :]
|
|
543
|
+
|
|
544
|
+
return _join(before, text.split("\n"), after)
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def normalized_name(requirement: str) -> str | None:
|
|
548
|
+
"""Normalized distribution name (PEP 503) of a requirement string."""
|
|
549
|
+
|
|
550
|
+
match = NAME_RE.match(requirement)
|
|
551
|
+
return re.sub(r"[-_.]+", "-", match.group(1)).lower() if match else None
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _dependencies_span(text: str) -> tuple[int, int] | None:
|
|
555
|
+
"""Character span of the top-level `dependencies = [...]` in the header TOML."""
|
|
556
|
+
|
|
557
|
+
first_table = next(
|
|
558
|
+
(m.start() for m in re.finditer(r"(?m)^.*$", text) if _table_name(m.group())), len(text)
|
|
559
|
+
)
|
|
560
|
+
match = re.search(r"(?m)^dependencies\s*=\s*\[", text[:first_table])
|
|
561
|
+
if match is None:
|
|
562
|
+
return None
|
|
563
|
+
|
|
564
|
+
depth = 0
|
|
565
|
+
quote = None
|
|
566
|
+
i = match.end() - 1
|
|
567
|
+
|
|
568
|
+
while i < len(text):
|
|
569
|
+
char = text[i]
|
|
570
|
+
if quote is not None:
|
|
571
|
+
if char == "\\" and quote == '"':
|
|
572
|
+
i += 1
|
|
573
|
+
elif char == quote:
|
|
574
|
+
quote = None
|
|
575
|
+
elif char in "\"'":
|
|
576
|
+
quote = char
|
|
577
|
+
elif char == "#":
|
|
578
|
+
i = text.find("\n", i)
|
|
579
|
+
if i < 0:
|
|
580
|
+
break
|
|
581
|
+
elif char == "[":
|
|
582
|
+
depth += 1
|
|
583
|
+
elif char == "]":
|
|
584
|
+
depth -= 1
|
|
585
|
+
if depth == 0:
|
|
586
|
+
return match.start(), i + 1
|
|
587
|
+
i += 1
|
|
588
|
+
|
|
589
|
+
raise ConfigError("The header's `dependencies` array is not closed.")
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
# Header text helpers
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _split(src: str) -> tuple[str, list[str], str]:
|
|
596
|
+
"""Split `src` into text before the header body, the body as TOML lines, and the rest."""
|
|
597
|
+
|
|
598
|
+
src = normalize_newlines(src)
|
|
599
|
+
match = HEADER_RE.search(src)
|
|
600
|
+
if match is None:
|
|
601
|
+
raise ConfigError("No PEP 723 `# /// script` header found.")
|
|
602
|
+
|
|
603
|
+
content = match.group("content").removesuffix("\n")
|
|
604
|
+
body = [line[2:] for line in split_lines(content)]
|
|
605
|
+
return src[: match.start("content")], body, src[match.end("content") :]
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def _join(before: str, body: list[str], after: str) -> str:
|
|
609
|
+
"""Inverse of `_split`."""
|
|
610
|
+
|
|
611
|
+
lines = [f"# {line}" if line else "#" for line in body]
|
|
612
|
+
return before + "".join(line + "\n" for line in lines) + after
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _table_name(line: str) -> str | None:
|
|
616
|
+
"""Dotted name of a TOML table header line, with spaces around dots removed."""
|
|
617
|
+
|
|
618
|
+
match = TABLE_RE.match(line.strip())
|
|
619
|
+
return re.sub(r"\s+", "", match.group(1)) if match else None
|