codehood-cli 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. codehood/__init__.py +0 -0
  2. codehood/__main__.py +4 -0
  3. codehood/actions/__init__.py +0 -0
  4. codehood/actions/base.py +119 -0
  5. codehood/actions/resources.py +30 -0
  6. codehood/api/__init__.py +0 -0
  7. codehood/api/base.py +256 -0
  8. codehood/api/generate.py +1370 -0
  9. codehood/api/generated.py +3818 -0
  10. codehood/api/openapi.py +134 -0
  11. codehood/api/pages.py +53 -0
  12. codehood/cli/__init__.py +64 -0
  13. codehood/cli/api.py +422 -0
  14. codehood/cli/attendance.py +136 -0
  15. codehood/cli/auth.py +106 -0
  16. codehood/cli/base.py +42 -0
  17. codehood/cli/chill.py +52 -0
  18. codehood/cli/exam.py +107 -0
  19. codehood/cli/grades.py +185 -0
  20. codehood/cli/init.py +161 -0
  21. codehood/cli/push.py +609 -0
  22. codehood/cli/show.py +77 -0
  23. codehood/cli/uitils.py +26 -0
  24. codehood/functional.py +40 -0
  25. codehood/globs.py +71 -0
  26. codehood/grades.py +74 -0
  27. codehood/hypothesis.py +274 -0
  28. codehood/models/__init__.py +0 -0
  29. codehood/models/base.py +15 -0
  30. codehood/models/repo.py +187 -0
  31. codehood/models/validators.py +177 -0
  32. codehood/push/__init__.py +225 -0
  33. codehood/push/base.py +216 -0
  34. codehood/push/calendar.py +664 -0
  35. codehood/push/errors.py +136 -0
  36. codehood/push/exam.py +636 -0
  37. codehood/push/exclude.py +60 -0
  38. codehood/push/grades.py +455 -0
  39. codehood/push/hook.py +48 -0
  40. codehood/push/links.py +614 -0
  41. codehood/push/ours.py +78 -0
  42. codehood/push/plan.py +1981 -0
  43. codehood/push/project.py +272 -0
  44. codehood/push/question.py +338 -0
  45. codehood/push/report.py +244 -0
  46. codehood/push/repository.py +326 -0
  47. codehood/push/resource.py +576 -0
  48. codehood/push/run.py +1275 -0
  49. codehood/push/unconsumed.py +208 -0
  50. codehood/push/wire.py +222 -0
  51. codehood/py.typed +0 -0
  52. codehood/repo/__init__.py +62 -0
  53. codehood/repo/_config.py +28 -0
  54. codehood/repo/_layout.py +132 -0
  55. codehood/repo/_scaffold.py +244 -0
  56. codehood/repo/diff.py +71 -0
  57. codehood/repo/file_tracker.py +124 -0
  58. codehood/theme.py +101 -0
  59. codehood/widgets/__init__.py +0 -0
  60. codehood/widgets/mascot.py +76 -0
  61. codehood/widgets/questions/__init__.py +65 -0
  62. codehood/widgets/questions/base.py +119 -0
  63. codehood/widgets/questions/controls.py +194 -0
  64. codehood/widgets/questions/fill_in.py +81 -0
  65. codehood/widgets/questions/responses.py +137 -0
  66. codehood/widgets/questions/simple.py +117 -0
  67. codehood_cli-0.5.0.dist-info/METADATA +294 -0
  68. codehood_cli-0.5.0.dist-info/RECORD +71 -0
  69. codehood_cli-0.5.0.dist-info/WHEEL +4 -0
  70. codehood_cli-0.5.0.dist-info/entry_points.txt +4 -0
  71. codehood_cli-0.5.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,664 @@
