adventofcode 25.0__py3-none-any.whl → 25.1__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/__about__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "25.0"
1
+ __version__ = "25.1"
adventofcode/__init__.py CHANGED
@@ -14,7 +14,7 @@ from bs4 import BeautifulSoup
14
14
  from dotenv import load_dotenv
15
15
  from rich.console import Console
16
16
 
17
- load_dotenv()
17
+ load_dotenv(Path(".env").absolute().as_posix())
18
18
  cache = percache.Cache(".cache", livesync=True)
19
19
  console = Console()
20
20
 
@@ -22,7 +22,10 @@ AOC_URL = "https://adventofcode.com"
22
22
 
23
23
 
24
24
  AOC_SESSION = os.getenv("AOC_SESSION")
25
- AOC_YEAR = int(os.getenv("AOC_YEAR", str(datetime.datetime.now(tz=datetime.timezone.utc).year)))
25
+ est = datetime.timezone(datetime.timedelta(hours=-5))
26
+ today_est = datetime.datetime.now(tz=est).date()
27
+
28
+ AOC_YEAR = int(os.getenv("AOC_YEAR", str(today_est.year)))
26
29
 
27
30
  AOC_NOT_SET_MSG = (
28
31
  "Set AOC_SESSION to your `session` cookie on adventofcode.com. You can add it to your .env file or "
adventofcode/cli.py CHANGED
@@ -1,9 +1,25 @@
1
1
  import argparse
2
2
  import datetime
3
+ import os
4
+ import re
5
+ import subprocess
6
+ import sys
7
+ from dataclasses import dataclass
3
8
  from pathlib import Path
4
9
  from textwrap import dedent
10
+ from typing import Literal
5
11
 
12
+ from dotenv import load_dotenv
6
13
  from rich.console import Console
14
+ from rich.live import Live
15
+ from rich.table import Table
16
+
17
+ load_dotenv(Path(".env").absolute().as_posix())
18
+
19
+ est = datetime.timezone(datetime.timedelta(hours=-5))
20
+ today_est = datetime.datetime.now(tz=est).date()
21
+
22
+ AOC_YEAR = int(os.getenv("AOC_YEAR", str(today_est.year)))
7
23
 
8
24
  console = Console()
9
25
  TEMPLATE = dedent('''\
@@ -75,6 +91,270 @@ def generate_templates(year: int, output_dir: Path, num_days: int) -> None:
75
91
  console.log("Created .env file (remember to set your AOC_SESSION)")
76
92
 
77
93
 
94
+ def parse_timing_output(output: str) -> tuple[float, float]:
95
+ """Parse timing information from the AoC class output.
96
+
97
+ The AoC class outputs lines like:
98
+ - "0.00123s for submit_p1"
99
+ - "0.00456s for submit_p2"
100
+ """
101
+ part1_time = part2_time = 0.0
102
+
103
+ for line in output.split("\n"):
104
+ match = re.search(r"(\d+\.\d+)s for (?:submit_p1)", line)
105
+ if match:
106
+ part1_time = float(match.group(1))
107
+
108
+ match = re.search(r"(\d+\.\d+)s for (?:submit_p2)", line)
109
+ if match:
110
+ part2_time = float(match.group(1))
111
+
112
+ return part1_time, part2_time
113
+
114
+
115
+ Color = Literal["green", "yellow", "red", "white"]
116
+
117
+
118
+ @dataclass
119
+ class DayResult:
120
+ day: str
121
+ part1_time: float = 0.0
122
+ part2_time: float = 0.0
123
+ total_time: float = 0.0
124
+
125
+ status: str = ""
126
+ error: str | None = None
127
+
128
+
129
+ def time_to_color(seconds: float) -> Color:
130
+ if seconds <= 0.0:
131
+ return "white"
132
+ elif seconds < 0.1:
133
+ return "green"
134
+ elif seconds < 1:
135
+ return "yellow"
136
+ else:
137
+ return "red"
138
+
139
+
140
+ def run_day(filepath: Path) -> DayResult:
141
+ day_num = int(re.sub(r"[^0-9]", "", filepath.stem))
142
+ if datetime.date(AOC_YEAR, 12, day_num) > today_est:
143
+ return DayResult(day=filepath.stem, status="🕑")
144
+
145
+ result = DayResult(day=filepath.stem)
146
+
147
+ try:
148
+ proc = subprocess.run( # noqa: S603
149
+ [sys.executable, str(filepath)],
150
+ cwd=filepath.parent,
151
+ capture_output=True,
152
+ text=True,
153
+ timeout=300, # 300 second timeout
154
+ check=False,
155
+ )
156
+ except subprocess.TimeoutExpired:
157
+ result.error = "Timeout (>5m)"
158
+ result.status = "⏰"
159
+ return result
160
+ except Exception as e:
161
+ result.error = str(e)
162
+ result.status = "❌"
163
+ return result
164
+
165
+ output = proc.stdout + proc.stderr
166
+
167
+ if proc.returncode != 0:
168
+ result.error = output.strip()[-200:] if output else "Unknown error"
169
+ result.status = "❌"
170
+ return result
171
+
172
+ part1_time, part2_time = parse_timing_output(output)
173
+ result.part1_time = part1_time
174
+ result.part2_time = part2_time
175
+ result.total_time = part1_time + part2_time
176
+
177
+ if part1_time > 0.0 and part2_time > 0.0:
178
+ result.status = "✅"
179
+ elif part1_time > 0.0 or part2_time > 0.0:
180
+ if AOC_YEAR < 2025 and day_num == 25:
181
+ result.status = "✅"
182
+ elif AOC_YEAR >= 2025 and day_num == 12:
183
+ result.status = "✅"
184
+ else:
185
+ result.status = "⚠️"
186
+ else:
187
+ result.status = "✏️"
188
+
189
+ return result
190
+
191
+
192
+ def format_time(seconds: float) -> str:
193
+ if seconds <= 0.0:
194
+ return "-"
195
+ if seconds < 1:
196
+ return f"{seconds * 1000:.1f}ms"
197
+ return f"{seconds:.2f}s"
198
+
199
+
200
+ def build_markdown_table(results: list[DayResult], total_time: float, total_part_1: float, total_part_2: float) -> str:
201
+ """Generate a markdown table from benchmark results."""
202
+ lines = [
203
+ "| Day | Status | Part 1 Time | Part 2 Time | Total Time | ",
204
+ "|:---:|:------:|------------:|------------:|-----------:| ",
205
+ ]
206
+
207
+ for r in results:
208
+ p1_time = markdown_color(format_time(r.part1_time), time_to_color(r.part1_time))
209
+ p2_time = markdown_color(format_time(r.part2_time), time_to_color(r.part2_time))
210
+ total = markdown_color(format_time(r.total_time), time_to_color(r.total_time))
211
+
212
+ lines.append(f"| {r.day} | {r.status} | {p1_time} | {p2_time} | {total} |")
213
+
214
+ p1_total = markdown_color(format_time(total_part_1), time_to_color(total_part_1))
215
+ p2_total = markdown_color(format_time(total_part_2), time_to_color(total_part_2))
216
+ total = markdown_color(format_time(total_time), time_to_color(total_time))
217
+ # Add total row
218
+ lines.append(f"| **Total** | | {p1_total} | {p2_total} | {total} |")
219
+ lines.append("")
220
+ lines.append("Legend:")
221
+ lines.append(" * 🟢 < 100ms")
222
+ lines.append(" * 🟡 100ms - 1s")
223
+ lines.append(" * 🔴 > 1s")
224
+ return "\n".join(lines)
225
+
226
+
227
+ def update_readme(readme_path: Path, results_table: str) -> None:
228
+ """Update the README.md with benchmark results."""
229
+ marker_start = "<!-- BENCHMARK_RESULTS_START -->"
230
+ marker_end = "<!-- BENCHMARK_RESULTS_END -->"
231
+
232
+ if not readme_path.exists():
233
+ # Create a new README with results
234
+ content = f"# Advent of Code\n\n## Benchmark Results\n\n{marker_start}\n{results_table}\n{marker_end}\n"
235
+ readme_path.write_text(content)
236
+ console.log(f"Created {readme_path} with benchmark results")
237
+ return
238
+
239
+ content = readme_path.read_text()
240
+
241
+ if marker_start in content and marker_end in content:
242
+ # Replace existing results
243
+ pattern = re.compile(re.escape(marker_start) + r".*?" + re.escape(marker_end), re.DOTALL)
244
+ new_section = f"{marker_start}\n{results_table}\n{marker_end}"
245
+ content = pattern.sub(new_section, content)
246
+ else:
247
+ # Append results section
248
+ content += f"\n## Benchmark Results\n\n{marker_start}\n{results_table}\n{marker_end}\n"
249
+
250
+ readme_path.write_text(content)
251
+ console.log(f"Updated {readme_path} with benchmark results")
252
+
253
+
254
+ def console_color(formatted_time: str, color: Color) -> str:
255
+ return f"[{color}]{formatted_time}[/{color}]"
256
+
257
+
258
+ def markdown_color(formatted_time: str, color: Color) -> str:
259
+ if color == "white":
260
+ return formatted_time
261
+ elif color == "green":
262
+ return f"{formatted_time} 🟢"
263
+ elif color == "yellow":
264
+ return f"{formatted_time} 🟡"
265
+ else:
266
+ return f"{formatted_time} 🔴"
267
+
268
+
269
+ def build_console_table(
270
+ results: list[DayResult], current_running: str | None, total_part_1: float, total_part_2: float, total_time: float
271
+ ) -> Table:
272
+ table = Table(title="Advent of Code Benchmarks")
273
+ table.add_column("Day", style="cyan", justify="right")
274
+ table.add_column("Status", justify="center")
275
+ table.add_column("Part 1", justify="right")
276
+ table.add_column("Part 2", justify="right")
277
+ table.add_column("Total", justify="right")
278
+
279
+ for r in results:
280
+ p1_time = console_color(format_time(r.part1_time), time_to_color(r.part1_time))
281
+ p2_time = console_color(format_time(r.part2_time), time_to_color(r.part2_time))
282
+ total = console_color(format_time(r.total_time), time_to_color(r.total_time))
283
+ status = r.status
284
+ table.add_row(r.day, status, p1_time, p2_time, total)
285
+
286
+ if current_running is not None:
287
+ table.add_row(str(current_running), "⏳", "...", "...", "...")
288
+
289
+ table.add_row(
290
+ "Total",
291
+ "",
292
+ console_color(format_time(total_part_1), time_to_color(total_part_1)),
293
+ console_color(format_time(total_part_2), time_to_color(total_part_2)),
294
+ console_color(format_time(total_time), time_to_color(total_time)),
295
+ )
296
+ return table
297
+
298
+
299
+ def run_benchmark(directory: Path) -> None:
300
+ console.log("[bold]Running benchmarks for Advent of Code[/bold]\n")
301
+
302
+ # Find all day files
303
+ day_files = sorted(directory.glob("[0-9][0-9].py"))
304
+ if not day_files:
305
+ console.log("[yellow]No day files found[/yellow]")
306
+ return
307
+
308
+ results: list[DayResult] = []
309
+ total_time = 0.0
310
+ total_part_1 = 0.0
311
+ total_part_2 = 0.0
312
+
313
+ with Live(
314
+ build_console_table(
315
+ results=[],
316
+ current_running=None,
317
+ total_part_1=0.0,
318
+ total_part_2=0.0,
319
+ total_time=0.0,
320
+ ),
321
+ console=console,
322
+ refresh_per_second=4,
323
+ ) as live:
324
+ for filepath in day_files:
325
+ live.update(
326
+ build_console_table(
327
+ results=results,
328
+ current_running=filepath.stem,
329
+ total_part_1=total_part_1,
330
+ total_part_2=total_part_2,
331
+ total_time=total_time,
332
+ )
333
+ )
334
+ result = run_day(filepath)
335
+ results.append(result)
336
+
337
+ total_part_1 += result.part1_time
338
+ total_part_2 += result.part2_time
339
+ total_time += result.total_time
340
+
341
+ live.update(
342
+ build_console_table(
343
+ results=results,
344
+ current_running=None,
345
+ total_part_1=total_part_1,
346
+ total_part_2=total_part_2,
347
+ total_time=total_time,
348
+ )
349
+ )
350
+
351
+ readme_path = directory / "README.md"
352
+ results_table = build_markdown_table(
353
+ results, total_time=total_time, total_part_1=total_part_1, total_part_2=total_part_2
354
+ )
355
+ update_readme(readme_path, results_table)
356
+
357
+
78
358
  def main() -> None:
79
359
  """Main entry point for the CLI."""
80
360
  parser = argparse.ArgumentParser(
@@ -110,8 +390,39 @@ def main() -> None:
110
390
  "-y",
111
391
  "--year",
112
392
  type=int,
113
- default=datetime.datetime.now(tz=datetime.timezone.utc).year,
114
- help="Year to generate templates for (default: current year)",
393
+ default=AOC_YEAR,
394
+ help="Year to generate templates for (default: AOC_YEAR env variable or current year)",
395
+ )
396
+
397
+ # Benchmark command
398
+ benchmark_parser = subparsers.add_parser(
399
+ "benchmark",
400
+ help="Run all days and generate benchmark results",
401
+ description=("Run all day solutions, measure execution times, and update the README with a benchmark table."),
402
+ formatter_class=argparse.RawDescriptionHelpFormatter,
403
+ epilog=dedent("""\
404
+ Examples:
405
+ adventofcode benchmark # Run benchmarks in current directory
406
+ adventofcode benchmark ./2024 # Run benchmarks in the ./2024 directory
407
+
408
+ The benchmark will:
409
+ 1. Find all day files (01.py, 02.py, etc.)
410
+ 2. Run each day script (python 01.py, etc.)
411
+ 3. Parse execution times from the output
412
+ 4. Display a live-updating table in the console
413
+ 5. Update README.md with a benchmark results table
414
+
415
+ Note: Each day script must complete successfully (exit code 0)
416
+ to be marked as passing. The timing is parsed from the AoC
417
+ class output (e.g., "0.00123s for submit_p1").
418
+ """),
419
+ )
420
+ benchmark_parser.add_argument(
421
+ "directory",
422
+ type=Path,
423
+ nargs="?",
424
+ default=Path("."),
425
+ help="Directory containing day files (default: current directory)",
115
426
  )
116
427
 
117
428
  args = parser.parse_args()
@@ -119,6 +430,8 @@ def main() -> None:
119
430
  match args.command:
120
431
  case "init":
121
432
  generate_templates(args.year, args.directory, 12 if args.year >= 2025 else 25)
433
+ case "benchmark":
434
+ run_benchmark(args.directory)
122
435
  case _:
123
436
  parser.print_help()
124
437
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: adventofcode
3
- Version: 25.0
3
+ Version: 25.1
4
4
  Summary: Helper utilities for solving Advent of Code puzzles
5
5
  Project-URL: Documentation, https://github.com/anze3db/adventofcode#readme
6
6
  Project-URL: Issues, https://github.com/anze3db/adventofcode/issues
@@ -0,0 +1,8 @@
1
+ adventofcode/__about__.py,sha256=dvZ1v7S_ZALQJCbVXidP8uGGCco3DKNk4N53UWAklLI,21
2
+ adventofcode/__init__.py,sha256=OqMPnvRc5pcDWMDM4zjwCm4nsOdBohB_1ZSmJz3bXP0,4462
3
+ adventofcode/cli.py,sha256=-y1uIExMoGr0DnAZAgfX45QyAIEFBj1E0koANByyPMs,14439
4
+ adventofcode-25.1.dist-info/METADATA,sha256=OVxHtPDozKsrTR7rtUdBFb0aU8YjVh9a-xj1LAQmSbg,3708
5
+ adventofcode-25.1.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
6
+ adventofcode-25.1.dist-info/entry_points.txt,sha256=Yw9pyDrVVS3XWRcjOv1BnAxkqtJdYoG747A1LysScak,83
7
+ adventofcode-25.1.dist-info/licenses/LICENSE,sha256=7w16SgIHVGYHh8TS_-XnKFvY6aKa_JDtVFoduWtIPTY,1069
8
+ adventofcode-25.1.dist-info/RECORD,,
@@ -1,8 +0,0 @@
1
- adventofcode/__about__.py,sha256=uFk-qsH3qMJ8WiSqopyKngOm1O1YIY_4NMRdGUTdTlg,21
2
- adventofcode/__init__.py,sha256=06BKcDNoqtpbfaW4PVo5cFbCDu05Se_r3RSorFUS8UA,4362
3
- adventofcode/cli.py,sha256=cdpCJm_pLd9E683rhi5Wj34bPx91A8LKY88pgOPq1dg,4074
4
- adventofcode-25.0.dist-info/METADATA,sha256=KUH8kCvlqpvDcdD5cs-qMNeN_rZFO2yHZwZLatkM5bs,3708
5
- adventofcode-25.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
6
- adventofcode-25.0.dist-info/entry_points.txt,sha256=Yw9pyDrVVS3XWRcjOv1BnAxkqtJdYoG747A1LysScak,83
7
- adventofcode-25.0.dist-info/licenses/LICENSE,sha256=7w16SgIHVGYHh8TS_-XnKFvY6aKa_JDtVFoduWtIPTY,1069
8
- adventofcode-25.0.dist-info/RECORD,,