adventofcode 26.1__py3-none-any.whl → 26.2__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.
adventofcode/__init__.py CHANGED
@@ -1,13 +1,14 @@
1
- import datetime as dt
1
+ import dbm
2
+ import functools
2
3
  import os
3
- import re
4
+ import shelve
4
5
  import sys
5
6
  import time
6
7
  from collections.abc import Callable
7
8
  from contextlib import contextmanager
8
9
  from pathlib import Path
9
10
  from timeit import Timer
10
- from typing import Any
11
+ from typing import Any, Literal
11
12
 
12
13
  import percache
13
14
  import requests
@@ -15,25 +16,89 @@ from bs4 import BeautifulSoup
15
16
  from dotenv import load_dotenv
16
17
  from rich.console import Console
17
18
 
18
- from adventofcode.utils import PART_1_RETURN_STR, PART_2_RETURN_STR, format_time
19
+ from adventofcode.__about__ import __version__
20
+ from adventofcode.auth import read_saved_session
21
+ from adventofcode.puzzle import to_markdown, to_rich, to_text
22
+ from adventofcode.utils import PART_1_RETURN_STR, PART_2_RETURN_STR, default_year, format_time, parse_day
19
23
 
20
24
  load_dotenv(Path(".env").absolute().as_posix())
21
- cache = percache.Cache(".cache", livesync=True)
22
25
  console = Console(log_path=False)
23
26
 
24
27
  AOC_URL = "https://adventofcode.com"
25
-
28
+ # Advent of Code asks automated tools to identify themselves in the User-Agent header.
29
+ HEADERS = {"User-Agent": f"adventofcode/{__version__} (+https://github.com/anze3db/adventofcode)"}
26
30
 
27
31
  AOC_SESSION = os.getenv("AOC_SESSION")
28
- est = dt.timezone(dt.timedelta(hours=-5))
29
- today_est = dt.datetime.now(tz=est).date()
30
-
31
- AOC_YEAR = int(os.getenv("AOC_YEAR", str(today_est.year)))
32
+ AOC_YEAR = int(os.getenv("AOC_YEAR", str(default_year())))
32
33
 
33
34
  AOC_NOT_SET_MSG = (
34
- "Set AOC_SESSION to your `session` cookie on adventofcode.com. You can add it to your .env file or "
35
- "export it in your shell (export AOC_SESSION='your session cookie')"
35
+ "No Advent of Code session cookie is set up. Run `adventofcode login` to set it up for every folder, "
36
+ "or set AOC_SESSION in this folder's .env file."
36
37
  )
38
+ SESSION_EXPIRED_MSG = (
39
+ "adventofcode.com didn't accept your session cookie. It has probably expired (they last about a month) "
40
+ "or wasn't copied completely: run `adventofcode login` to set up a new one."
41
+ )
42
+
43
+ PuzzleFormat = Literal["text", "markdown", "html"]
44
+ SubmitStatus = Literal["correct", "incorrect", "already_solved", "too_recent", "skipped", "unknown"]
45
+ # Answers that count as "this part is done": the next part can be submitted.
46
+ SOLVED_STATUSES = frozenset({"correct", "already_solved"})
47
+
48
+
49
+ class AoCError(Exception):
50
+ """Something went wrong talking to adventofcode.com."""
51
+
52
+
53
+ class SessionExpiredError(AoCError):
54
+ """adventofcode.com doesn't recognise the session cookie."""
55
+
56
+ def __init__(self, msg: str = SESSION_EXPIRED_MSG):
57
+ super().__init__(msg)
58
+
59
+
60
+ class PuzzleNotAvailableError(AoCError):
61
+ """The requested puzzle part isn't unlocked yet."""
62
+
63
+
64
+ class AnswerTooRecentError(AoCError):
65
+ """adventofcode.com asked us to wait before submitting another answer.
66
+
67
+ Raised from the cached `submit` so the response is never cached and the answer can be retried.
68
+ """
69
+
70
+
71
+ _cache: percache.Cache | None = None
72
+
73
+
74
+ def _open_cache() -> percache.Cache:
75
+ """Open the cache of puzzle inputs and submitted answers the first time it's needed, not on import."""
76
+ global _cache # noqa: PLW0603
77
+ if _cache is None:
78
+ path = os.getenv("AOC_CACHE", ".cache")
79
+ try:
80
+ # Open the shelf here so a failure doesn't leave a half-built percache.Cache behind
81
+ # (its __del__ prints a traceback).
82
+ shelf = shelve.open(path, protocol=-1) # noqa: S301
83
+ except dbm.error as e:
84
+ msg = (
85
+ f"Could not open the cache at {path!r} ({e}). It was probably created by another Python version: "
86
+ "run with that version again, or delete the cache (answers you already submitted will be "
87
+ "submitted again)."
88
+ )
89
+ raise AoCError(msg) from e
90
+ _cache = percache.Cache(shelf, livesync=True)
91
+ return _cache
92
+
93
+
94
+ def cache(func):
95
+ """Cache the result of `func` in the `.cache` file (`AOC_CACHE`) so it survives between runs."""
96
+
97
+ @functools.wraps(func)
98
+ def wrapper(*args, **kwargs):
99
+ return _open_cache()(func)(*args, **kwargs)
100
+
101
+ return wrapper
37
102
 