1
+ """
2
+ The pure core that turns `calendar.md` into TimeSlots and CalendarEvents.
3
+
4
+ Two steps, both side-effect free: `parse_calendar` reads the file into a
5
+ `Calendar` and nothing more, and `allocate` walks the course's date range
6
+ handing each h2 section a date. Neither knows the network, the clock, or
7
+ the server's idea of what it holds -- see `plan.py` for that half, and
8
+ `docs/design/mapping-local-filesystem.md`, "Calendar", for the mapping
9
+ this implements.
10
+
11
+ Every case the mapping calls a warning comes back in
12
+ `Allocation.warnings` rather than going to `warnings.warn`, so the whole
13
+ allocation is one comparable value.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import json
20
+ import re
21
+ from collections.abc import Iterator
22
+ from dataclasses import dataclass
23
+ from datetime import date, datetime, timedelta
24
+ from itertools import groupby
25
+ from typing import Literal
26
+
27
+ import yaml
28
+
29
+ from .errors import CalendarError
30
+
31
+ __all__ = [
32
+ "Allocation",
33
+ "Calendar",
34
+ "Duration",
35
+ "Event",
36
+ "EventKey",
37
+ "EventKind",
38
+ "Holiday",
39
+ "Section",
40
+ "TimeOfDay",
41
+ "TimeSlot",
42
+ "Weekday",
43
+ "allocate",
44
+ "parse_calendar",
45
+ ]
46
+
47
+ #: The weekday names the server's enum uses, in its own order.
48
+ type Weekday = Literal[
49
+ "SUNDAY",
50
+ "MONDAY",
51
+ "TUESDAY",
52
+ "WEDNESDAY",
53
+ "THURSDAY",
54
+ "FRIDAY",
55
+ "SATURDAY",
56
+ ]
57
+
58
+ #: The kinds a push writes. `CANCELLED` comes from a struck-through h2
59
+ #: (`## ~~Title~~`) or from the web, and a push never undoes it -- see the
60
+ #: mapping's "Calendar events".
61
+ type EventKind = Literal["REGULAR", "HOLIDAY", "CANCELLED"]
62
+
63
+ #: Wraps an h2 title to mark the lesson cancelled.
64
+ CANCELLED_MARK = "~~"
65
+
66
+ #: Weekday spellings a `days:`/`## Title` entry may use, keyed
67
+ #: case-insensitively, both the three-letter abbreviation and the full name.
68
+ _WEEKDAY_ALIASES: dict[str, Weekday] = {
69
+ "sun": "SUNDAY",
70
+ "sunday": "SUNDAY",
71
+ "mon": "MONDAY",
72
+ "monday": "MONDAY",
73
+ "tue": "TUESDAY",
74
+ "tuesday": "TUESDAY",
75
+ "wed": "WEDNESDAY",
76
+ "wednesday": "WEDNESDAY",
77
+ "thu": "THURSDAY",
78
+ "thursday": "THURSDAY",
79
+ "fri": "FRIDAY",
80
+ "friday": "FRIDAY",
81
+ "sat": "SATURDAY",
82
+ "saturday": "SATURDAY",
83
+ }
84
+
85
+ #: The three-letter slug a `TimeSlot` uses before any collision suffix.
86
+ _WEEKDAY_SLUG: dict[Weekday, str] = {
87
+ "SUNDAY": "sun",
88
+ "MONDAY": "mon",
89
+ "TUESDAY": "tue",
90
+ "WEDNESDAY": "wed",
91
+ "THURSDAY": "thu",
92
+ "FRIDAY": "fri",
93
+ "SATURDAY": "sat",
94
+ }
95
+
96
+ #: ISO weekday number (Monday=1 .. Sunday=7), the order `days:` sorts by.
97
+ _WEEKDAY_ISO: dict[Weekday, int] = {
98
+ "MONDAY": 1,
99
+ "TUESDAY": 2,
100
+ "WEDNESDAY": 3,
101
+ "THURSDAY": 4,
102
+ "FRIDAY": 5,
103
+ "SATURDAY": 6,
104
+ "SUNDAY": 7,
105
+ }
106
+
107
+ #: `date.weekday()` (Monday=0 .. Sunday=6) to `Weekday`.
108
+ _PY_WEEKDAY: tuple[Weekday, ...] = (
109
+ "MONDAY",
110
+ "TUESDAY",
111
+ "WEDNESDAY",
112
+ "THURSDAY",
113
+ "FRIDAY",
114
+ "SATURDAY",
115
+ "SUNDAY",
116
+ )
117
+
118
+ _DAYS_ENTRY_RE = re.compile(
119
+ r"^\s*(?P<day>\S+)\s+(?P<hour>\d{1,2}):(?P<minute>\d{2})\s+"
120
+ r"(?P<duration>\S+)\s*,\s*(?P<title>.*?)\s*$"
121
+ )
122
+ _DURATION_RE = re.compile(r"^(?:(?P<hours>\d+)h)?(?:(?P<minutes>\d+)m)?$")
123
+ _SECTION_RE = re.compile(
124
+ r"^##[ \t]+(?P<title>.+?)(?:\s*\((?P<date>\d{4}-\d{2}-\d{2})\))?\s*$",
125
+ re.MULTILINE,
126
+ )
127
+
128
+
129
+ @dataclass(frozen=True)
130
+ class TimeOfDay:
131
+ """
132
+ A wall-clock time of day, as the server's `start` object spells it.
133
+ """
134
+
135
+ hour: int
136
+ minute: int
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class Duration:
141
+ """
142
+ A length of time, as the server's `duration` object spells it.
143
+ """
144
+
145
+ hours: int
146
+ minutes: int
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class TimeSlot:
151
+ """
152
+ One recurring weekly slot, from a single `days:` entry.
153
+ """
154
+
155
+ slug: str
156
+ day: Weekday
157
+ start: TimeOfDay
158
+ duration: Duration
159
+ title: str | None = None
160
+
161
+ @property
162
+ def ref(self) -> str:
163
+ """
164
+ The md5 digest of this slot's pushable fields.
165
+
166
+ The server stores no `ref` for a time slot, so this is computed on
167
+ both sides of the diff -- see `run.fetch_server_state`.
168
+ """
169
+ canonical = json.dumps(
170
+ {
171
+ "slug": self.slug,
172
+ "day": self.day,
173
+ "start": {"hour": self.start.hour, "minute": self.start.minute},
174
+ "duration": {
175
+ "hours": self.duration.hours,
176
+ "minutes": self.duration.minutes,
177
+ },
178
+ "title": self.title,
179
+ },
180
+ separators=(",", ":"),
181
+ sort_keys=True,
182
+ ensure_ascii=False,
183
+ )
184
+ return hashlib.md5(canonical.encode("utf-8")).hexdigest()
185
+
186
+
187
+ @dataclass(frozen=True)
188
+ class Holiday:
189
+ """
190
+ One `holidays:` entry: a `Month, Day, Title` with the year left out.
191
+ """
192
+
193
+ month: int
194
+ day: int
195
+ title: str
196
+
197
+
198
+ @dataclass(frozen=True)
199
+ class Section:
200
+ """
201
+ One h2 section of `calendar.md`, before any date is assigned to it.
202
+ """
203
+
204
+ title: str
205
+ description: str
206
+ fixed_date: date | None = None
207
+ cancelled: bool = False
208
+
209
+
210
+ @dataclass(frozen=True)
211
+ class Calendar:
212
+ """
213
+ `calendar.md`, parsed and nothing more.
214
+ """
215
+
216
+ start: date
217
+ end: date
218
+ slots: tuple[TimeSlot, ...] = ()
219
+ holidays: tuple[Holiday, ...] = ()
220
+ sections: tuple[Section, ...] = ()
221
+
222
+
223
+ @dataclass(frozen=True)
224
+ class EventKey:
225
+ """
226
+ The `(week, timeSlot)` natural key that names one CalendarEvent.
227
+ """
228
+
229
+ week: int
230
+ time_slot: str
231
+
232
+
233
+ @dataclass(frozen=True)
234
+ class Event:
235
+ """
236
+ One CalendarEvent, keyed the way the server keys it.
237
+
238
+ `time_slot` is a `TimeSlot.slug`, not a `TimeSlot`: `(week,
239
+ timeSlot)` is the server's primary key and its URL, so the plan
240
+ carries exactly that pair and nothing downstream re-derives it.
241
+ """
242
+
243
+ week: int
244
+ time_slot: str
245
+ title: str
246
+ description: str = ""
247
+ kind: EventKind = "REGULAR"
248
+ #: Slugs of the repositories the lesson links, sorted, without repeats.
249
+ repositories: tuple[str, ...] = ()
250
+
251
+ @property
252
+ def ref(self) -> str:
253
+ """
254
+ `md5(f"{title}#{description}")`, per the mapping.
255
+
256
+ With repositories, their sorted slugs also enter the digest, so
257
+ linking or unlinking one re-sends the event; so does a `kind` other
258
+ than `REGULAR`. Without either the digest stays the old one, so
259
+ existing refs do not change.
260
+ """
261
+ text = f"{self.title}#{self.description}"
262
+ if self.kind != "REGULAR":
263
+ text += f"#kind:{self.kind}"
264
+ if self.repositories:
265
+ text += "#repositories:" + ",".join(sorted(self.repositories))
266
+ digest = text.encode("utf-8")
267
+ return hashlib.md5(digest).hexdigest()
268
+
269
+
270
+ @dataclass(frozen=True)
271
+ class Allocation:
272
+ """
273
+ Every event a calendar yields, plus what the instructor should know.
274
+ """
275
+
276
+ events: tuple[Event, ...] = ()
277
+ warnings: tuple[str, ...] = ()
278
+
279
+
280
+ def parse_calendar(text: str) -> Calendar:
281
+ """
282
+ Parse `calendar.md` into a `Calendar`.
283
+
284
+ Raises:
285
+ CalendarError: The frontmatter is missing or malformed, `start` or
286
+ `end` is absent, `end` precedes `start`, or a `days:`/
287
+ `holidays:` entry does not parse.
288
+ """
289
+ front_matter, body = _split_front_matter(text)
290
+
291
+ start = _parse_date_field(front_matter, "start")
292
+ end = _parse_date_field(front_matter, "end")
293
+ if end < start:
294
+ raise CalendarError(f"end ({end}) precedes start ({start})")
295
+
296
+ raw_days = front_matter.get("days") or []
297
+ if not isinstance(raw_days, list):
298
+ raise CalendarError("`days:` must be a list")
299
+ slots = _parse_time_slots(raw_days)
300
+
301
+ raw_holidays = front_matter.get("holidays") or []
302
+ if not isinstance(raw_holidays, list):
303
+ raise CalendarError("`holidays:` must be a list")
304
+ holidays = tuple(_parse_holiday(entry) for entry in raw_holidays)
305
+
306
+ sections = _parse_sections(body)
307
+
308
+ return Calendar(
309
+ start=start,
310
+ end=end,
311
+ slots=slots,
312
+ holidays=holidays,
313
+ sections=sections,
314
+ )
315
+
316
+
317
+ def allocate(calendar: Calendar) -> Allocation:
318
+ """
319
+ Hand every h2 section a date, and every holiday that lands on a slot
320
+ an event of its own.
321
+
322
+ Raises:
323
+ CalendarError: A holiday's `Month, Day` matches two dates inside
324
+ the course's range, which only the instructor can resolve.
325
+ """
326
+ warnings: list[str] = []
327
+
328
+ # 1. Every (date, slot) candidate pair in range, in canonical order.
329
+ candidates: list[tuple[date, TimeSlot]] = []
330
+ day = calendar.start
331
+ while day <= calendar.end:
332
+ weekday = _PY_WEEKDAY[day.weekday()]
333
+ for slot in calendar.slots:
334
+ if slot.day == weekday:
335
+ candidates.append((day, slot))
336
+ day += timedelta(days=1)
337
+ candidates.sort(
338
+ key=lambda pair: (
339
+ pair[0],
340
+ pair[1].start.hour,
341
+ pair[1].start.minute,
342
+ pair[1].slug,
343
+ )
344
+ )
345
+
346
+ # 2. Resolve every holiday against the whole date range (not just the
347
+ # dates that carry a slot).
348
+ holiday_by_date: dict[date, Holiday] = {}
349
+ for holiday in calendar.holidays:
350
+ matches = [
351
+ candidate
352
+ for candidate in _date_range(calendar.start, calendar.end)
353
+ if candidate.month == holiday.month and candidate.day == holiday.day
354
+ ]
355
+ if not matches:
356
+ warnings.append(
357
+ f"holiday {holiday.title!r} ({holiday.month}/{holiday.day}) "
358
+ "matches no date in the course's range"
359
+ )
360
+ continue
361
+ if len(matches) > 1:
362
+ raise CalendarError(
363
+ f"holiday {holiday.title!r} ({holiday.month}/{holiday.day}) "
364
+ f"matches more than one date in the course's range: {matches}"
365
+ )
366
+ holiday_by_date[matches[0]] = holiday
367
+
368
+ # 3. Drop holiday pairs; each becomes its own HOLIDAY event.
369
+ emitted: list[tuple[date, TimeSlot, EventKind, str, str]] = []
370
+ pool: list[tuple[date, TimeSlot]] = []
371
+ for candidate_date, slot in candidates:
372
+ matched_holiday = holiday_by_date.get(candidate_date)
373
+ if matched_holiday is not None:
374
+ emitted.append((candidate_date, slot, "HOLIDAY", matched_holiday.title, ""))
375
+ else:
376
+ pool.append((candidate_date, slot))
377
+
378
+ # 4. Resolve fixed sections first; everything else queues sequentially.
379
+ queue: list[Section] = []
380
+ for section in calendar.sections:
381
+ if section.fixed_date is None:
382
+ queue.append(section)
383
+ continue
384
+
385
+ fixed_date = section.fixed_date
386
+ index = None
387
+ if (
388
+ calendar.start <= fixed_date <= calendar.end
389
+ and fixed_date not in holiday_by_date
390
+ ):
391
+ for candidate_index, (candidate_date, _slot) in enumerate(pool):
392
+ if candidate_date == fixed_date:
393
+ index = candidate_index
394
+ break
395
+
396
+ if index is None:
397
+ warnings.append(
398
+ f"section {section.title!r} has an invalid fixed date "
399
+ f"({fixed_date}) and rejoins the sequential queue"
400
+ )
401
+ queue.append(section)
402
+ continue
403
+
404
+ candidate_date, slot = pool.pop(index)
405
+ emitted.append(
406
+ (candidate_date, slot, _kind(section), section.title, section.description)
407
+ )
408
+
409
+ # 5. Assign the remaining sections, in file order, to the remaining
410
+ # pairs, in chronological order.
411
+ allocated = min(len(queue), len(pool))
412
+ for index in range(allocated):
413
+ candidate_date, slot = pool[index]
414
+ section = queue[index]
415
+ emitted.append(
416
+ (candidate_date, slot, _kind(section), section.title, section.description)
417
+ )
418
+
419
+ if len(pool) > allocated:
420
+ warnings.append(f"{len(pool) - allocated} date(s) left unallocated")
421
+ if len(queue) > allocated:
422
+ warnings.append(f"{len(queue) - allocated} section(s) truncated: no dates left")
423
+
424
+ if not emitted:
425
+ return Allocation(events=(), warnings=tuple(warnings))
426
+
427
+ # 6. `week` is the ISO-week distance from the week the course starts in,
428
+ # the same week 0 the server counts from the course's `startDate`.
429
+ start_monday = _iso_week_start(calendar.start)
430
+
431
+ emitted.sort(
432
+ key=lambda item: (
433
+ item[0],
434
+ item[1].start.hour,
435
+ item[1].start.minute,
436
+ item[1].slug,
437
+ )
438
+ )
439
+ events = tuple(
440
+ Event(
441
+ week=(_iso_week_start(event_date) - start_monday).days // 7,
442
+ time_slot=slot.slug,
443
+ title=title,
444
+ description=description,
445
+ kind=kind,
446
+ )
447
+ for event_date, slot, kind, title, description in emitted
448
+ )
449
+ return Allocation(events=events, warnings=tuple(warnings))
450
+
451
+
452
+ #
453
+ # Utilities
454
+ #
455
+ def _split_front_matter(text: str) -> tuple[dict[str, object], str]:
456
+ """
457
+ Split `calendar.md`'s leading `---`-delimited YAML front matter from
458
+ its body.
459
+
460
+ Raises:
461
+ CalendarError: There is no front matter, or it fails to parse as a
462
+ YAML mapping.
463
+ """
464
+ lines = text.splitlines(keepends=True)
465
+ if not lines or lines[0].strip() != "---":
466
+ raise CalendarError("calendar.md has no front matter")
467
+ for index in range(1, len(lines)):
468
+ if lines[index].strip() != "---":
469
+ continue
470
+ front_matter_text = "".join(lines[1:index])
471
+ body = "".join(lines[index + 1 :]).lstrip("\n")
472
+ try:
473
+ data = yaml.safe_load(front_matter_text)
474
+ except yaml.YAMLError as exc:
475
+ raise CalendarError(f"malformed front matter: {exc}") from exc
476
+ if not isinstance(data, dict):
477
+ raise CalendarError("front matter must be a YAML mapping")
478
+ return data, body
479
+ raise CalendarError("calendar.md's front matter is never closed")
480
+
481
+
482
+ def _parse_date_field(front_matter: dict[str, object], key: str) -> date:
483
+ """
484
+ Read a `date`-valued front matter field, accepting both the `date`
485
+ object YAML already parses and a plain ISO string.
486
+
487
+ Raises:
488
+ CalendarError: The field is absent or does not parse as a date.
489
+ """
490
+ value = front_matter.get(key)
491
+ if value is None:
492
+ raise CalendarError(f"calendar.md's front matter has no `{key}:`")
493
+ if isinstance(value, date):
494
+ return value
495
+ if isinstance(value, str):
496
+ try:
497
+ return date.fromisoformat(value)
498
+ except ValueError as exc:
499
+ raise CalendarError(f"`{key}: {value!r}` is not a valid date") from exc
500
+ raise CalendarError(f"`{key}: {value!r}` is not a valid date")
501
+
502
+
503
+ def _parse_time_slots(raw_days: list[object]) -> tuple[TimeSlot, ...]:
504
+ """
505
+ Parse every `days:` entry into a `TimeSlot`, sorted by ISO weekday then
506
+ start time, with slugs assigned (and suffixed on collision) afterward.
507
+
508
+ Raises:
509
+ CalendarError: An entry does not match `WeekDay HH:MM Duration,
510
+ Title`.
511
+ """
512
+ parsed: list[tuple[Weekday, TimeOfDay, Duration, str | None]] = []
513
+ for entry in raw_days:
514
+ parsed.append(_parse_time_slot_entry(str(entry)))
515
+
516
+ parsed.sort(key=lambda item: (_WEEKDAY_ISO[item[0]], item[1].hour, item[1].minute))
517
+
518
+ slots: list[TimeSlot] = []
519
+ for weekday, group in groupby(parsed, key=lambda item: item[0]):
520
+ entries = list(group)
521
+ base_slug = _WEEKDAY_SLUG[weekday]
522
+ collision = len(entries) > 1
523
+ for day, start, duration, title in entries:
524
+ slug = (
525
+ f"{base_slug}-{start.hour:02d}_{start.minute:02d}"
526
+ if collision
527
+ else base_slug
528
+ )
529
+ slots.append(
530
+ TimeSlot(
531
+ slug=slug, day=day, start=start, duration=duration, title=title
532
+ )
533
+ )
534
+ return tuple(slots)
535
+
536
+
537
+ def _parse_time_slot_entry(
538
+ entry: str,
539
+ ) -> tuple[Weekday, TimeOfDay, Duration, str | None]:
540
+ match = _DAYS_ENTRY_RE.match(entry)
541
+ if match is None:
542
+ raise CalendarError(
543
+ f"`days:` entry {entry!r} is not `WeekDay HH:MM Duration, Title`"
544
+ )
545
+
546
+ weekday = _WEEKDAY_ALIASES.get(match.group("day").lower())
547
+ if weekday is None:
548
+ raise CalendarError(f"`days:` entry {entry!r} has an unknown weekday")
549
+
550
+ hour = int(match.group("hour"))
551
+ minute = int(match.group("minute"))
552
+
553
+ duration_match = _DURATION_RE.match(match.group("duration"))
554
+ if duration_match is None or not _duration_has_value(duration_match):
555
+ raise CalendarError(f"`days:` entry {entry!r} has an invalid duration")
556
+ hours = int(duration_match.group("hours") or 0)
557
+ minutes = int(duration_match.group("minutes") or 0)
558
+
559
+ title = match.group("title").strip() or None
560
+ return (
561
+ weekday,
562
+ TimeOfDay(hour=hour, minute=minute),
563
+ Duration(hours=hours, minutes=minutes),
564
+ title,
565
+ )
566
+
567
+
568
+ def _duration_has_value(match: re.Match[str]) -> bool:
569
+ """
570
+ Whether a duration match captured at least one of `hours`/`minutes`.
571
+ """
572
+ return match.group("hours") is not None or match.group("minutes") is not None
573
+
574
+
575
+ def _parse_holiday(entry: object) -> Holiday:
576
+ """
577
+ Parse one `holidays:` entry, `Month, Day, Title`.
578
+
579
+ Raises:
580
+ CalendarError: The entry does not split into three parts, or the
581
+ month/day do not parse.
582
+ """
583
+ text = str(entry)
584
+ parts = [part.strip() for part in text.split(",", 2)]
585
+ if len(parts) != 3:
586
+ raise CalendarError(f"`holidays:` entry {entry!r} is not `Month, Day, Title`")
587
+ month_text, day_text, title = parts
588
+
589
+ month = _parse_month(month_text)
590
+ try:
591
+ day = int(day_text)
592
+ except ValueError as exc:
593
+ raise CalendarError(f"`holidays:` entry {entry!r} has an invalid day") from exc
594
+
595
+ return Holiday(month=month, day=day, title=title)
596
+
597
+
598
+ def _parse_month(text: str) -> int:
599
+ if text.isdigit():
600
+ return int(text)
601
+ for fmt in ("%b", "%B"):
602
+ try:
603
+ return datetime.strptime(text, fmt).month
604
+ except ValueError:
605
+ continue
606
+ raise CalendarError(f"{text!r} is not a valid month")
607
+
608
+
609
+ def _parse_sections(body: str) -> tuple[Section, ...]:
610
+ """
611
+ Parse every h2 (`## Title`, optionally `## Title (YYYY-MM-DD)`) into a
612
+ `Section`, its description running to the next h2 or the end of file.
613
+ A title struck through (`## ~~Title~~`) is a cancelled lesson.
614
+ """
615
+ matches = list(_SECTION_RE.finditer(body))
616
+ sections = []
617
+ for index, match in enumerate(matches):
618
+ title = match.group("title").strip()
619
+ mark = CANCELLED_MARK
620
+ inner = title.removeprefix(mark).removesuffix(mark).strip()
621
+ cancelled = (
622
+ len(title) > 2 * len(mark)
623
+ and title.startswith(mark)
624
+ and title.endswith(mark)
625
+ and bool(inner)
626
+ )
627
+ if cancelled:
628
+ title = inner
629
+ fixed_date = (
630
+ date.fromisoformat(match.group("date")) if match.group("date") else None
631
+ )
632
+ start = match.end()
633
+ end = matches[index + 1].start() if index + 1 < len(matches) else len(body)
634
+ description = body[start:end].strip()
635
+ sections.append(
636
+ Section(
637
+ title=title,
638
+ description=description,
639
+ fixed_date=fixed_date,
640
+ cancelled=cancelled,
641
+ )
642
+ )
643
+ return tuple(sections)
644
+
645
+
646
+ def _kind(section: Section) -> EventKind:
647
+ return "CANCELLED" if section.cancelled else "REGULAR"
648
+
649
+
650
+ def _date_range(start: date, end: date) -> Iterator[date]:
651
+ """
652
+ Every date from `start` to `end`, inclusive.
653
+ """
654
+ day = start
655
+ while day <= end:
656
+ yield day
657
+ day += timedelta(days=1)
658
+
659
+
660
+ def _iso_week_start(day: date) -> date:
661
+ """
662
+ The Monday of the ISO week `day` falls in.
663
+ """
664
+ return day - timedelta(days=day.isoweekday() - 1)