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
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`codehood attendance`: show a course's attendance report, or write it as CSV.
|
|
3
|
+
|
|
4
|
+
The CSV mirrors the server's download (`attendanceCsvRows` in
|
|
5
|
+
`src/services/attendance-table.ts`), so both produce the same bytes.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import csv
|
|
11
|
+
import io
|
|
12
|
+
import math
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Annotated
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
import typer
|
|
18
|
+
from pydantic import ValidationError
|
|
19
|
+
from rich.console import Console
|
|
20
|
+
from rich.table import Table
|
|
21
|
+
|
|
22
|
+
from .. import repo
|
|
23
|
+
from ..api import generated
|
|
24
|
+
from ..api.base import get_client
|
|
25
|
+
from ..models.repo import RepoConfig
|
|
26
|
+
from .base import app
|
|
27
|
+
|
|
28
|
+
__all__ = ["attendance", "csv_text", "render_table"]
|
|
29
|
+
|
|
30
|
+
#: How a cell shows in the CSV: present, absent and anything else.
|
|
31
|
+
_CSV_CELLS = {"present": "1", "absent": "0"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@app.command()
|
|
35
|
+
def attendance(
|
|
36
|
+
path: Annotated[
|
|
37
|
+
Path,
|
|
38
|
+
typer.Argument(help="Course repository. Defaults to the current directory."),
|
|
39
|
+
] = Path("."),
|
|
40
|
+
csv_path: Annotated[
|
|
41
|
+
Path | None,
|
|
42
|
+
typer.Option("--csv", help="Write the report to this CSV file."),
|
|
43
|
+
] = None,
|
|
44
|
+
) -> None:
|
|
45
|
+
"""
|
|
46
|
+
Print the course's attendance table, or write it to a CSV file.
|
|
47
|
+
"""
|
|
48
|
+
try:
|
|
49
|
+
config = RepoConfig.open(repo.config_path(path))
|
|
50
|
+
except (FileNotFoundError, ValidationError) as exc:
|
|
51
|
+
typer.echo(f"error: {exc}", err=True)
|
|
52
|
+
raise typer.Exit(code=1) from exc
|
|
53
|
+
|
|
54
|
+
client = get_client(config.server.url)
|
|
55
|
+
try:
|
|
56
|
+
report = generated.course_attendance(
|
|
57
|
+
discipline=config.course.discipline,
|
|
58
|
+
course=f"{config.course.instructor}_{config.course.edition}",
|
|
59
|
+
client=client,
|
|
60
|
+
)
|
|
61
|
+
except httpx.HTTPStatusError as exc:
|
|
62
|
+
typer.echo(f"error: could not read the course's attendance: {exc}", err=True)
|
|
63
|
+
raise typer.Exit(code=1) from exc
|
|
64
|
+
|
|
65
|
+
if csv_path is not None:
|
|
66
|
+
with csv_path.open("w", encoding="utf-8", newline="") as file:
|
|
67
|
+
file.write(csv_text(report))
|
|
68
|
+
typer.echo(f"wrote {csv_path}")
|
|
69
|
+
return
|
|
70
|
+
|
|
71
|
+
if not report.events:
|
|
72
|
+
typer.echo("The course has no roll call yet")
|
|
73
|
+
return
|
|
74
|
+
Console().print(render_table(report))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def csv_text(report: generated.CourseAttendanceResponse) -> str:
|
|
78
|
+
"""
|
|
79
|
+
The report as CSV: `\\r\\n` between lines, quoting only where needed, and
|
|
80
|
+
no trailing newline.
|
|
81
|
+
"""
|
|
82
|
+
keys = [f"{event.week}/{event.time_slot}" for event in report.events]
|
|
83
|
+
buffer = io.StringIO(newline="")
|
|
84
|
+
writer = csv.writer(buffer, lineterminator="\r\n")
|
|
85
|
+
writer.writerow(
|
|
86
|
+
["username", "name", "schoolId", "status", *keys, "present", "total", "%"]
|
|
87
|
+
)
|
|
88
|
+
for student in report.students:
|
|
89
|
+
writer.writerow(
|
|
90
|
+
[
|
|
91
|
+
student.username,
|
|
92
|
+
student.name,
|
|
93
|
+
student.school_id or "",
|
|
94
|
+
student.status.lower(),
|
|
95
|
+
*(_CSV_CELLS.get(student.cells.get(key, ""), "-") for key in keys),
|
|
96
|
+
student.present,
|
|
97
|
+
student.total,
|
|
98
|
+
_percent(student.present, student.total),
|
|
99
|
+
]
|
|
100
|
+
)
|
|
101
|
+
return buffer.getvalue().removesuffix("\r\n")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def render_table(report: generated.CourseAttendanceResponse) -> Table:
|
|
105
|
+
"""
|
|
106
|
+
The report as a table: one row per student, one column per roll call.
|
|
107
|
+
"""
|
|
108
|
+
keys = [f"{event.week}/{event.time_slot}" for event in report.events]
|
|
109
|
+
table = Table()
|
|
110
|
+
table.add_column("Student")
|
|
111
|
+
table.add_column("Status")
|
|
112
|
+
for key in keys:
|
|
113
|
+
table.add_column(key, justify="center")
|
|
114
|
+
table.add_column("Present", justify="right")
|
|
115
|
+
table.add_column("%", justify="right")
|
|
116
|
+
|
|
117
|
+
for student in report.students:
|
|
118
|
+
table.add_row(
|
|
119
|
+
student.username,
|
|
120
|
+
student.status,
|
|
121
|
+
*(_CSV_CELLS.get(student.cells.get(key, ""), "-") for key in keys),
|
|
122
|
+
f"{student.present}/{student.total}",
|
|
123
|
+
_percent(student.present, student.total),
|
|
124
|
+
)
|
|
125
|
+
return table
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _percent(present: int, total: int) -> str:
|
|
129
|
+
"""
|
|
130
|
+
Attendance percentage with two decimals, empty without a roll call.
|
|
131
|
+
|
|
132
|
+
Rounds half up, like the server.
|
|
133
|
+
"""
|
|
134
|
+
if total == 0:
|
|
135
|
+
return ""
|
|
136
|
+
return f"{math.floor(present / total * 10000 + 0.5) / 100:.2f}"
|
codehood/cli/auth.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`codehood login` / `codehood logout`. See `dev/specs/to-review/login.md`.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
import typer
|
|
11
|
+
|
|
12
|
+
from .. import repo
|
|
13
|
+
from ..api import generated
|
|
14
|
+
from ..api.base import (
|
|
15
|
+
TOKEN_ENV,
|
|
16
|
+
CodehoodAPIError,
|
|
17
|
+
delete_token,
|
|
18
|
+
env_token,
|
|
19
|
+
get_client,
|
|
20
|
+
load_login,
|
|
21
|
+
load_stored_token,
|
|
22
|
+
save_token,
|
|
23
|
+
)
|
|
24
|
+
from ..models.repo import RepoConfig
|
|
25
|
+
from .base import app
|
|
26
|
+
|
|
27
|
+
__all__ = ["login", "logout"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@app.command()
|
|
31
|
+
def login() -> None:
|
|
32
|
+
"""
|
|
33
|
+
Exchange a login and password for a CLI API key, and store it.
|
|
34
|
+
|
|
35
|
+
The login prompt defaults to the course's instructor in `codehood.toml`.
|
|
36
|
+
There is one stored login per server, so logging in as someone else
|
|
37
|
+
replaces the previous one, and says so.
|
|
38
|
+
"""
|
|
39
|
+
config = _repo_config()
|
|
40
|
+
server_url = config.server.url
|
|
41
|
+
login_name = typer.prompt("Login", default=config.course.instructor)
|
|
42
|
+
password = typer.prompt("Password", hide_input=True)
|
|
43
|
+
|
|
44
|
+
client = get_client(server_url)
|
|
45
|
+
try:
|
|
46
|
+
result = generated.login(
|
|
47
|
+
body=generated.LoginRequest(login=login_name, password=password),
|
|
48
|
+
client=client,
|
|
49
|
+
)
|
|
50
|
+
except CodehoodAPIError as exc:
|
|
51
|
+
typer.echo(f"error: {exc.payload}", err=True)
|
|
52
|
+
raise typer.Exit(code=1) from exc
|
|
53
|
+
except httpx.HTTPError as exc:
|
|
54
|
+
typer.echo(f"error: could not reach {server_url}: {exc}", err=True)
|
|
55
|
+
raise typer.Exit(code=1) from exc
|
|
56
|
+
|
|
57
|
+
key = str(client.base_url)
|
|
58
|
+
if load_stored_token(key) is not None and load_login(key) != login_name:
|
|
59
|
+
previous = load_login(key)
|
|
60
|
+
was = f" (was {previous})" if previous else ""
|
|
61
|
+
typer.echo(f"replacing the stored login for {server_url}{was}")
|
|
62
|
+
save_token(key, result.token, login=login_name)
|
|
63
|
+
typer.echo(f"logged in to {server_url} as {login_name}")
|
|
64
|
+
_note_env_override()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@app.command()
|
|
68
|
+
def logout() -> None:
|
|
69
|
+
"""
|
|
70
|
+
Forget the locally stored CLI API key for the current repository's server.
|
|
71
|
+
"""
|
|
72
|
+
server_url = _repo_config().server.url
|
|
73
|
+
client = get_client(server_url)
|
|
74
|
+
key = str(client.base_url)
|
|
75
|
+
previous = load_login(key)
|
|
76
|
+
if delete_token(key):
|
|
77
|
+
was = f" (forgot the login of {previous})" if previous else ""
|
|
78
|
+
typer.echo(f"logged out of {server_url}{was}")
|
|
79
|
+
else:
|
|
80
|
+
typer.echo(f"not logged in to {server_url}")
|
|
81
|
+
typer.echo(
|
|
82
|
+
"note: this only forgets the key locally -- the server has no way "
|
|
83
|
+
"yet to revoke it remotely; use /profile for that."
|
|
84
|
+
)
|
|
85
|
+
_note_env_override()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _note_env_override() -> None:
|
|
89
|
+
if env_token() is not None:
|
|
90
|
+
typer.echo(f"note: {TOKEN_ENV} is set and overrides the stored key")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _repo_config() -> RepoConfig:
|
|
94
|
+
"""
|
|
95
|
+
The current repository's `codehood.toml`, or a clean exit if there isn't
|
|
96
|
+
one.
|
|
97
|
+
|
|
98
|
+
Neither command takes a `--server` flag -- see the spec's "Login and
|
|
99
|
+
logout take no flags".
|
|
100
|
+
"""
|
|
101
|
+
path = repo.config_path(Path())
|
|
102
|
+
config = repo.read_config(path)
|
|
103
|
+
if config is None:
|
|
104
|
+
typer.echo(f"error: could not find Codehood config at {path}", err=True)
|
|
105
|
+
raise typer.Exit(code=1)
|
|
106
|
+
return config
|
codehood/cli/base.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Annotated
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from .. import repo
|
|
9
|
+
|
|
10
|
+
app = typer.Typer(
|
|
11
|
+
name="codehood",
|
|
12
|
+
help="Codehood CLI",
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.callback()
|
|
17
|
+
def configure(
|
|
18
|
+
ctx: typer.Context,
|
|
19
|
+
config: Annotated[
|
|
20
|
+
Path | None,
|
|
21
|
+
typer.Option(
|
|
22
|
+
"--config",
|
|
23
|
+
"-c",
|
|
24
|
+
envvar="CODEHOOD_CONFIG",
|
|
25
|
+
help=(
|
|
26
|
+
"Read this file instead of codehood.toml in the repository root. "
|
|
27
|
+
"Must come before the command."
|
|
28
|
+
),
|
|
29
|
+
),
|
|
30
|
+
] = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
"""
|
|
33
|
+
Codehood CLI
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
typer.Exit: With code 1 when `config` does not exist and the command
|
|
37
|
+
is not `init`, which creates it.
|
|
38
|
+
"""
|
|
39
|
+
repo.set_config_override(config)
|
|
40
|
+
if config is not None and ctx.invoked_subcommand != "init" and not config.is_file():
|
|
41
|
+
typer.echo(f"error: could not find Codehood config at {config}", err=True)
|
|
42
|
+
raise typer.Exit(code=1)
|
codehood/cli/chill.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`codehood chill`: does nothing useful -- just mounts the mascot and lets it
|
|
3
|
+
blink and hop until you quit.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from textual.app import ComposeResult
|
|
9
|
+
from textual.containers import Vertical
|
|
10
|
+
from textual.widgets import Static
|
|
11
|
+
|
|
12
|
+
from ..theme import CodehoodApp
|
|
13
|
+
from ..widgets.mascot import Mascot
|
|
14
|
+
from .base import app
|
|
15
|
+
|
|
16
|
+
__all__ = ["chill"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@app.command()
|
|
20
|
+
def chill() -> None:
|
|
21
|
+
"""
|
|
22
|
+
Chill for a bit.
|
|
23
|
+
"""
|
|
24
|
+
ChillApp().run()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ChillApp(CodehoodApp[None]):
|
|
28
|
+
"""Full-screen mascot with a "Chilling..." caption. Press q to quit."""
|
|
29
|
+
|
|
30
|
+
BINDINGS = [("q", "quit", "Quit")]
|
|
31
|
+
TITLE = "codehood chill"
|
|
32
|
+
|
|
33
|
+
DEFAULT_CSS = """
|
|
34
|
+
Screen {
|
|
35
|
+
align: center middle;
|
|
36
|
+
}
|
|
37
|
+
#chill {
|
|
38
|
+
width: auto;
|
|
39
|
+
height: auto;
|
|
40
|
+
align: center middle;
|
|
41
|
+
}
|
|
42
|
+
#caption {
|
|
43
|
+
margin-top: 1;
|
|
44
|
+
width: auto;
|
|
45
|
+
text-align: center;
|
|
46
|
+
}
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def compose(self) -> ComposeResult:
|
|
50
|
+
with Vertical(id="chill"):
|
|
51
|
+
yield Mascot(id="mascot")
|
|
52
|
+
yield Static("Chilling...", id="caption")
|
codehood/cli/exam.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`codehood exam`: commands that act on one exam of the course on the server.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Annotated
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
import typer
|
|
12
|
+
from pydantic import ValidationError
|
|
13
|
+
|
|
14
|
+
from .. import repo
|
|
15
|
+
from ..api import generated
|
|
16
|
+
from ..api.base import get_client
|
|
17
|
+
from ..models.repo import RepoConfig
|
|
18
|
+
from .base import app
|
|
19
|
+
|
|
20
|
+
__all__ = ["exam", "refusal_text", "release"]
|
|
21
|
+
|
|
22
|
+
exam = typer.Typer(name="exam", help="Act on one exam of the course.")
|
|
23
|
+
app.add_typer(exam)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@exam.command()
|
|
27
|
+
def release(
|
|
28
|
+
slug: Annotated[str, typer.Argument(help="Slug of the exam.")],
|
|
29
|
+
path: Annotated[
|
|
30
|
+
Path,
|
|
31
|
+
typer.Argument(help="Course repository. Defaults to the current directory."),
|
|
32
|
+
] = Path("."),
|
|
33
|
+
) -> None:
|
|
34
|
+
"""
|
|
35
|
+
Release the grades of an exam to its students.
|
|
36
|
+
|
|
37
|
+
Releasing an exam already released changes nothing.
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
typer.Exit: With code 1 when the repository has no valid
|
|
41
|
+
`codehood.toml`, or the server refuses the release.
|
|
42
|
+
"""
|
|
43
|
+
try:
|
|
44
|
+
config = RepoConfig.open(repo.config_path(path))
|
|
45
|
+
except (FileNotFoundError, ValidationError) as exc:
|
|
46
|
+
typer.echo(f"error: {exc}", err=True)
|
|
47
|
+
raise typer.Exit(code=1) from exc
|
|
48
|
+
|
|
49
|
+
client = get_client(config.server.url)
|
|
50
|
+
try:
|
|
51
|
+
result = generated.exam_release(
|
|
52
|
+
discipline=config.course.discipline,
|
|
53
|
+
course=f"{config.course.instructor}_{config.course.edition}",
|
|
54
|
+
slug=slug,
|
|
55
|
+
client=client,
|
|
56
|
+
)
|
|
57
|
+
except generated.GradeReleaseRefused as exc:
|
|
58
|
+
typer.echo(f"error: cannot release {slug}: {refusal_text(exc)}", err=True)
|
|
59
|
+
raise typer.Exit(code=1) from exc
|
|
60
|
+
except httpx.HTTPStatusError as exc:
|
|
61
|
+
typer.echo(f"error: {status_text(slug, exc.response.status_code)}", err=True)
|
|
62
|
+
raise typer.Exit(code=1) from exc
|
|
63
|
+
|
|
64
|
+
typer.echo(f"released the grades of {slug} at {result.grades_released_at}")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def refusal_text(exc: generated.GradeReleaseRefused) -> str:
|
|
68
|
+
"""
|
|
69
|
+
Why the server refused to release an exam, with the counts it checked.
|
|
70
|
+
"""
|
|
71
|
+
match exc.reason:
|
|
72
|
+
case "not-closed":
|
|
73
|
+
return (
|
|
74
|
+
"the exam is not closed yet. Close it on the exam's page "
|
|
75
|
+
"(this also ends the attempts still open), then release again"
|
|
76
|
+
)
|
|
77
|
+
case "pending":
|
|
78
|
+
return f"{plural(exc.payload.pending_answers, 'answer')} still without a grade"
|
|
79
|
+
case "exception-open":
|
|
80
|
+
count = exc.payload.open_exceptions
|
|
81
|
+
verb = "keeps" if count == 1 else "keep"
|
|
82
|
+
return f"{plural(count, 'student exception')} still {verb} a personal window open"
|
|
83
|
+
case "not-an-exam":
|
|
84
|
+
return "it is a quiz or a practice; only an EXAM releases grades"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
#
|
|
88
|
+
# Utilities
|
|
89
|
+
#
|
|
90
|
+
def status_text(slug: str, status: int) -> str:
|
|
91
|
+
"""
|
|
92
|
+
The error line for a failed release the server gave no reason for.
|
|
93
|
+
"""
|
|
94
|
+
match status:
|
|
95
|
+
case 403:
|
|
96
|
+
return f"not allowed to release {slug}: only the course's instructor can"
|
|
97
|
+
case 404:
|
|
98
|
+
return f"no exam {slug} in this course"
|
|
99
|
+
case _:
|
|
100
|
+
return f"could not release {slug}: the server answered {status}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def plural(count: int, noun: str) -> str:
|
|
104
|
+
"""
|
|
105
|
+
`count` followed by `noun`, with an `s` unless `count` is 1.
|
|
106
|
+
"""
|
|
107
|
+
return f"{count} {noun}" if count == 1 else f"{count} {noun}s"
|
codehood/cli/grades.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`codehood grades`: print the grade columns `codehood push` would send.
|
|
3
|
+
|
|
4
|
+
Also home to `read_grade_sheet`, the one place that gathers what the columns
|
|
5
|
+
are computed from: `codehood.toml`, `grades.csv`, `grades.py` and the
|
|
6
|
+
server's exam results. See `dev/specs/to-review/push-grades.md`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Annotated
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
import typer
|
|
17
|
+
from pydantic import ValidationError
|
|
18
|
+
from rich.console import Console
|
|
19
|
+
from rich.table import Table
|
|
20
|
+
|
|
21
|
+
from .. import repo
|
|
22
|
+
from ..api.base import get_client
|
|
23
|
+
from ..models.repo import RepoConfig
|
|
24
|
+
from ..push.grades import (
|
|
25
|
+
ColumnSpec,
|
|
26
|
+
GradeColumn,
|
|
27
|
+
GradesError,
|
|
28
|
+
Roster,
|
|
29
|
+
build_roster,
|
|
30
|
+
compute_columns,
|
|
31
|
+
parse_grades_csv,
|
|
32
|
+
)
|
|
33
|
+
from ..push.hook import load_grade_function
|
|
34
|
+
from ..push.run import fetch_students
|
|
35
|
+
from .base import app
|
|
36
|
+
|
|
37
|
+
__all__ = ["GradeSheet", "grades", "read_grade_sheet", "unmatched_warnings"]
|
|
38
|
+
|
|
39
|
+
CSV_FILE = "grades.csv"
|
|
40
|
+
SCRIPT_FILE = "grades.py"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class GradeSheet:
|
|
45
|
+
"""
|
|
46
|
+
The computed grade columns, with the students they were computed for.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
columns: tuple[GradeColumn, ...] = ()
|
|
50
|
+
roster: Roster = Roster()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@app.command()
|
|
54
|
+
def grades(
|
|
55
|
+
path: Annotated[
|
|
56
|
+
Path,
|
|
57
|
+
typer.Argument(help="Course repository. Defaults to the current directory."),
|
|
58
|
+
] = Path("."),
|
|
59
|
+
) -> None:
|
|
60
|
+
"""
|
|
61
|
+
Print the grade columns a push would send. Writes nothing.
|
|
62
|
+
"""
|
|
63
|
+
try:
|
|
64
|
+
config = RepoConfig.open(repo.config_path(path))
|
|
65
|
+
except (FileNotFoundError, ValidationError) as exc:
|
|
66
|
+
typer.echo(f"error: {exc}", err=True)
|
|
67
|
+
raise typer.Exit(code=1) from exc
|
|
68
|
+
|
|
69
|
+
client = get_client(config.server.url)
|
|
70
|
+
try:
|
|
71
|
+
sheet = read_grade_sheet(path, config, client=client)
|
|
72
|
+
except GradesError as exc:
|
|
73
|
+
for problem in exc.problems:
|
|
74
|
+
typer.echo(f"error: {problem}", err=True)
|
|
75
|
+
raise typer.Exit(code=1) from exc
|
|
76
|
+
except httpx.HTTPStatusError as exc:
|
|
77
|
+
typer.echo(f"error: could not read the course's grades: {exc}", err=True)
|
|
78
|
+
raise typer.Exit(code=1) from exc
|
|
79
|
+
|
|
80
|
+
for warning in unmatched_warnings(sheet.roster):
|
|
81
|
+
typer.echo(f"warning {warning}", err=True)
|
|
82
|
+
|
|
83
|
+
if not sheet.columns:
|
|
84
|
+
typer.echo("codehood.toml declares no grade column")
|
|
85
|
+
return
|
|
86
|
+
Console().print(render_table(sheet))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def read_grade_sheet(
|
|
90
|
+
path: Path, config: RepoConfig, *, client: httpx.Client
|
|
91
|
+
) -> GradeSheet:
|
|
92
|
+
"""
|
|
93
|
+
Compute the grade columns of the repository at `path`.
|
|
94
|
+
|
|
95
|
+
Everything local is read and checked before the one network call, so a
|
|
96
|
+
broken `grades.csv` or `grades.py` costs no request.
|
|
97
|
+
|
|
98
|
+
Raises:
|
|
99
|
+
GradesError: The columns cannot be computed. See `compute_columns`,
|
|
100
|
+
`parse_grades_csv` and `load_grade_function`.
|
|
101
|
+
httpx.HTTPStatusError: The server refused to list the students.
|
|
102
|
+
"""
|
|
103
|
+
specs = tuple(
|
|
104
|
+
ColumnSpec(slug=column.slug, title=column.title, kind=column.kind)
|
|
105
|
+
for column in config.grades.column
|
|
106
|
+
)
|
|
107
|
+
if not specs:
|
|
108
|
+
return GradeSheet()
|
|
109
|
+
|
|
110
|
+
csv_path = path / CSV_FILE
|
|
111
|
+
script_path = path / SCRIPT_FILE
|
|
112
|
+
sheet = (
|
|
113
|
+
parse_grades_csv(csv_path.read_text(encoding="utf-8"))
|
|
114
|
+
if csv_path.exists()
|
|
115
|
+
else None
|
|
116
|
+
)
|
|
117
|
+
grade = load_grade_function(script_path) if script_path.exists() else None
|
|
118
|
+
if sheet is None and grade is None:
|
|
119
|
+
raise GradesError(
|
|
120
|
+
[
|
|
121
|
+
"codehood.toml declares grade columns, but the repository has "
|
|
122
|
+
f"neither {SCRIPT_FILE} nor {CSV_FILE}"
|
|
123
|
+
]
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
students = fetch_students(
|
|
127
|
+
config.course.discipline,
|
|
128
|
+
f"{config.course.instructor}_{config.course.edition}",
|
|
129
|
+
client,
|
|
130
|
+
)
|
|
131
|
+
roster = build_roster(students, sheet)
|
|
132
|
+
return GradeSheet(columns=compute_columns(specs, roster, grade), roster=roster)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def unmatched_warnings(roster: Roster) -> list[str]:
|
|
136
|
+
"""
|
|
137
|
+
One line per `grades.csv` row that belongs to no enrolled student.
|
|
138
|
+
"""
|
|
139
|
+
return [
|
|
140
|
+
f"{CSV_FILE}: no enrolled student with {roster.id_field} {student_id}, "
|
|
141
|
+
"row skipped"
|
|
142
|
+
for student_id in roster.unmatched
|
|
143
|
+
]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
#
|
|
147
|
+
# Utilities
|
|
148
|
+
#
|
|
149
|
+
def render_table(sheet: GradeSheet) -> Table:
|
|
150
|
+
"""
|
|
151
|
+
The computed columns as a table: one row per student, one column per
|
|
152
|
+
grade column, an empty cell where a student has no value.
|
|
153
|
+
"""
|
|
154
|
+
table = Table()
|
|
155
|
+
table.add_column("Student")
|
|
156
|
+
for column in sheet.columns:
|
|
157
|
+
table.add_column(
|
|
158
|
+
column.title, justify="right" if column.kind == "number" else "left"
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
values = [dict(column.values) for column in sheet.columns]
|
|
162
|
+
for student in sheet.roster.students:
|
|
163
|
+
label = student.username
|
|
164
|
+
if student.status == "dropped":
|
|
165
|
+
label += " (dropped)"
|
|
166
|
+
table.add_row(
|
|
167
|
+
label,
|
|
168
|
+
*(
|
|
169
|
+
format_value(by_username.get(student.username))
|
|
170
|
+
for by_username in values
|
|
171
|
+
),
|
|
172
|
+
)
|
|
173
|
+
return table
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def format_value(value: float | str | None) -> str:
|
|
177
|
+
"""
|
|
178
|
+
One cell of the table: a number without a trailing `.0`, a label as it
|
|
179
|
+
is, nothing for no value.
|
|
180
|
+
"""
|
|
181
|
+
if value is None:
|
|
182
|
+
return ""
|
|
183
|
+
if isinstance(value, float):
|
|
184
|
+
return f"{value:g}"
|
|
185
|
+
return value
|