38
103
 
39
104
  class PerfResult:
@@ -58,16 +123,17 @@ def print_perf(typ=""):
58
123
  class AoC:
59
124
  def __init__(
60
125
  self,
61
- part_1: Callable[[str], str | int | None],
62
- part_2: Callable[[str], str | int | None],
126
+ part_1: Callable[[str], str | int | None] | None = None,
127
+ part_2: Callable[[str], str | int | None] | None = None,
63
128
  *,
64
129
  day: int | None = None,
65
130
  year: int | None = None,
66
131
  ):
67
132
  if day is None:
68
- current_filename = Path(sys.argv[0]).stem
69
- current_filename_numbers = re.sub(r"[^0-9.]", "", current_filename)
70
- day = int(current_filename_numbers)
133
+ day = parse_day(Path(sys.argv[0]).stem)
134
+ if day is None:
135
+ msg = f"Could not determine the day from {sys.argv[0]!r}. Pass day= explicitly."
136
+ raise ValueError(msg)
71
137
  if year is None:
72
138
  year = AOC_YEAR
73
139
 
@@ -78,117 +144,237 @@ class AoC:
78
144
  self.part_2 = part_2
79
145
 
80
146
  def print_p1(self):
81
- console.log(get_puzzle(self.day, self.year, part=1))
147
+ self._print_puzzle(part=1)
82
148
 
83
149
  def print_p2(self):
84
- console.log(get_puzzle(self.day, self.year, part=2))
150
+ self._print_puzzle(part=2)
151
+
152
+ def _print_puzzle(self, part: int):
153
+ """Print the puzzle with its highlights and code styled, as on adventofcode.com."""
154
+ try:
155
+ console.print(to_rich(get_puzzle_html(self.day, self.year, part=part)))
156
+ except PuzzleNotAvailableError as e:
157
+ console.log(f"[yellow]{e}[/yellow]")
158
+
159
+ def get_puzzle(self, part: int, format: PuzzleFormat = "text") -> str: # noqa: A002
160
+ """The puzzle description for a part, as plain text, Markdown or HTML."""
161
+ return get_puzzle(self.day, self.year, part=part, format=format)
85
162
 
86
163
  def get_input(self):
87
164
  return get_input(year=self.year, day=self.day)
88
165
 
89
166
  def assert_p1(self, inp: str, expected: Any):
90
- res = None
91
- with print_perf("assert part1"):
92
- res = self.part_1(inp)
93
-
94
- if res is None:
95
- console.log(f"[red]part_1 returned [white]None[/white] for input:[/red]\n{inp[:100]}")
96
- sys.exit(10)
97
- if res != expected:
98
- console.log(
99
- f"[red]part_1 returned [white]{res}[/white] instead of expected [white]{expected}[/white]"
100
- f" for input:[/red]\n{inp[:100]}"
101
- )
102
- sys.exit(11)
167
+ self._assert(self._solver(1), inp, expected, part=1)
103
168
 
104
169
  def assert_p2(self, inp: str, expected: Any):
105
- res = None
106
- with print_perf("assert part2"):
107
- res = self.part_2(inp)
170
+ self._assert(self._solver(2), inp, expected, part=2)
171
+
172
+ def _assert(self, solver: Callable[[str], Any], inp: str, expected: Any, part: int):
173
+ with print_perf(f"assert part{part}"):
174
+ res = solver(inp)
108
175
 
109
176
  if res is None:
110
- console.log(f"[red]part_2 returned [white]None[/white] for input:[/red]\n{inp[:100]}")
111
- sys.exit(20)
177
+ console.log(f"[red]part_{part} returned [white]None[/white] for input:[/red]\n{inp[:100]}")
178
+ sys.exit(part * 10)
112
179
  if res != expected:
113
180
  console.log(
114
- f"[red]part_2 returned [white]{res}[/white] instead of expected [white]{expected}[/white]"
181
+ f"[red]part_{part} returned [white]{res}[/white] instead of expected [white]{expected}[/white]"
115
182
  f" for input:[/red]\n{inp[:100]}"
116
183
  )
