codehood-cli 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codehood/__init__.py +0 -0
- codehood/__main__.py +4 -0
- codehood/actions/__init__.py +0 -0
- codehood/actions/base.py +119 -0
- codehood/actions/resources.py +30 -0
- codehood/api/__init__.py +0 -0
- codehood/api/base.py +256 -0
- codehood/api/generate.py +1370 -0
- codehood/api/generated.py +3818 -0
- codehood/api/openapi.py +134 -0
- codehood/api/pages.py +53 -0
- codehood/cli/__init__.py +64 -0
- codehood/cli/api.py +422 -0
- codehood/cli/attendance.py +136 -0
- codehood/cli/auth.py +106 -0
- codehood/cli/base.py +42 -0
- codehood/cli/chill.py +52 -0
- codehood/cli/exam.py +107 -0
- codehood/cli/grades.py +185 -0
- codehood/cli/init.py +161 -0
- codehood/cli/push.py +609 -0
- codehood/cli/show.py +77 -0
- codehood/cli/uitils.py +26 -0
- codehood/functional.py +40 -0
- codehood/globs.py +71 -0
- codehood/grades.py +74 -0
- codehood/hypothesis.py +274 -0
- codehood/models/__init__.py +0 -0
- codehood/models/base.py +15 -0
- codehood/models/repo.py +187 -0
- codehood/models/validators.py +177 -0
- codehood/push/__init__.py +225 -0
- codehood/push/base.py +216 -0
- codehood/push/calendar.py +664 -0
- codehood/push/errors.py +136 -0
- codehood/push/exam.py +636 -0
- codehood/push/exclude.py +60 -0
- codehood/push/grades.py +455 -0
- codehood/push/hook.py +48 -0
- codehood/push/links.py +614 -0
- codehood/push/ours.py +78 -0
- codehood/push/plan.py +1981 -0
- codehood/push/project.py +272 -0
- codehood/push/question.py +338 -0
- codehood/push/report.py +244 -0
- codehood/push/repository.py +326 -0
- codehood/push/resource.py +576 -0
- codehood/push/run.py +1275 -0
- codehood/push/unconsumed.py +208 -0
- codehood/push/wire.py +222 -0
- codehood/py.typed +0 -0
- codehood/repo/__init__.py +62 -0
- codehood/repo/_config.py +28 -0
- codehood/repo/_layout.py +132 -0
- codehood/repo/_scaffold.py +244 -0
- codehood/repo/diff.py +71 -0
- codehood/repo/file_tracker.py +124 -0
- codehood/theme.py +101 -0
- codehood/widgets/__init__.py +0 -0
- codehood/widgets/mascot.py +76 -0
- codehood/widgets/questions/__init__.py +65 -0
- codehood/widgets/questions/base.py +119 -0
- codehood/widgets/questions/controls.py +194 -0
- codehood/widgets/questions/fill_in.py +81 -0
- codehood/widgets/questions/responses.py +137 -0
- codehood/widgets/questions/simple.py +117 -0
- codehood_cli-0.5.0.dist-info/METADATA +294 -0
- codehood_cli-0.5.0.dist-info/RECORD +71 -0
- codehood_cli-0.5.0.dist-info/WHEEL +4 -0
- codehood_cli-0.5.0.dist-info/entry_points.txt +4 -0
- codehood_cli-0.5.0.dist-info/licenses/LICENSE +21 -0
codehood/cli/push.py
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`codehood push`: sync a local course repository to the server. See
|
|
3
|
+
`dev/specs/to-do/push.md` and `docs/design/mapping-local-filesystem.md`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from dataclasses import replace
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Annotated, assert_never
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
import typer
|
|
15
|
+
from pydantic import ValidationError
|
|
16
|
+
|
|
17
|
+
from .. import repo
|
|
18
|
+
from ..api.base import get_client
|
|
19
|
+
from ..models.repo import RepoConfig
|
|
20
|
+
from ..push.base import BaseState, load_base, save_base
|
|
21
|
+
from ..push.calendar import allocate, parse_calendar
|
|
22
|
+
from ..push.errors import (
|
|
23
|
+
CalendarError,
|
|
24
|
+
QuestionSourceError,
|
|
25
|
+
RepositoryError,
|
|
26
|
+
ResourceFileError,
|
|
27
|
+
ResourceLinkError,
|
|
28
|
+
SlugCollisionError,
|
|
29
|
+
)
|
|
30
|
+
from ..push.exam import ExamFile, inline_questions, scan_exams
|
|
31
|
+
from ..push.exclude import scan_excluded
|
|
32
|
+
from ..push.grades import GradesError
|
|
33
|
+
from ..push.links import (
|
|
34
|
+
attach_repositories,
|
|
35
|
+
attach_resources,
|
|
36
|
+
rewrite_body_links,
|
|
37
|
+
rewrite_event_links,
|
|
38
|
+
rewrite_repository_links,
|
|
39
|
+
)
|
|
40
|
+
from ..push.ours import ours_warnings, resolve_ours
|
|
41
|
+
from ..push.plan import (
|
|
42
|
+
DeleteCalendarEvent,
|
|
43
|
+
DeleteExam,
|
|
44
|
+
DeleteGradeColumn,
|
|
45
|
+
DeleteQuestion,
|
|
46
|
+
DeleteRepository,
|
|
47
|
+
DeleteResource,
|
|
48
|
+
DeleteRollCall,
|
|
49
|
+
DeleteTimeSlot,
|
|
50
|
+
IgnoredExamPolicy,
|
|
51
|
+
KeptCancelled,
|
|
52
|
+
KeptDraftPublished,
|
|
53
|
+
KeptExamLive,
|
|
54
|
+
KeptForRollCall,
|
|
55
|
+
KeptPinnedSlot,
|
|
56
|
+
KeptRepository,
|
|
57
|
+
LocalState,
|
|
58
|
+
Notice,
|
|
59
|
+
Plan,
|
|
60
|
+
Rejected,
|
|
61
|
+
ServerDrifted,
|
|
62
|
+
UpsertCalendarEvent,
|
|
63
|
+
UpsertCourse,
|
|
64
|
+
UpsertExam,
|
|
65
|
+
UpsertGradeColumn,
|
|
66
|
+
UpsertQuestion,
|
|
67
|
+
UpsertRepository,
|
|
68
|
+
UpsertResource,
|
|
69
|
+
UpsertTimeSlot,
|
|
70
|
+
Write,
|
|
71
|
+
plan_sync,
|
|
72
|
+
)
|
|
73
|
+
from ..push.question import QuestionFile, scan_questions
|
|
74
|
+
from ..push.report import (
|
|
75
|
+
describe_server_drifted,
|
|
76
|
+
sync_exit_code,
|
|
77
|
+
sync_lines,
|
|
78
|
+
sync_summary,
|
|
79
|
+
)
|
|
80
|
+
from ..push.repository import scan_repositories
|
|
81
|
+
from ..push.resource import read_course_readme, scan_resources
|
|
82
|
+
from ..push.run import (
|
|
83
|
+
HttpRepositoryApi,
|
|
84
|
+
OpResult,
|
|
85
|
+
apply,
|
|
86
|
+
fetch_server_state,
|
|
87
|
+
run_plan,
|
|
88
|
+
)
|
|
89
|
+
from ..push.unconsumed import (
|
|
90
|
+
consumed_paths,
|
|
91
|
+
excluded_paths,
|
|
92
|
+
find_unconsumed,
|
|
93
|
+
ignore_patterns,
|
|
94
|
+
list_files,
|
|
95
|
+
read_ignore,
|
|
96
|
+
)
|
|
97
|
+
from ..repo.file_tracker import scan_files
|
|
98
|
+
from .base import app
|
|
99
|
+
from .grades import read_grade_sheet, unmatched_warnings
|
|
100
|
+
|
|
101
|
+
__all__ = ["push"]
|
|
102
|
+
|
|
103
|
+
#: Ops a `--no-prune` run reports instead of running.
|
|
104
|
+
PRUNE_OPS = (
|
|
105
|
+
DeleteResource,
|
|
106
|
+
DeleteQuestion,
|
|
107
|
+
DeleteTimeSlot,
|
|
108
|
+
DeleteCalendarEvent,
|
|
109
|
+
DeleteRollCall,
|
|
110
|
+
DeleteGradeColumn,
|
|
111
|
+
DeleteRepository,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@app.command()
|
|
116
|
+
def push(
|
|
117
|
+
path: Annotated[
|
|
118
|
+
Path,
|
|
119
|
+
typer.Argument(
|
|
120
|
+
help="Course repository to push. Defaults to the current directory."
|
|
121
|
+
),
|
|
122
|
+
] = Path("."),
|
|
123
|
+
dry_run: Annotated[
|
|
124
|
+
bool,
|
|
125
|
+
typer.Option("--dry-run", help="Print the plan; write nothing."),
|
|
126
|
+
] = False,
|
|
127
|
+
prune: Annotated[
|
|
128
|
+
bool,
|
|
129
|
+
typer.Option(
|
|
130
|
+
"--prune/--no-prune",
|
|
131
|
+
help="Delete server entities whose local source is gone (default: on).",
|
|
132
|
+
),
|
|
133
|
+
] = True,
|
|
134
|
+
drop_roll_calls: Annotated[
|
|
135
|
+
bool,
|
|
136
|
+
typer.Option(
|
|
137
|
+
"--drop-roll-calls",
|
|
138
|
+
help="Also delete the roll call of an event removed from the calendar.",
|
|
139
|
+
),
|
|
140
|
+
] = False,
|
|
141
|
+
drop_repositories: Annotated[
|
|
142
|
+
bool,
|
|
143
|
+
typer.Option(
|
|
144
|
+
"--drop-repositories",
|
|
145
|
+
help="Delete server repositories whose folder is gone from repositories/.",
|
|
146
|
+
),
|
|
147
|
+
] = False,
|
|
148
|
+
message: Annotated[
|
|
149
|
+
str | None,
|
|
150
|
+
typer.Option(
|
|
151
|
+
"-m",
|
|
152
|
+
"--message",
|
|
153
|
+
help="Commit message for every repository this push changes.",
|
|
154
|
+
),
|
|
155
|
+
] = None,
|
|
156
|
+
ours: Annotated[
|
|
157
|
+
list[str] | None,
|
|
158
|
+
typer.Option(
|
|
159
|
+
"--ours",
|
|
160
|
+
help=(
|
|
161
|
+
"Settle the conflicts matching this glob, written <kind>/<key> "
|
|
162
|
+
"(e.g. resource/intro), by sending the local version. "
|
|
163
|
+
"Repeatable."
|
|
164
|
+
),
|
|
165
|
+
),
|
|
166
|
+
] = None,
|
|
167
|
+
) -> None:
|
|
168
|
+
"""
|
|
169
|
+
Sync the repository's course row, repositories, calendar, resources, questions,
|
|
170
|
+
exams and grade columns.
|
|
171
|
+
"""
|
|
172
|
+
try:
|
|
173
|
+
config = RepoConfig.open(repo.config_path(path))
|
|
174
|
+
local = read_local_state(path, config)
|
|
175
|
+
except (
|
|
176
|
+
FileNotFoundError,
|
|
177
|
+
ValidationError,
|
|
178
|
+
CalendarError,
|
|
179
|
+
SlugCollisionError,
|
|
180
|
+
QuestionSourceError,
|
|
181
|
+
ResourceLinkError,
|
|
182
|
+
ResourceFileError,
|
|
183
|
+
RepositoryError,
|
|
184
|
+
) as exc:
|
|
185
|
+
typer.echo(f"error: {exc}", err=True)
|
|
186
|
+
raise typer.Exit(code=1) from exc
|
|
187
|
+
|
|
188
|
+
for warning in local.warnings:
|
|
189
|
+
typer.echo(f"warning {warning}", err=True)
|
|
190
|
+
|
|
191
|
+
try:
|
|
192
|
+
sync(
|
|
193
|
+
path,
|
|
194
|
+
config,
|
|
195
|
+
local,
|
|
196
|
+
dry_run=dry_run,
|
|
197
|
+
prune=prune,
|
|
198
|
+
drop_roll_calls=drop_roll_calls,
|
|
199
|
+
drop_repositories=drop_repositories,
|
|
200
|
+
message=message,
|
|
201
|
+
ours=ours or [],
|
|
202
|
+
)
|
|
203
|
+
except httpx.TransportError as exc:
|
|
204
|
+
typer.echo(f"error: could not reach {config.server.url}: {exc}", err=True)
|
|
205
|
+
raise typer.Exit(code=1) from exc
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def sync(
|
|
209
|
+
path: Path,
|
|
210
|
+
config: RepoConfig,
|
|
211
|
+
local: LocalState,
|
|
212
|
+
*,
|
|
213
|
+
dry_run: bool,
|
|
214
|
+
prune: bool,
|
|
215
|
+
drop_roll_calls: bool,
|
|
216
|
+
drop_repositories: bool = False,
|
|
217
|
+
message: str | None = None,
|
|
218
|
+
ours: Sequence[str] = (),
|
|
219
|
+
) -> None:
|
|
220
|
+
"""
|
|
221
|
+
Read the server's state, plan the push, and run it or print it.
|
|
222
|
+
|
|
223
|
+
Raises:
|
|
224
|
+
typer.Exit: With code 1 when an operation or the grade columns failed.
|
|
225
|
+
httpx.TransportError: When the server cannot be reached.
|
|
226
|
+
"""
|
|
227
|
+
client = get_client(config.server.url)
|
|
228
|
+
repositories = HttpRepositoryApi(client, local.discipline, local.course)
|
|
229
|
+
try:
|
|
230
|
+
server = fetch_server_state(
|
|
231
|
+
local.discipline, local.course, client, repositories
|
|
232
|
+
)
|
|
233
|
+
except httpx.HTTPStatusError as exc:
|
|
234
|
+
typer.echo(f"error: could not read the server's current state: {exc}", err=True)
|
|
235
|
+
raise typer.Exit(code=1) from exc
|
|
236
|
+
|
|
237
|
+
grades_failed = False
|
|
238
|
+
try:
|
|
239
|
+
sheet = read_grade_sheet(path, config, client=client)
|
|
240
|
+
except GradesError as exc:
|
|
241
|
+
for problem in exc.problems:
|
|
242
|
+
typer.echo(f"error: grades: {problem}", err=True)
|
|
243
|
+
grades_failed = True
|
|
244
|
+
local = replace(local, grade_columns=None)
|
|
245
|
+
except httpx.HTTPStatusError as exc:
|
|
246
|
+
typer.echo(
|
|
247
|
+
f"error: grades: could not read the course's grades: {exc}", err=True
|
|
248
|
+
)
|
|
249
|
+
grades_failed = True
|
|
250
|
+
local = replace(local, grade_columns=None)
|
|
251
|
+
else:
|
|
252
|
+
for warning in unmatched_warnings(sheet.roster):
|
|
253
|
+
typer.echo(f"warning {warning}", err=True)
|
|
254
|
+
local = replace(local, grade_columns=sheet.columns)
|
|
255
|
+
|
|
256
|
+
base = load_base(path)
|
|
257
|
+
for warning in base.warnings:
|
|
258
|
+
typer.echo(f"warning {warning}", err=True)
|
|
259
|
+
|
|
260
|
+
plan = plan_sync(
|
|
261
|
+
local,
|
|
262
|
+
base,
|
|
263
|
+
server,
|
|
264
|
+
drop_roll_calls=drop_roll_calls,
|
|
265
|
+
drop_repositories=drop_repositories,
|
|
266
|
+
message=message,
|
|
267
|
+
ours=ours,
|
|
268
|
+
)
|
|
269
|
+
for warning in ours_warnings(plan, ours):
|
|
270
|
+
typer.echo(f"warning {warning}", err=True)
|
|
271
|
+
plan = resolve_ours(plan, ours)
|
|
272
|
+
|
|
273
|
+
for file in local.excluded:
|
|
274
|
+
typer.echo(f"excluded {file.path}")
|
|
275
|
+
excluded_note = f", {len(local.excluded)} excluded" if local.excluded else ""
|
|
276
|
+
for unconsumed in local.unconsumed:
|
|
277
|
+
typer.echo(f"not pushed (no handler): {unconsumed}")
|
|
278
|
+
# `sync_lines` renders the drift notices along with the pulls and conflicts.
|
|
279
|
+
for notice in plan.notices:
|
|
280
|
+
if not isinstance(notice, ServerDrifted):
|
|
281
|
+
typer.echo(notice_line(notice))
|
|
282
|
+
for line in sync_lines(plan):
|
|
283
|
+
typer.echo(line)
|
|
284
|
+
|
|
285
|
+
if dry_run:
|
|
286
|
+
for op in plan.writes:
|
|
287
|
+
typer.echo(f"planned {describe(op)}")
|
|
288
|
+
typer.echo(dry_run_summary(plan) + excluded_note)
|
|
289
|
+
_echo_sync_summary(plan)
|
|
290
|
+
if exit_code(plan, (), grades_failed=grades_failed):
|
|
291
|
+
raise typer.Exit(code=1)
|
|
292
|
+
return
|
|
293
|
+
|
|
294
|
+
to_run: list[Write] = []
|
|
295
|
+
skipped: list[Write] = []
|
|
296
|
+
for op in plan.writes:
|
|
297
|
+
(skipped if isinstance(op, PRUNE_OPS) and not prune else to_run).append(op)
|
|
298
|
+
|
|
299
|
+
for op in skipped:
|
|
300
|
+
typer.echo(f"skipped {describe(op)} (--no-prune)")
|
|
301
|
+
|
|
302
|
+
results: list[OpResult] = []
|
|
303
|
+
try:
|
|
304
|
+
for result in run_plan(
|
|
305
|
+
to_run,
|
|
306
|
+
discipline=local.discipline,
|
|
307
|
+
course=local.course,
|
|
308
|
+
client=client,
|
|
309
|
+
repositories=repositories,
|
|
310
|
+
):
|
|
311
|
+
results.append(result)
|
|
312
|
+
if result.skipped:
|
|
313
|
+
typer.echo(f"skipped {describe(result.op)} ({result.message})")
|
|
314
|
+
continue
|
|
315
|
+
status = "ok" if result.ok else "failed"
|
|
316
|
+
typer.echo(f"{status:>6} {describe(result.op)}: {result.message}")
|
|
317
|
+
finally:
|
|
318
|
+
record_base(path, base, plan, results)
|
|
319
|
+
|
|
320
|
+
failures = [result for result in results if not result.ok and not result.skipped]
|
|
321
|
+
typer.echo(run_summary(plan, results, skipped=len(skipped)) + excluded_note)
|
|
322
|
+
_echo_sync_summary(plan)
|
|
323
|
+
if failures:
|
|
324
|
+
typer.echo("failures:")
|
|
325
|
+
for result in failures:
|
|
326
|
+
typer.echo(f" {describe(result.op)}: {result.message}")
|
|
327
|
+
if grades_failed:
|
|
328
|
+
typer.echo("grade columns were not pushed, see the errors above")
|
|
329
|
+
if exit_code(plan, results, grades_failed=grades_failed):
|
|
330
|
+
raise typer.Exit(code=1)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def record_base(
|
|
334
|
+
path: Path, base: BaseState, plan: Plan, results: list[OpResult]
|
|
335
|
+
) -> None:
|
|
336
|
+
"""
|
|
337
|
+
Write the base the push leaves behind, and say so when it cannot.
|
|
338
|
+
|
|
339
|
+
Runs even when the push stops halfway, so what already went through is
|
|
340
|
+
not forgotten. A base that cannot be written costs the next push its
|
|
341
|
+
memory, not this one its result.
|
|
342
|
+
"""
|
|
343
|
+
state = apply(base, plan, results)
|
|
344
|
+
if state == base and not base.warnings:
|
|
345
|
+
return
|
|
346
|
+
try:
|
|
347
|
+
save_base(path, state)
|
|
348
|
+
except OSError as exc:
|
|
349
|
+
typer.echo(f"warning could not record the base: {exc}", err=True)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def exit_code(
|
|
353
|
+
plan: Plan, results: Sequence[OpResult], *, grades_failed: bool = False
|
|
354
|
+
) -> int:
|
|
355
|
+
"""
|
|
356
|
+
The exit code of a push: failed when a question was rejected, a conflict
|
|
357
|
+
remains, a write failed or the grade columns could not be computed.
|
|
358
|
+
"""
|
|
359
|
+
failed = bool(plan.rejected) or grades_failed or bool(sync_exit_code(plan))
|
|
360
|
+
return int(failed or any(not result.ok for result in results))
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _echo_sync_summary(plan: Plan) -> None:
|
|
364
|
+
if summary := sync_summary(plan):
|
|
365
|
+
typer.echo(summary)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def dry_run_summary(plan: Plan) -> str:
|
|
369
|
+
"""
|
|
370
|
+
The summary line of a `--dry-run`: planned writes, apart from the
|
|
371
|
+
rejected questions.
|
|
372
|
+
"""
|
|
373
|
+
return (
|
|
374
|
+
f"summary: {len(plan.writes)} operation(s) planned, 0 executed (--dry-run)"
|
|
375
|
+
f"{_invalid_note(plan)}"
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def run_summary(plan: Plan, results: Sequence[OpResult], *, skipped: int) -> str:
|
|
380
|
+
"""
|
|
381
|
+
The summary line of a push that ran: counts only writes, never notices.
|
|
382
|
+
|
|
383
|
+
`skipped` is the number of writes `--no-prune` held back; `results` that
|
|
384
|
+
were never attempted are counted apart.
|
|
385
|
+
"""
|
|
386
|
+
attempted = [result for result in results if not result.skipped]
|
|
387
|
+
failed = sum(1 for result in attempted if not result.ok)
|
|
388
|
+
not_attempted = len(results) - len(attempted)
|
|
389
|
+
return (
|
|
390
|
+
f"summary: {len(attempted)} operation(s) executed, {failed} failed, "
|
|
391
|
+
f"{skipped} skipped"
|
|
392
|
+
f"{f', {not_attempted} not attempted' if not_attempted else ''}"
|
|
393
|
+
f"{_invalid_note(plan)}"
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _invalid_note(plan: Plan) -> str:
|
|
398
|
+
return f", {len(plan.rejected)} invalid" if plan.rejected else ""
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def read_local_state(path: Path, config: RepoConfig) -> LocalState:
|
|
402
|
+
"""
|
|
403
|
+
Read a course repository into the value `plan_sync` diffs.
|
|
404
|
+
|
|
405
|
+
Every read and every parse happens here, before the first network
|
|
406
|
+
call, so a malformed repository costs nothing and writes nothing.
|
|
407
|
+
|
|
408
|
+
Raises:
|
|
409
|
+
FileNotFoundError: `codehood.toml`, `README.md` or `calendar.md` is
|
|
410
|
+
missing. The mapping makes all three mandatory: the last two
|
|
411
|
+
are the only source of the course's description and dates.
|
|
412
|
+
CalendarError: `calendar.md` does not parse.
|
|
413
|
+
SlugCollisionError: Two resources or two questions want one slug.
|
|
414
|
+
QuestionSourceError: A test file or an attachment linked by a question
|
|
415
|
+
or an exam cannot be read or is over the upload limit.
|
|
416
|
+
RepositoryError: A folder under `repositories/` cannot be pushed.
|
|
417
|
+
ResourceLinkError: A lesson links a missing resource or repository.
|
|
418
|
+
ResourceFileError: An `info.yaml` or a `.url` file is malformed.
|
|
419
|
+
"""
|
|
420
|
+
readme_path = path / "README.md"
|
|
421
|
+
if not readme_path.exists():
|
|
422
|
+
raise FileNotFoundError(
|
|
423
|
+
f"no README.md at {path} -- it is the course description"
|
|
424
|
+
)
|
|
425
|
+
description, readme = read_course_readme(
|
|
426
|
+
readme_path.read_text(encoding="utf-8"), config.course.description, readme_path
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
calendar_path = path / "calendar.md"
|
|
430
|
+
if not calendar_path.exists():
|
|
431
|
+
raise FileNotFoundError(
|
|
432
|
+
f"no calendar.md at {path} -- it sets the course's start and end"
|
|
433
|
+
)
|
|
434
|
+
calendar = parse_calendar(calendar_path.read_text(encoding="utf-8"))
|
|
435
|
+
allocation = allocate(calendar)
|
|
436
|
+
|
|
437
|
+
key = config.key
|
|
438
|
+
ignore = read_ignore(path)
|
|
439
|
+
exclude = [*config.push.exclude, *ignore_patterns(path, ignore)]
|
|
440
|
+
tracked = tuple(scan_files(path, exclude))
|
|
441
|
+
files, gitignore = list_files(path)
|
|
442
|
+
trees = tuple(scan_repositories(path, exclude))
|
|
443
|
+
linked = attach_repositories(allocation.events, trees)
|
|
444
|
+
extras = (readme,) if readme is not None else ()
|
|
445
|
+
scanned = tuple(scan_resources(path, exclude, extras))
|
|
446
|
+
resources = rewrite_body_links(attach_resources(linked, scanned, path), path, key)
|
|
447
|
+
|
|
448
|
+
questions = tuple(scan_questions(path, exclude))
|
|
449
|
+
excluded = tuple(scan_excluded(path, exclude))
|
|
450
|
+
exams = tuple(scan_exams(path, questions, excluded))
|
|
451
|
+
sources = [
|
|
452
|
+
source
|
|
453
|
+
for question in (*questions, *inline_questions(exams))
|
|
454
|
+
if isinstance(question, QuestionFile)
|
|
455
|
+
for source in question.sources
|
|
456
|
+
]
|
|
457
|
+
sources.extend(
|
|
458
|
+
source
|
|
459
|
+
for exam in exams
|
|
460
|
+
if isinstance(exam, ExamFile)
|
|
461
|
+
for source in exam.sources
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
return LocalState(
|
|
465
|
+
key=key,
|
|
466
|
+
description=description,
|
|
467
|
+
start=calendar.start,
|
|
468
|
+
end=calendar.end,
|
|
469
|
+
slots=calendar.slots,
|
|
470
|
+
events=rewrite_repository_links(
|
|
471
|
+
rewrite_event_links(linked, resources, path, key), key
|
|
472
|
+
),
|
|
473
|
+
resources=resources,
|
|
474
|
+
repositories=trees,
|
|
475
|
+
questions=questions,
|
|
476
|
+
exams=exams,
|
|
477
|
+
excluded=excluded,
|
|
478
|
+
unconsumed=find_unconsumed(
|
|
479
|
+
files,
|
|
480
|
+
consumed=consumed_paths(tracked, sources=sources, root=path),
|
|
481
|
+
excluded=excluded_paths(tracked),
|
|
482
|
+
gitignore=gitignore,
|
|
483
|
+
codehoodignore=ignore,
|
|
484
|
+
),
|
|
485
|
+
warnings=allocation.warnings,
|
|
486
|
+
)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def describe(op: Write) -> str:
|
|
490
|
+
"""
|
|
491
|
+
Render one operation as the line `push` prints for it.
|
|
492
|
+
"""
|
|
493
|
+
match op:
|
|
494
|
+
case UpsertCourse():
|
|
495
|
+
return f"course {op.discipline}/{op.course}"
|
|
496
|
+
case UpsertResource():
|
|
497
|
+
return f"resource {op.slug} ({op.data.type})"
|
|
498
|
+
case DeleteResource():
|
|
499
|
+
return f"delete resource {op.slug}"
|
|
500
|
+
case UpsertQuestion():
|
|
501
|
+
return f"question {op.slug}"
|
|
502
|
+
case DeleteQuestion():
|
|
503
|
+
return f"delete question {op.slug}"
|
|
504
|
+
case UpsertExam():
|
|
505
|
+
return f"exam {op.slug} ({op.payload['type']}, {op.status})"
|
|
506
|
+
case DeleteExam():
|
|
507
|
+
return f"delete exam {op.slug}"
|
|
508
|
+
case UpsertTimeSlot():
|
|
509
|
+
return f"time slot {op.slot.slug}"
|
|
510
|
+
case DeleteTimeSlot():
|
|
511
|
+
return f"delete time slot {op.slug}"
|
|
512
|
+
case UpsertCalendarEvent():
|
|
513
|
+
return f"event {op.event.week}/{op.event.time_slot} ({op.event.kind})"
|
|
514
|
+
case DeleteCalendarEvent():
|
|
515
|
+
return f"delete event {op.week}/{op.time_slot}"
|
|
516
|
+
case UpsertGradeColumn():
|
|
517
|
+
return f"grade column {op.column.slug} ({len(op.column.values)} values)"
|
|
518
|
+
case DeleteGradeColumn():
|
|
519
|
+
return f"delete grade column {op.slug}"
|
|
520
|
+
case DeleteRollCall():
|
|
521
|
+
return f"delete roll call {op.week}/{op.time_slot}"
|
|
522
|
+
case UpsertRepository() | DeleteRepository():
|
|
523
|
+
return describe_repository(op)
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def describe_repository(op: UpsertRepository | DeleteRepository) -> str:
|
|
527
|
+
"""
|
|
528
|
+
Render one repository operation as the line `push` prints for it.
|
|
529
|
+
|
|
530
|
+
`UpsertRepository` reads `repository lab1: 3 files (1.2 MB), commit
|
|
531
|
+
4f2a9c1`, with the first 7 hex digits of the local `tree_sha`.
|
|
532
|
+
"""
|
|
533
|
+
match op:
|
|
534
|
+
case UpsertRepository():
|
|
535
|
+
count = len(op.tree.entries)
|
|
536
|
+
noun = "file" if count == 1 else "files"
|
|
537
|
+
return (
|
|
538
|
+
f"repository {op.tree.slug}: {count} {noun} "
|
|
539
|
+
f"({format_size(op.tree.size)}), commit {op.tree.tree_sha[:7]}"
|
|
540
|
+
)
|
|
541
|
+
case DeleteRepository():
|
|
542
|
+
return f"delete repository {op.slug}"
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def describe_notice(notice: Notice) -> str:
|
|
546
|
+
"""
|
|
547
|
+
Render one notice as the text `push` prints after its `invalid` or
|
|
548
|
+
`warning` prefix.
|
|
549
|
+
"""
|
|
550
|
+
match notice:
|
|
551
|
+
case Rejected():
|
|
552
|
+
return f"{notice.kind} {notice.slug} ({notice.path.name}): {notice.reason}"
|
|
553
|
+
case KeptDraftPublished():
|
|
554
|
+
return (
|
|
555
|
+
f"question {notice.slug} (its file marks a draft): kept "
|
|
556
|
+
f"{notice.status}; hide it on the web or drop the `_`"
|
|
557
|
+
)
|
|
558
|
+
case KeptExamLive():
|
|
559
|
+
wanted = f" (file says {notice.wanted})" if notice.wanted else ""
|
|
560
|
+
return f"exam {notice.slug} kept at {notice.status}{wanted}"
|
|
561
|
+
case IgnoredExamPolicy():
|
|
562
|
+
return (
|
|
563
|
+
f"exam {notice.slug}: {', '.join(notice.fields)} "
|
|
564
|
+
"not sent, the server has no field for it"
|
|
565
|
+
)
|
|
566
|
+
case KeptPinnedSlot():
|
|
567
|
+
events = ", ".join(f"{week}/{notice.slug}" for week in notice.weeks)
|
|
568
|
+
plural = len(notice.weeks) > 1
|
|
569
|
+
return (
|
|
570
|
+
f"time slot {notice.slug} kept (event{'s' if plural else ''} "
|
|
571
|
+
f"{events} {'are' if plural else 'is'} CANCELLED)"
|
|
572
|
+
)
|
|
573
|
+
case KeptForRollCall():
|
|
574
|
+
return (
|
|
575
|
+
f"event {notice.week}/{notice.time_slot} kept: it has a roll call "
|
|
576
|
+
f"with {notice.attendances} attendance(s); use --drop-roll-calls "
|
|
577
|
+
"to delete it"
|
|
578
|
+
)
|
|
579
|
+
case KeptRepository():
|
|
580
|
+
return (
|
|
581
|
+
f"repository {notice.slug} kept: its folder is gone; "
|
|
582
|
+
"use --drop-repositories to delete it"
|
|
583
|
+
)
|
|
584
|
+
case KeptCancelled():
|
|
585
|
+
return f"event {notice.week}/{notice.time_slot} kept: it is CANCELLED"
|
|
586
|
+
case ServerDrifted():
|
|
587
|
+
return describe_server_drifted(notice).removeprefix("warning ")
|
|
588
|
+
case _:
|
|
589
|
+
assert_never(notice)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def notice_line(notice: Notice) -> str:
|
|
593
|
+
"""
|
|
594
|
+
The line `push` prints for a notice: `invalid` when it fails the push,
|
|
595
|
+
`warning` otherwise.
|
|
596
|
+
"""
|
|
597
|
+
prefix = "invalid" if isinstance(notice, Rejected) else "warning"
|
|
598
|
+
return f"{prefix} {describe_notice(notice)}"
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def format_size(size: int) -> str:
|
|
602
|
+
"""
|
|
603
|
+
A byte count in decimal units, e.g. `1.2 MB`.
|
|
604
|
+
"""
|
|
605
|
+
if size < 1000:
|
|
606
|
+
return f"{size} B"
|
|
607
|
+
if size < 1_000_000:
|
|
608
|
+
return f"{size / 1000:.1f} kB"
|
|
609
|
+
return f"{size / 1_000_000:.1f} MB"
|
codehood/cli/show.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`codehood show`: open one MDQ question file in the interactive widget for its
|
|
3
|
+
type, for manually exercising `src/codehood_cli/widgets/questions/`.
|
|
4
|
+
Provisional -- see `dev/specs/to-do/question-widgets.md`'s "Out of scope".
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Annotated
|
|
11
|
+
|
|
12
|
+
import mdq
|
|
13
|
+
import typer
|
|
14
|
+
from textual.app import ComposeResult
|
|
15
|
+
from textual.widgets import Footer
|
|
16
|
+
|
|
17
|
+
from ..theme import CodehoodApp
|
|
18
|
+
from ..widgets.questions import (
|
|
19
|
+
QUESTION_WIDGETS,
|
|
20
|
+
QuestionDocument,
|
|
21
|
+
QuestionWidget,
|
|
22
|
+
Response,
|
|
23
|
+
question_document,
|
|
24
|
+
)
|
|
25
|
+
from .base import app
|
|
26
|
+
|
|
27
|
+
__all__ = ["show"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@app.command()
|
|
31
|
+
def show(
|
|
32
|
+
file: Annotated[Path, typer.Argument(help="Path to a single-question MDQ file.")],
|
|
33
|
+
) -> None:
|
|
34
|
+
"""
|
|
35
|
+
Open a question file in its interactive widget and print what you submit.
|
|
36
|
+
"""
|
|
37
|
+
text = file.read_text(encoding="utf-8")
|
|
38
|
+
try:
|
|
39
|
+
parsed = mdq.parse(text)
|
|
40
|
+
except mdq.MdqError as exc:
|
|
41
|
+
typer.echo(f"error: {exc}", err=True)
|
|
42
|
+
raise typer.Exit(code=1) from exc
|
|
43
|
+
|
|
44
|
+
if isinstance(parsed, mdq.Exam):
|
|
45
|
+
typer.echo(
|
|
46
|
+
"error: `codehood show` only handles a single question, not an exam",
|
|
47
|
+
err=True,
|
|
48
|
+
)
|
|
49
|
+
raise typer.Exit(code=1)
|
|
50
|
+
document = question_document(parsed)
|
|
51
|
+
|
|
52
|
+
widget_class = QUESTION_WIDGETS.get(document["type"])
|
|
53
|
+
if widget_class is None:
|
|
54
|
+
typer.echo(f"error: no widget for question type {document['type']!r}", err=True)
|
|
55
|
+
raise typer.Exit(code=1)
|
|
56
|
+
|
|
57
|
+
response = ShowApp(document, widget_class).run()
|
|
58
|
+
if response is not None:
|
|
59
|
+
typer.echo(response)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ShowApp(CodehoodApp[Response]):
|
|
63
|
+
"""Mounts the widget for `document`'s type; exits with the `Response` it submits."""
|
|
64
|
+
|
|
65
|
+
BINDINGS = [("q", "quit", "Quit")]
|
|
66
|
+
TITLE = "codehood show"
|
|
67
|
+
|
|
68
|
+
def __init__(
|
|
69
|
+
self, document: QuestionDocument, widget_class: type[QuestionWidget]
|
|
70
|
+
) -> None:
|
|
71
|
+
super().__init__()
|
|
72
|
+
self.document = document
|
|
73
|
+
self.widget_class = widget_class
|
|
74
|
+
|
|
75
|
+
def compose(self) -> ComposeResult:
|
|
76
|
+
yield self.widget_class(self.document, on_response=self.exit)
|
|
77
|
+
yield Footer()
|
codehood/cli/uitils.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import typer
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def require(
|
|
5
|
+
flag: str,
|
|
6
|
+
value: str | None,
|
|
7
|
+
*,
|
|
8
|
+
interactive: bool,
|
|
9
|
+
prompt: str,
|
|
10
|
+
default: str | None = None,
|
|
11
|
+
) -> str:
|
|
12
|
+
"""
|
|
13
|
+
Resolve a required value: the flag if given, else a default, else a
|
|
14
|
+
prompt when stdin is a TTY, else a non-zero exit naming the flag.
|
|
15
|
+
|
|
16
|
+
Prompting only when interactive is what makes `init` testable without
|
|
17
|
+
driving a pty -- see the spec's "Every value is a flag" section.
|
|
18
|
+
"""
|
|
19
|
+
if value is not None:
|
|
20
|
+
return value
|
|
21
|
+
if default is not None:
|
|
22
|
+
return default
|
|
23
|
+
if interactive:
|
|
24
|
+
return typer.prompt(prompt)
|
|
25
|
+
typer.echo(f"error: missing required option '--{flag}'", err=True)
|
|
26
|
+
raise typer.Exit(code=1)
|