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,177 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Field validators and their `Annotated` types for `codehood.toml`'s models.
|
|
3
|
+
|
|
4
|
+
The patterns and the reserved-slug set are copied from the server's
|
|
5
|
+
published rules for a valid course URL segment -- see `repo.py`'s
|
|
6
|
+
docstring and `dev/specs/to-do/init.md`, "Slugs are validated locally,
|
|
7
|
+
existence is not".
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from functools import wraps
|
|
15
|
+
from typing import Annotated, Any
|
|
16
|
+
from urllib.parse import urlsplit
|
|
17
|
+
|
|
18
|
+
from pydantic import AfterValidator
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
#: Types
|
|
22
|
+
"DisciplineSlug",
|
|
23
|
+
"InstructorUsername",
|
|
24
|
+
"EditionSlug",
|
|
25
|
+
"GradeColumnSlug",
|
|
26
|
+
"ServerUrl",
|
|
27
|
+
#: Validator composition
|
|
28
|
+
"string_validator",
|
|
29
|
+
#: Validators
|
|
30
|
+
"validate_discipline",
|
|
31
|
+
"validate_instructor",
|
|
32
|
+
"validate_edition",
|
|
33
|
+
"validate_slug",
|
|
34
|
+
"url_validator",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
type Validator[T] = Callable[[Any], T]
|
|
38
|
+
|
|
39
|
+
# Patterns copied from `codehood-server/src/utils/course-url.ts`
|
|
40
|
+
# (`DISCIPLINE_SLUG_RE`, `USERNAME_RE`, `EDITION_RE`), the server's
|
|
41
|
+
# published rules for what makes a valid course URL segment. `init` checks
|
|
42
|
+
# these locally so a typo like `2026_1` or `CS101` is a fast local error;
|
|
43
|
+
# whether the slug actually names something is left to the server.
|
|
44
|
+
DISCIPLINE_RE = re.compile(r"^[a-z][a-z0-9-]{1,30}[a-z0-9]$")
|
|
45
|
+
INSTRUCTOR_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,30}$")
|
|
46
|
+
EDITION_RE = re.compile(r"^[0-9]{4}(-([1-9][0-9]*|0))?$")
|
|
47
|
+
|
|
48
|
+
# The server's rule for a flat slug (`slug` in `src/core/schemas/base.ts`):
|
|
49
|
+
# exactly one URL segment.
|
|
50
|
+
SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
|
|
51
|
+
|
|
52
|
+
# Hosts a server URL may reach over plain `http://`.
|
|
53
|
+
LOCAL_HOSTS: frozenset[str] = frozenset({"localhost", "127.0.0.1", "::1"})
|
|
54
|
+
|
|
55
|
+
# Copied from `codehood-server/src/utils/course-url.ts`'s `RESERVED_SLUGS`.
|
|
56
|
+
# Top-level names a discipline slug must not equal, because the root
|
|
57
|
+
# namespace is shared with every system route. This copy will drift from
|
|
58
|
+
# the server's list over time; that is accepted (see the spec) and the fix
|
|
59
|
+
# when it does is a paste from that file.
|
|
60
|
+
RESERVED_SLUGS: frozenset[str] = frozenset(
|
|
61
|
+
{
|
|
62
|
+
"403",
|
|
63
|
+
"404",
|
|
64
|
+
"500",
|
|
65
|
+
"_actions",
|
|
66
|
+
"_astro",
|
|
67
|
+
"_image",
|
|
68
|
+
"admin",
|
|
69
|
+
"api",
|
|
70
|
+
"calendar",
|
|
71
|
+
"courses",
|
|
72
|
+
"design",
|
|
73
|
+
"favicon",
|
|
74
|
+
"files",
|
|
75
|
+
"getting-started",
|
|
76
|
+
"img",
|
|
77
|
+
"invite",
|
|
78
|
+
"login",
|
|
79
|
+
"logo",
|
|
80
|
+
"manifest",
|
|
81
|
+
"profile",
|
|
82
|
+
"sw",
|
|
83
|
+
"about",
|
|
84
|
+
"docs",
|
|
85
|
+
"help",
|
|
86
|
+
"logout",
|
|
87
|
+
"me",
|
|
88
|
+
"new",
|
|
89
|
+
"search",
|
|
90
|
+
"settings",
|
|
91
|
+
"signup",
|
|
92
|
+
"static",
|
|
93
|
+
"users",
|
|
94
|
+
}
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
#
|
|
99
|
+
# Validator composition
|
|
100
|
+
#
|
|
101
|
+
def string_validator(fn: Callable[[str], str], /) -> Validator[str]:
|
|
102
|
+
"""
|
|
103
|
+
Wrap a string validator to accept any value and convert it to a string.
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
@wraps(fn)
|
|
107
|
+
def wrapper(value: Any) -> str:
|
|
108
|
+
return fn(str(value))
|
|
109
|
+
|
|
110
|
+
return wrapper
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
#
|
|
114
|
+
# Validator functions
|
|
115
|
+
#
|
|
116
|
+
@string_validator
|
|
117
|
+
def validate_discipline(value: str) -> str:
|
|
118
|
+
if not DISCIPLINE_RE.fullmatch(value):
|
|
119
|
+
raise ValueError(f"discipline {value!r} must match {DISCIPLINE_RE.pattern!r}")
|
|
120
|
+
if value in RESERVED_SLUGS:
|
|
121
|
+
raise ValueError(f"discipline {value!r} is a reserved name")
|
|
122
|
+
return value
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@string_validator
|
|
126
|
+
def validate_instructor(value: str) -> str:
|
|
127
|
+
if not INSTRUCTOR_RE.fullmatch(value):
|
|
128
|
+
raise ValueError(f"instructor {value!r} must match {INSTRUCTOR_RE.pattern!r}")
|
|
129
|
+
return value
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@string_validator
|
|
133
|
+
def validate_edition(value: str) -> str:
|
|
134
|
+
if not EDITION_RE.fullmatch(value):
|
|
135
|
+
raise ValueError(f"edition {value!r} must match {EDITION_RE.pattern!r}")
|
|
136
|
+
return value
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@string_validator
|
|
140
|
+
def validate_slug(value: str) -> str:
|
|
141
|
+
if not SLUG_RE.fullmatch(value):
|
|
142
|
+
raise ValueError(f"slug {value!r} must match {SLUG_RE.pattern!r}")
|
|
143
|
+
return value
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@string_validator
|
|
147
|
+
def url_validator(value: str) -> str:
|
|
148
|
+
"""
|
|
149
|
+
Normalize a server URL, defaulting to `https://` and dropping a trailing slash.
|
|
150
|
+
|
|
151
|
+
Plain `http://` is only accepted for local servers, since the CLI sends
|
|
152
|
+
passwords and API keys to it.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
ValueError: If the URL has no host, another scheme, or `http://` on a
|
|
156
|
+
remote host.
|
|
157
|
+
"""
|
|
158
|
+
if "://" not in value:
|
|
159
|
+
value = f"https://{value}"
|
|
160
|
+
parts = urlsplit(value)
|
|
161
|
+
if parts.scheme not in ("http", "https") or not parts.hostname:
|
|
162
|
+
raise ValueError(f"server {value!r} must be a URL like 'https://codehood.dev'")
|
|
163
|
+
if parts.scheme == "http" and parts.hostname not in LOCAL_HOSTS:
|
|
164
|
+
raise ValueError(
|
|
165
|
+
f"server {value!r} must use https:// (http is only for local servers)"
|
|
166
|
+
)
|
|
167
|
+
return value.removesuffix("/")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
#
|
|
171
|
+
# Annotated type aliases
|
|
172
|
+
#
|
|
173
|
+
DisciplineSlug = Annotated[str, AfterValidator(validate_discipline)]
|
|
174
|
+
InstructorUsername = Annotated[str, AfterValidator(validate_instructor)]
|
|
175
|
+
EditionSlug = Annotated[str, AfterValidator(validate_edition)]
|
|
176
|
+
GradeColumnSlug = Annotated[str, AfterValidator(validate_slug)]
|
|
177
|
+
ServerUrl = Annotated[str, AfterValidator(url_validator)]
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`codehood push`: sync a course repository's course row, `calendar.md`,
|
|
3
|
+
`resources/` and grade columns to the server. See `dev/specs/to-do/push.md` and
|
|
4
|
+
`docs/design/mapping-local-filesystem.md`.
|
|
5
|
+
|
|
6
|
+
Functional core, imperative shell: `plan.plan_sync` is a pure function
|
|
7
|
+
that diffs a `LocalState`, the base and a `ServerState` into a plan
|
|
8
|
+
(`plan.Plan`); `run.run_plan` is the only thing here that touches HTTP.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from .calendar import (
|
|
14
|
+
Allocation,
|
|
15
|
+
Calendar,
|
|
16
|
+
Duration,
|
|
17
|
+
Event,
|
|
18
|
+
EventKey,
|
|
19
|
+
EventKind,
|
|
20
|
+
Holiday,
|
|
21
|
+
Section,
|
|
22
|
+
TimeOfDay,
|
|
23
|
+
TimeSlot,
|
|
24
|
+
Weekday,
|
|
25
|
+
allocate,
|
|
26
|
+
parse_calendar,
|
|
27
|
+
)
|
|
28
|
+
from .errors import (
|
|
29
|
+
CalendarError,
|
|
30
|
+
QuestionParseError,
|
|
31
|
+
QuestionSourceError,
|
|
32
|
+
RepositoryError,
|
|
33
|
+
ResourceLinkError,
|
|
34
|
+
SlugCollisionError,
|
|
35
|
+
)
|
|
36
|
+
from .grades import (
|
|
37
|
+
ColumnSpec,
|
|
38
|
+
GradeColumn,
|
|
39
|
+
GradesCsv,
|
|
40
|
+
GradesError,
|
|
41
|
+
Roster,
|
|
42
|
+
ServerStudent,
|
|
43
|
+
build_roster,
|
|
44
|
+
compute_columns,
|
|
45
|
+
parse_grades_csv,
|
|
46
|
+
)
|
|
47
|
+
from .hook import load_grade_function
|
|
48
|
+
from .links import (
|
|
49
|
+
RepositoryLink,
|
|
50
|
+
attach_repositories,
|
|
51
|
+
attach_resources,
|
|
52
|
+
extract_repository_links,
|
|
53
|
+
extract_resource_links,
|
|
54
|
+
rewrite_body_links,
|
|
55
|
+
rewrite_event_links,
|
|
56
|
+
rewrite_repository_links,
|
|
57
|
+
rewrite_resource_links,
|
|
58
|
+
)
|
|
59
|
+
from .plan import (
|
|
60
|
+
DeleteCalendarEvent,
|
|
61
|
+
DeleteGradeColumn,
|
|
62
|
+
DeleteQuestion,
|
|
63
|
+
DeleteRepository,
|
|
64
|
+
DeleteResource,
|
|
65
|
+
DeleteTimeSlot,
|
|
66
|
+
KeptDraftPublished,
|
|
67
|
+
KeptForRollCall,
|
|
68
|
+
KeptPinnedSlot,
|
|
69
|
+
KeptRepository,
|
|
70
|
+
LocalState,
|
|
71
|
+
Notice,
|
|
72
|
+
Plan,
|
|
73
|
+
Rejected,
|
|
74
|
+
ServerEvent,
|
|
75
|
+
ServerQuestion,
|
|
76
|
+
ServerState,
|
|
77
|
+
UpsertCalendarEvent,
|
|
78
|
+
UpsertCourse,
|
|
79
|
+
UpsertGradeColumn,
|
|
80
|
+
UpsertQuestion,
|
|
81
|
+
UpsertRepository,
|
|
82
|
+
UpsertResource,
|
|
83
|
+
UpsertTimeSlot,
|
|
84
|
+
Write,
|
|
85
|
+
plan_repositories,
|
|
86
|
+
plan_sync,
|
|
87
|
+
)
|
|
88
|
+
from .question import (
|
|
89
|
+
AnyQuestion,
|
|
90
|
+
InvalidQuestion,
|
|
91
|
+
QuestionFile,
|
|
92
|
+
question_version,
|
|
93
|
+
scan_questions,
|
|
94
|
+
)
|
|
95
|
+
from .repository import (
|
|
96
|
+
MAX_FILE_BYTES,
|
|
97
|
+
RepositoryEntry,
|
|
98
|
+
RepositoryTree,
|
|
99
|
+
batch_entries,
|
|
100
|
+
blob_sha,
|
|
101
|
+
scan_repositories,
|
|
102
|
+
tree_sha,
|
|
103
|
+
)
|
|
104
|
+
from .resource import (
|
|
105
|
+
CodeData,
|
|
106
|
+
FileData,
|
|
107
|
+
LinkData,
|
|
108
|
+
MdData,
|
|
109
|
+
ResourceData,
|
|
110
|
+
ResourceFile,
|
|
111
|
+
content_ref,
|
|
112
|
+
scan_resources,
|
|
113
|
+
slugify,
|
|
114
|
+
)
|
|
115
|
+
from .run import (
|
|
116
|
+
HttpRepositoryApi,
|
|
117
|
+
OpResult,
|
|
118
|
+
RepositoryApi,
|
|
119
|
+
fetch_server_state,
|
|
120
|
+
fetch_students,
|
|
121
|
+
run_plan,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
__all__ = [
|
|
125
|
+
#: Repositories
|
|
126
|
+
"MAX_FILE_BYTES",
|
|
127
|
+
"Allocation",
|
|
128
|
+
#: Questions
|
|
129
|
+
"AnyQuestion",
|
|
130
|
+
#: Calendar
|
|
131
|
+
"Calendar",
|
|
132
|
+
"CalendarError",
|
|
133
|
+
"CodeData",
|
|
134
|
+
#: Grade columns
|
|
135
|
+
"ColumnSpec",
|
|
136
|
+
"DeleteCalendarEvent",
|
|
137
|
+
"DeleteGradeColumn",
|
|
138
|
+
"DeleteQuestion",
|
|
139
|
+
"DeleteRepository",
|
|
140
|
+
"DeleteResource",
|
|
141
|
+
"DeleteTimeSlot",
|
|
142
|
+
"Duration",
|
|
143
|
+
"Event",
|
|
144
|
+
"EventKey",
|
|
145
|
+
"EventKind",
|
|
146
|
+
"FileData",
|
|
147
|
+
"GradeColumn",
|
|
148
|
+
"GradesCsv",
|
|
149
|
+
"GradesError",
|
|
150
|
+
"Holiday",
|
|
151
|
+
"HttpRepositoryApi",
|
|
152
|
+
"InvalidQuestion",
|
|
153
|
+
"KeptDraftPublished",
|
|
154
|
+
"KeptForRollCall",
|
|
155
|
+
"KeptPinnedSlot",
|
|
156
|
+
"KeptRepository",
|
|
157
|
+
"LinkData",
|
|
158
|
+
#: Plan
|
|
159
|
+
"LocalState",
|
|
160
|
+
"MdData",
|
|
161
|
+
"Notice",
|
|
162
|
+
#: Shell
|
|
163
|
+
"OpResult",
|
|
164
|
+
"Plan",
|
|
165
|
+
"QuestionFile",
|
|
166
|
+
"QuestionParseError",
|
|
167
|
+
"QuestionSourceError",
|
|
168
|
+
"Rejected",
|
|
169
|
+
"RepositoryApi",
|
|
170
|
+
"RepositoryEntry",
|
|
171
|
+
"RepositoryError",
|
|
172
|
+
"RepositoryLink",
|
|
173
|
+
"RepositoryTree",
|
|
174
|
+
"ResourceData",
|
|
175
|
+
#: Resources
|
|
176
|
+
"ResourceFile",
|
|
177
|
+
"ResourceLinkError",
|
|
178
|
+
"Roster",
|
|
179
|
+
"Section",
|
|
180
|
+
"ServerEvent",
|
|
181
|
+
"ServerQuestion",
|
|
182
|
+
"ServerState",
|
|
183
|
+
"ServerStudent",
|
|
184
|
+
#: Errors
|
|
185
|
+
"SlugCollisionError",
|
|
186
|
+
"TimeOfDay",
|
|
187
|
+
"TimeSlot",
|
|
188
|
+
"UpsertCalendarEvent",
|
|
189
|
+
"UpsertCourse",
|
|
190
|
+
"UpsertGradeColumn",
|
|
191
|
+
"UpsertQuestion",
|
|
192
|
+
"UpsertRepository",
|
|
193
|
+
"UpsertResource",
|
|
194
|
+
"UpsertTimeSlot",
|
|
195
|
+
"Weekday",
|
|
196
|
+
"Write",
|
|
197
|
+
"allocate",
|
|
198
|
+
"attach_repositories",
|
|
199
|
+
"attach_resources",
|
|
200
|
+
"batch_entries",
|
|
201
|
+
"blob_sha",
|
|
202
|
+
"build_roster",
|
|
203
|
+
"compute_columns",
|
|
204
|
+
"content_ref",
|
|
205
|
+
"extract_repository_links",
|
|
206
|
+
"extract_resource_links",
|
|
207
|
+
"fetch_server_state",
|
|
208
|
+
"fetch_students",
|
|
209
|
+
"load_grade_function",
|
|
210
|
+
"parse_calendar",
|
|
211
|
+
"parse_grades_csv",
|
|
212
|
+
"plan_repositories",
|
|
213
|
+
"plan_sync",
|
|
214
|
+
"question_version",
|
|
215
|
+
"rewrite_body_links",
|
|
216
|
+
"rewrite_event_links",
|
|
217
|
+
"rewrite_repository_links",
|
|
218
|
+
"rewrite_resource_links",
|
|
219
|
+
"run_plan",
|
|
220
|
+
"scan_questions",
|
|
221
|
+
"scan_repositories",
|
|
222
|
+
"scan_resources",
|
|
223
|
+
"slugify",
|
|
224
|
+
"tree_sha",
|
|
225
|
+
]
|
codehood/push/base.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The base: what the last successful sync left on the server.
|
|
3
|
+
|
|
4
|
+
For each synced resource the base keeps the JSON payload the push sent, plus
|
|
5
|
+
the `rev` and `updatedAt` the server reported. Comparing local, base and
|
|
6
|
+
server tells who changed what since then. It lives in `.local/codehood/base/`,
|
|
7
|
+
one JSON file per collection.
|
|
8
|
+
|
|
9
|
+
`encode_collection` and `decode_collection` are the pure core; `load_base` and
|
|
10
|
+
`save_base` are the effects around them. Writes are atomic (temporary file in
|
|
11
|
+
the same directory, then `os.replace`), and a file that is missing, unreadable
|
|
12
|
+
or in an unknown format counts as an absent base for that collection, reported
|
|
13
|
+
through `BaseState.warnings` instead of an exception.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from ..repo import MACHINE_DIR, ensure_machine_dir
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"COLLECTIONS",
|
|
27
|
+
"FORMAT_VERSION",
|
|
28
|
+
"BaseEntry",
|
|
29
|
+
"BaseState",
|
|
30
|
+
"JsonValue",
|
|
31
|
+
"base_dir",
|
|
32
|
+
"decode_collection",
|
|
33
|
+
"encode_collection",
|
|
34
|
+
"load_base",
|
|
35
|
+
"save_base",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
type JsonValue = (
|
|
39
|
+
dict[str, JsonValue] | list[JsonValue] | str | int | float | bool | None
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
#: Version of the file format. A file with another version is an absent base.
|
|
43
|
+
FORMAT_VERSION = 1
|
|
44
|
+
|
|
45
|
+
#: Names of the `BaseState` collections, and of their files (`<name>.json`).
|
|
46
|
+
COLLECTIONS = (
|
|
47
|
+
"course",
|
|
48
|
+
"resources",
|
|
49
|
+
"questions",
|
|
50
|
+
"exams",
|
|
51
|
+
"time_slots",
|
|
52
|
+
"calendar_events",
|
|
53
|
+
"grade_columns",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
BASE_DIR = "base"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class BaseEntry:
|
|
61
|
+
"""
|
|
62
|
+
One resource as of the last successful sync.
|
|
63
|
+
|
|
64
|
+
`payload` is the JSON body that was sent, in wire form. `updated_at` is the
|
|
65
|
+
server's ISO timestamp, kept as text.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
payload: dict[str, JsonValue]
|
|
69
|
+
rev: str | None = None
|
|
70
|
+
updated_at: str | None = None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class BaseState:
|
|
75
|
+
"""
|
|
76
|
+
The base of every synced resource type, keyed by natural key.
|
|
77
|
+
|
|
78
|
+
An empty `BaseState` is an absent base. Calendar events are keyed by a
|
|
79
|
+
string the caller builds from the week and the time slot. `warnings` is
|
|
80
|
+
filled by `load_base` and ignored by comparison and by `save_base`.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
course: dict[str, BaseEntry] = field(default_factory=dict)
|
|
84
|
+
resources: dict[str, BaseEntry] = field(default_factory=dict)
|
|
85
|
+
questions: dict[str, BaseEntry] = field(default_factory=dict)
|
|
86
|
+
exams: dict[str, BaseEntry] = field(default_factory=dict)
|
|
87
|
+
time_slots: dict[str, BaseEntry] = field(default_factory=dict)
|
|
88
|
+
calendar_events: dict[str, BaseEntry] = field(default_factory=dict)
|
|
89
|
+
grade_columns: dict[str, BaseEntry] = field(default_factory=dict)
|
|
90
|
+
warnings: tuple[str, ...] = field(default=(), compare=False)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def base_dir(root: Path) -> Path:
|
|
94
|
+
"""
|
|
95
|
+
The directory that holds the base files of the repository at `root`.
|
|
96
|
+
"""
|
|
97
|
+
return root / MACHINE_DIR / BASE_DIR
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def encode_collection(entries: dict[str, BaseEntry]) -> str:
|
|
101
|
+
"""
|
|
102
|
+
Serialize one collection to the text of its file.
|
|
103
|
+
"""
|
|
104
|
+
document = {
|
|
105
|
+
"version": FORMAT_VERSION,
|
|
106
|
+
"entries": {
|
|
107
|
+
key: {
|
|
108
|
+
"payload": entry.payload,
|
|
109
|
+
"rev": entry.rev,
|
|
110
|
+
"updatedAt": entry.updated_at,
|
|
111
|
+
}
|
|
112
|
+
for key, entry in entries.items()
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
return json.dumps(document, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def decode_collection(text: str, name: str) -> tuple[dict[str, BaseEntry], str | None]:
|
|
119
|
+
"""
|
|
120
|
+
Parse the text of a collection file.
|
|
121
|
+
|
|
122
|
+
Returns the entries and a warning. Text that is not valid, or has an
|
|
123
|
+
unexpected shape or version, gives no entries and a warning naming `name`.
|
|
124
|
+
"""
|
|
125
|
+
try:
|
|
126
|
+
document = json.loads(text)
|
|
127
|
+
if not isinstance(document, dict):
|
|
128
|
+
raise TypeError("not an object")
|
|
129
|
+
version = document.get("version")
|
|
130
|
+
if version != FORMAT_VERSION:
|
|
131
|
+
return {}, f"base '{name}': unknown format version {version!r}, ignored"
|
|
132
|
+
raw = document.get("entries")
|
|
133
|
+
if not isinstance(raw, dict):
|
|
134
|
+
raise TypeError("'entries' is not an object")
|
|
135
|
+
return {key: _decode_entry(value) for key, value in raw.items()}, None
|
|
136
|
+
except (ValueError, TypeError) as exc:
|
|
137
|
+
return {}, f"base '{name}': unreadable ({exc}), ignored"
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def load_base(root: Path) -> BaseState:
|
|
141
|
+
"""
|
|
142
|
+
Read the base of the repository at `root`.
|
|
143
|
+
|
|
144
|
+
Never raises: a missing file is an empty collection without a warning, any
|
|
145
|
+
other problem is an empty collection with one.
|
|
146
|
+
"""
|
|
147
|
+
collections: dict[str, dict[str, BaseEntry]] = {}
|
|
148
|
+
warnings: list[str] = []
|
|
149
|
+
for name in COLLECTIONS:
|
|
150
|
+
path = base_dir(root) / f"{name}.json"
|
|
151
|
+
try:
|
|
152
|
+
text = path.read_text(encoding="utf-8")
|
|
153
|
+
except FileNotFoundError:
|
|
154
|
+
collections[name] = {}
|
|
155
|
+
continue
|
|
156
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
157
|
+
collections[name] = {}
|
|
158
|
+
warnings.append(f"base '{name}': unreadable ({exc}), ignored")
|
|
159
|
+
continue
|
|
160
|
+
collections[name], warning = decode_collection(text, name)
|
|
161
|
+
if warning is not None:
|
|
162
|
+
warnings.append(warning)
|
|
163
|
+
return BaseState(**collections, warnings=tuple(warnings))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def save_base(root: Path, state: BaseState) -> None:
|
|
167
|
+
"""
|
|
168
|
+
Write every collection of `state`, each file atomically.
|
|
169
|
+
|
|
170
|
+
A crash leaves each file either as it was or fully written, never partial.
|
|
171
|
+
The `.gitignore` that keeps `.local/codehood/` out of git is created first
|
|
172
|
+
when missing.
|
|
173
|
+
"""
|
|
174
|
+
ensure_machine_dir(root)
|
|
175
|
+
directory = base_dir(root)
|
|
176
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
177
|
+
for name in COLLECTIONS:
|
|
178
|
+
write_atomic(
|
|
179
|
+
directory / f"{name}.json", encode_collection(getattr(state, name))
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
#
|
|
184
|
+
# Utilities
|
|
185
|
+
#
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def write_atomic(path: Path, text: str) -> None:
|
|
189
|
+
"""
|
|
190
|
+
Write `text` to `path` through a temporary file in the same directory.
|
|
191
|
+
"""
|
|
192
|
+
tmp = path.with_name(path.name + ".tmp")
|
|
193
|
+
try:
|
|
194
|
+
with open(tmp, "w", encoding="utf-8") as handle:
|
|
195
|
+
handle.write(text)
|
|
196
|
+
handle.flush()
|
|
197
|
+
os.fsync(handle.fileno())
|
|
198
|
+
os.replace(tmp, path)
|
|
199
|
+
except Exception:
|
|
200
|
+
tmp.unlink(missing_ok=True)
|
|
201
|
+
raise
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _decode_entry(value: object) -> BaseEntry:
|
|
205
|
+
if not isinstance(value, dict):
|
|
206
|
+
raise TypeError("entry is not an object")
|
|
207
|
+
payload = value.get("payload")
|
|
208
|
+
rev = value.get("rev")
|
|
209
|
+
updated_at = value.get("updatedAt")
|
|
210
|
+
if not isinstance(payload, dict):
|
|
211
|
+
raise TypeError("entry payload is not an object")
|
|
212
|
+
if rev is not None and not isinstance(rev, str):
|
|
213
|
+
raise TypeError("entry rev is not text")
|
|
214
|
+
if updated_at is not None and not isinstance(updated_at, str):
|
|
215
|
+
raise TypeError("entry updatedAt is not text")
|
|
216
|
+
return BaseEntry(payload=payload, rev=rev, updated_at=updated_at)
|