117
- sys.exit(21)
118
-
119
- def submit_p1(self, answer: Any | None = None):
184
+ sys.exit(part * 10 + 1)
185
+
186
+ def _solver(self, part: int) -> Callable[[str], Any]:
187
+ solver = self.part_1 if part == 1 else self.part_2
188
+ if solver is None:
189
+ msg = f"AoC was created without a part_{part} function"
190
+ raise TypeError(msg)
191
+ return solver
192
+
193
+ def submit_p1(self, answer: Any | None = None) -> SubmitStatus:
194
+ """Submit part 1. Without an `answer`, solve the puzzle input with `part_1` and submit the result."""
195
+ return self._submit(1, answer)
196
+
197
+ def submit_p2(self, answer: Any | None = None) -> SubmitStatus:
198
+ """Submit part 2. Without an `answer`, solve the puzzle input with `part_2` and submit the result."""
199
+ return self._submit(2, answer)
200
+
201
+ def _submit(self, level: int, answer: Any | None) -> SubmitStatus:
202
+ if answer is None:
203
+ solver = self._solver(level)
204
+ inp = self.get_input()
205
+ with print_perf(PART_1_RETURN_STR if level == 1 else PART_2_RETURN_STR) as perf:
206
+ answer = solver(inp)
207
+ perf.value = answer
208
+ return submit_answer(year=self.year, day=self.day, level=level, answer=answer)
209
+
210
+ def submit_p1_benchmark(self) -> SubmitStatus:
211
+ return self._submit_benchmark(1)
212
+
213
+ def submit_p2_benchmark(self) -> SubmitStatus:
214
+ return self._submit_benchmark(2)
215
+
216
+ def _submit_benchmark(self, level: int) -> SubmitStatus:
217
+ solver = self._solver(level)
120
218
  inp = self.get_input()
121
- with print_perf(PART_1_RETURN_STR) as perf:
122
- answer = self.part_1(inp)
123
- perf.value = answer
124
- submit(year=self.year, day=self.day, level=1, answer=answer)
219
+ answer = solver(inp)
220
+ num_loops, total_time = Timer(lambda: solver(inp)).autorange()
221
+ label = PART_1_RETURN_STR if level == 1 else PART_2_RETURN_STR
222
+ console.log(f"{format_time(total_time / num_loops)} to {label}")
223
+ return submit_answer(year=self.year, day=self.day, level=level, answer=answer)
224
+
225
+
226
+ def _get(url: str, *, session: str | None) -> requests.Response:
227
+ return requests.get(
228
+ url,
229
+ cookies={"session": session} if session else None,
230
+ headers=HEADERS,
231
+ timeout=10,
232
+ )
125
233
 
126
- def submit_p2(self, answer: Any | None = None):
127
- inp = self.get_input()
128
- with print_perf(PART_2_RETURN_STR) as perf:
129
- answer = self.part_2(inp)
130
- perf.value = answer
131
- submit(year=self.year, day=self.day, level=2, answer=answer)
132
234
 
133
- def submit_p1_benchmark(self):
134
- inp = self.get_input()
135
- num_loops, total_time = Timer(lambda: self.part_1(inp)).autorange()
136
- console.log(f"{format_time(total_time / num_loops)} to {PART_1_RETURN_STR}")
137
- submit(year=self.year, day=self.day, level=1, answer=self.part_1(inp))
235
+ def current_session() -> str | None:
236
+ """The session cookie: AOC_SESSION (from the environment or .env) first, then the one `adventofcode login` saved."""
237
+ return AOC_SESSION or read_saved_session()
138
238
 
139
- def submit_p2_benchmark(self):
140
- inp = self.get_input()
141
- num_loops, total_time = Timer(lambda: self.part_2(inp)).autorange()
142
- console.log(f"{format_time(total_time / num_loops)} to {PART_2_RETURN_STR}")
143
- submit(year=self.year, day=self.day, level=2, answer=self.part_2(inp))
239
+
240
+ def _require_session() -> str:
241
+ if not (session := current_session()):
242
+ raise AoCError(AOC_NOT_SET_MSG)
243
+ return session
244
+
245
+
246
+ def _rejected(result: requests.Response) -> bool:
247
+ """Whether adventofcode.com rejected the session cookie we sent.
248
+
249
+ An expired cookie gets the logged-out page ("Please log in", a [Log In] link); a cookie the site doesn't
250
+ recognise at all gets a 500 Internal Server Error.
251
+ """
252
+ return result.status_code == 500 or "please log in" in result.text.lower() or "/auth/login" in result.text
253
+
254
+
255
+ def whoami(session: str) -> str | None:
256
+ """The adventofcode.com user name for a session cookie, or None when the site doesn't accept the cookie."""
257
+ result = _get(f"{AOC_URL}/2015", session=session) # The first event's page is always there.
258
+ if _rejected(result):
259
+ return None
260
+ if result.status_code != 200:
261
+ msg = f"Could not reach adventofcode.com ({result.status_code})"
262
+ raise AoCError(msg)
263
+ user = BeautifulSoup(result.text, features="html.parser").select_one("div.user")
264
+ if user is None:
265
+ return None
266
+ for extra in user.find_all(["span", "a"]): # The star count and the AoC++ badge
267
+ extra.decompose()
268
+ return user.get_text(strip=True) or "an anonymous user"
269
+
270
+
271
+ def get_puzzle(day: int, year: int, part: int, format: PuzzleFormat = "text") -> str: # noqa: A002
272
+ """The puzzle description for a part.
273
+
274
+ `format` is "text" (plain text), "markdown" (highlights in bold, code as code; examples with highlights stay
275
+ HTML, since Markdown can't highlight inside a code block) or "html" (the page's <article> as it is).
276
+ """
277
+ html = get_puzzle_html(day, year, part=part)
278
+ match format:
279
+ case "html":
280
+ return html
281
+ case "markdown":
282
+ return to_markdown(html)
283
+ case "text":
284
+ return to_text(html)
285
+ msg = f"format must be 'text', 'markdown' or 'html', not {format!r}"
286
+ raise ValueError(msg)
144
287
 
145
288
 
146
289
  @cache
147
- def get_puzzle(day: int, year: int, part: int) -> str:
290
+ def get_puzzle_html(day: int, year: int, part: int) -> str:
291
+ """The <article> with the description of a puzzle part, fetched once and cached."""
148
292
  console.log("Fetching puzzle text from server")
149
- result = requests.get(
150
- f"{AOC_URL}/{year}/day/{day}",
151
- cookies={"session": AOC_SESSION} if AOC_SESSION else None,
152
- timeout=10,
153
- )
154
- assert result.status_code == 200, result.text
293
+ session = current_session()
294
+ result = _get(f"{AOC_URL}/{year}/day/{day}", session=session)
295
+ if session and _rejected(result):
296
+ raise SessionExpiredError
297
+ if result.status_code != 200:
298
+ msg = f"Could not fetch the puzzle for {year} day {day} ({result.status_code}): {result.text.strip()}"
299
+ raise PuzzleNotAvailableError(msg)
155
300
 
156
301
  soup = BeautifulSoup(result.text, features="html.parser")
302
+ articles = soup.body.main.find_all("article")
303
+ if len(articles) < part:
304
+ # Raised rather than returned so a "not available yet" answer is never cached.
305
+ msg = f"Part {part} is not available yet"
306
+ raise PuzzleNotAvailableError(msg)
157
307
 
158
- index = part - 1
159
- if len(soup.body.main.findAll("article")) < index:
160
- return f"Part {part} Not yet available"
161
-
162
- return soup.body.main.findAll("article")[part - 1].get_text()
308
+ return str(articles[part - 1])
163
309
 
164
310
 
165
311
  @cache
166
312
  def get_input(year: int, day: int) -> str:
167
- assert AOC_SESSION, AOC_NOT_SET_MSG
313
+ session = _require_session()
168
314
  console.log("Fetching from server")
169
- result = requests.get(
170
- f"{AOC_URL}/{year}/day/{day}/input",
171
- cookies={"session": AOC_SESSION},
172
- timeout=10,
173
- )
174
- assert result.status_code == 200, (f"{AOC_URL}/{year}/day/{day}/input", result.text)
315
+ result = _get(f"{AOC_URL}/{year}/day/{day}/input", session=session)
316
+ if result.status_code != 200 and _rejected(result):
317
+ raise SessionExpiredError
318
+ if result.status_code != 200:
319
+ msg = f"Could not fetch {AOC_URL}/{year}/day/{day}/input ({result.status_code}): {result.text.strip()}"
320
+ raise AoCError(msg)
175
321
 
176
322
  return result.text
177
323
 
178
324
 
325
+ def parse_submit_response(text: str) -> SubmitStatus:
326
+ """Classify the message adventofcode.com shows after an answer is submitted."""
327
+ if "That's the right answer" in text:
328
+ return "correct"
329
+ if "That's not the right answer" in text:
330
+ return "incorrect"
331
+ if "You gave an answer too recently" in text:
332
+ return "too_recent"
333
+ if "You don't seem to be solving the right level" in text:
334
+ return "already_solved"
335
+ return "unknown"
336
+
337
+
338
+ # The cache key is derived from the function name and arguments (keyword names included), so keep both stable:
339
+ # renaming it would resubmit every answer (including known wrong ones) that was ever cached.
179
340
  @cache
180
- def submit(year: int, day: int, level: int, answer: Any):
181
- assert AOC_SESSION, AOC_NOT_SET_MSG
341
+ def submit(year: int, day: int, level: int, answer: Any) -> SubmitStatus:
342
+ """Submit an answer once. The response is cached so the same answer is never submitted twice.
343
+
344
+ Raises AnswerTooRecentError (which isn't cached) when adventofcode.com asks us to wait.
345
+ """
346
+ session = _require_session()
182
347
  console.log(f"Posting [bold]{answer}[/bold] for {day=} {level=}")
183
- if not answer:
184
- console.log("Skipping submission", answer)
185
- return
186
348
  result = requests.post(
187
349
  f"{AOC_URL}/{year}/day/{day}/answer",
188
350
  {"level": level, "answer": answer},
189
- cookies={"session": AOC_SESSION},
351
+ cookies={"session": session},
352
+ headers=HEADERS,
190
353
  timeout=10,
191
354
  )
192
- assert result.status_code == 200, result.text
355
+ if _rejected(result):
356
+ raise SessionExpiredError
357
+ if result.status_code != 200:
358
+ msg = f"Submitting the answer failed ({result.status_code}): {result.text.strip()}"
359
+ raise AoCError(msg)
193
360
  soup = BeautifulSoup(result.text, features="html.parser")
194
- console.log(soup.body.main.article.get_text())
361
+ text = soup.body.main.article.get_text() if soup.body and soup.body.main and soup.body.main.article else ""
362
+ status = parse_submit_response(text)
363
+ color = {"correct": "green", "incorrect": "red", "too_recent": "yellow"}.get(status, "white")
364
+ console.log(f"[{color}]{text.strip()}[/{color}]")
365
+ if status == "too_recent":
366
+ raise AnswerTooRecentError(text.strip())
367
+ return status
368
+
369
+
370
+ def submit_answer(year: int, day: int, level: int, answer: Any) -> SubmitStatus:
371
+ """Submit an answer unless it's empty or was already submitted. Never raises for rate limiting."""
372
+ if answer is None or str(answer).strip() == "":
373
+ console.log(f"Skipping submission of empty answer {answer!r} for {day=} {level=}")
374
+ return "skipped"
375
+ try:
376
+ # Keyword arguments are part of the cache key: keep calling it exactly like this.
377
+ # Answers cached before statuses were tracked come back as None: they were submitted, the outcome is unknown.
378
+ return submit(year=year, day=day, level=level, answer=answer) or "unknown"
379
+ except AnswerTooRecentError:
380
+ return "too_recent"
adventofcode/auth.py ADDED
@@ -0,0 +1,45 @@
1
+ """Where `adventofcode login` keeps the session cookie, so every puzzle folder on the computer can use it."""
2
+
3
+ import os
4
+ import re
5
+ from pathlib import Path
6
+
7
+
8
+ def config_dir() -> Path:
9
+ if base := os.getenv("XDG_CONFIG_HOME"):
10
+ return Path(base) / "adventofcode"
11
+ if os.name == "nt" and (appdata := os.getenv("APPDATA")):
12
+ return Path(appdata) / "adventofcode"
13
+ return Path.home() / ".config" / "adventofcode"
14
+
15
+
16
+ def saved_session_path() -> Path:
17
+ return config_dir() / "session"
18
+
19
+
20
+ def read_saved_session() -> str | None:
21
+ try:
22
+ value = saved_session_path().read_text(encoding="utf-8").strip()
23
+ except OSError:
24
+ return None
25
+ return value or None
26
+
27
+
28
+ def save_session(session: str) -> Path:
29
+ """Save the cookie in a file only its owner can read. Returns the file's path."""
30
+ path = saved_session_path()
31
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
32
+ # Create the file with owner-only permissions before the secret goes into it.
33
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
34
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
35
+ f.write(f"{session}\n")
36
+ path.chmod(0o600) # The file may have existed with wider permissions.
37
+ return path
38
+
39
+
40
+ def clean_session(value: str) -> str:
41
+ """Accept what people paste: the bare value, `session=...`, quoted, or a whole Cookie header."""
42
+ value = value.strip().strip("'\"")
43
+ if match := re.search(r"(?:^|[;\s])session=([^;\s]+)", value):
44
+ value = match[1]
45
+ return value.strip().strip("'\"")