adventofcode 25.0__tar.gz → 25.1__tar.gz

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.
@@ -0,0 +1,72 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Calendar Versioning](https://calver.org).
7
+
8
+ ## [25.1]
9
+
10
+ ### Added
11
+
12
+ * `adventofcode benchmark` command that generates benchmark results both in the console and in the README. Example README:
13
+
14
+
15
+ | Day | Status | Part 1 Time | Part 2 Time | Total Time |
16
+ |:---:|:------:|------------:|------------:|-----------:|
17
+ | 01 | ✅ | 2.1ms 🟢 | 0.6ms 🟢 | 2.6ms 🟢 |
18
+ | 02 | ✅ | 1.9ms 🟢 | 1.2ms 🟢 | 3.1ms 🟢 |
19
+ | 03 | ✅ | 1.5ms 🟢 | 0.5ms 🟢 | 2.0ms 🟢 |
20
+ | 04 | ✅ | 22.5ms 🟢 | 5.2ms 🟢 | 27.8ms 🟢 |
21
+ | 05 | ✅ | 3.6ms 🟢 | 4.1ms 🟢 | 7.7ms 🟢 |
22
+ | 06 | ✅ | 3.6ms 🟢 | 4.14s 🔴 | 4.14s 🔴 |
23
+ | 07 | ✅ | 33.8ms 🟢 | 1.07s 🔴 | 1.11s 🔴 |
24
+ | 08 | ✅ | 1.0ms 🟢 | 0.7ms 🟢 | 1.7ms 🟢 |
25
+ | 09 | ✅ | 6.3ms 🟢 | 1.08s 🔴 | 1.09s 🔴 |
26
+ | 10 | ✅ | 3.2ms 🟢 | 3.2ms 🟢 | 6.4ms 🟢 |
27
+ | 11 | ✅ | 1.7ms 🟢 | 45.0ms 🟢 | 46.7ms 🟢 |
28
+ | 12 | ✅ | 33.3ms 🟢 | 31.0ms 🟢 | 64.4ms 🟢 |
29
+ | 13 | ✅ | 118.1ms 🟡 | 360.8ms 🟡 | 478.9ms 🟡 |
30
+ | 14 | ✅ | 3.7ms 🟢 | 411.4ms 🟡 | 415.1ms 🟡 |
31
+ | 15 | ✅ | 3.5ms 🟢 | 5.0ms 🟢 | 8.4ms 🟢 |
32
+ | 16 | ✅ | 87.1ms 🟢 | 133.9ms 🟡 | 221.1ms 🟡 |
33
+ | 17 | ✅ | 0.7ms 🟢 | 21.0ms 🟢 | 21.7ms 🟢 |
34
+ | 18 | ✅ | 7.2ms 🟢 | 7.49s 🔴 | 7.50s 🔴 |
35
+ | 19 | ✅ | 9.7ms 🟢 | 111.7ms 🟡 | 121.4ms 🟡 |
36
+ | 20 | ✅ | 50.54s 🔴 | 4.46s 🔴 | 54.99s 🔴 |
37
+ | 21 | ✅ | 0.4ms 🟢 | 0.3ms 🟢 | 0.8ms 🟢 |
38
+ | 22 | ✅ | 603.7ms 🟡 | 1.90s 🔴 | 2.50s 🔴 |
39
+ | 23 | ✅ | 255.0ms 🟡 | 263.4ms 🟡 | 518.4ms 🟡 |
40
+ | 24 | ⚠️ | 1.4ms 🟢 | - | 1.4ms 🟢 |
41
+ | 25 | ✅ | 7.2ms 🟢 | - | 7.2ms 🟢 |
42
+ | **Total** | | 51.75s 🔴 | 21.53s 🔴 | 73.28s 🔴 |
43
+
44
+ Legend:
45
+ * 🟢 < 100ms
46
+ * 🟡 100ms - 1s
47
+ * 🔴 > 1s
48
+
49
+ ## [25.0]
50
+
51
+ ### Added
52
+
53
+ * Command line tool for scaffolding all the days (`adventofcode init`)
54
+ * Support for Python 3.13 and 3.14
55
+
56
+ ### Removed
57
+
58
+ * `part_1_no_splitlines` and `part_2_no_splitlines` parameters. `part_1` and `part_2` now receive a `str` instead of `list[str]`. This was done to simplify the API.
59
+ * Support for Python 3.8 and 3.9
60
+
61
+ ## [23.0b1]
62
+
63
+ ### Added
64
+
65
+ * `assert_p1` and `assert_p2` methods to `AoC` class. Used for easily asserting your solutions against sample inputs.
66
+ * `part_1`, `part_2` optional arguments to the `AoC` class. Used to pass in a Callable that will return the correct result for the given input. The callable will be called by `assert_p1`, `assert_p2`, `submit_p1` and `submit_p2` methods.
67
+ * `part_1_no_splitlines` and `part_2_no_splitlines` optional arguments to `AoC` class. Used as an alternative to `part_1` and `part_2` for the rare cases when the input should not be split into lines.
68
+
69
+
70
+ ## [2023.0b0] - 2023-12-07
71
+
72
+ Initial release
@@ -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 @@
1
+ __version__ = "25.1"
@@ -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 "
@@ -0,0 +1,440 @@
1
+ import argparse
2
+ import datetime
3
+ import os
4
+ import re
5
+ import subprocess
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from textwrap import dedent
10
+ from typing import Literal
11
+
12
+ from dotenv import load_dotenv
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)))
23
+
24
+ console = Console()
25
+ TEMPLATE = dedent('''\
26
+ from adventofcode import AoC
27
+
28
+
29
+ def part1(inp: str) -> str | int | None:
30
+ return None
31
+
32
+
33
+ def part2(inp: str) -> str | int | None:
34
+ return None
35
+
36
+
37
+ aoc = AoC(part_1=part1, part_2=part2)
38
+ inp = """sample input"""
39
+ expected_result = None
40
+ aoc.assert_p1(inp, expected_result)
41
+ aoc.submit_p1()
42
+
43
+ expected_result = None
44
+ aoc.assert_p2(inp, expected_result)
45
+ aoc.submit_p2()
46
+ ''')
47
+
48
+
49
+ def generate_templates(year: int, output_dir: Path, num_days: int) -> None:
50
+ """Generate template files for the specified year."""
51
+ output_dir.mkdir(parents=True, exist_ok=True)
52
+
53
+ console.log(f"Generating templates for Advent of Code {year}")
54
+
55
+ for day in range(1, num_days + 1):
56
+ filename = f"{day:02d}.py"
57
+ filepath = output_dir / filename
58
+
59
+ if filepath.exists():
60
+ console.log(f"Skipping {filename} (already exists)")
61
+ continue
62
+
63
+ filepath.write_text(TEMPLATE)
64
+ console.log(f"Created {filename}")
65
+
66
+ gitignore_path = output_dir / ".gitignore"
67
+ if gitignore_path.exists():
68
+ gitignore_content = gitignore_path.read_text()
69
+ if ".cache" not in gitignore_content:
70
+ with gitignore_path.open("a") as f:
71
+ if not gitignore_content.endswith("\n"):
72
+ f.write("\n")
73
+ f.write(".cache\n")
74
+ console.log("Added .cache to .gitignore")
75
+ if ".env" not in gitignore_content:
76
+ with gitignore_path.open("a") as f:
77
+ if not gitignore_content.endswith("\n"):
78
+ f.write("\n")
79
+ f.write(".env\n")
80
+ console.log("Added .env to .gitignore")
81
+
82
+ env_path = output_dir / ".env"
83
+ if not env_path.exists():
84
+ env_path.write_text(
85
+ "# Set your Advent of Code session cookie below\n"
86
+ "# You can find it in your browser's developer tools after logging in to adventofcode.com. \n"
87
+ "# The name of the cookie is `session`.\n"
88
+ 'AOC_SESSION=""\n'
89
+ f"AOC_YEAR={year}\n"
90
+ )
91
+ console.log("Created .env file (remember to set your AOC_SESSION)")
92
+
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
+
358
+ def main() -> None:
359
+ """Main entry point for the CLI."""
360
+ parser = argparse.ArgumentParser(
361
+ prog="adventofcode",
362
+ description="Helper utilities for solving Advent of Code puzzles",
363
+ )
364
+ subparsers = parser.add_subparsers(dest="command", help="Available commands")
365
+
366
+ # Init command
367
+ init_parser = subparsers.add_parser(
368
+ "init",
369
+ help="Initialize template files for Advent of Code",
370
+ description=(
371
+ "Initialize all template files for a given year. "
372
+ "Creates one Python file per day with boilerplate code for solving puzzles."
373
+ ),
374
+ formatter_class=argparse.RawDescriptionHelpFormatter,
375
+ epilog=dedent("""\
376
+ Examples:
377
+ adventofcode init # Initialize templates for the current year in current directory
378
+ adventofcode init --year 2023 # Initialize templates for 2023 in the current directory
379
+ adventofcode init --year 2024 ./2024 # Initialize templates for 2024 in the ./2024 directory
380
+ """),
381
+ )
382
+ init_parser.add_argument(
383
+ "directory",
384
+ type=Path,
385
+ nargs="?",
386
+ default=Path("."),
387
+ help="Directory for generated files (default: current directory)",
388
+ )
389
+ init_parser.add_argument(
390
+ "-y",
391
+ "--year",
392
+ type=int,
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)",
426
+ )
427
+
428
+ args = parser.parse_args()
429
+
430
+ match args.command:
431
+ case "init":
432
+ generate_templates(args.year, args.directory, 12 if args.year >= 2025 else 25)
433
+ case "benchmark":
434
+ run_benchmark(args.directory)
435
+ case _:
436
+ parser.print_help()
437
+
438
+
439
+ if __name__ == "__main__":
440
+ main()
@@ -1,31 +0,0 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
-
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
- and this project adheres to [Calendar Versioning](https://calver.org).
7
-
8
- ## [25.0]
9
-
10
- ### Added
11
-
12
- * Command line tool for scaffolding all the days (`adventofcode init`)
13
- * Support for Python 3.13 and 3.14
14
-
15
- ### Removed
16
-
17
- * `part_1_no_splitlines` and `part_2_no_splitlines` parameters. `part_1` and `part_2` now receive a `str` instead of `list[str]`. This was done to simplify the API.
18
- * Support for Python 3.8 and 3.9
19
-
20
- ## [23.0b1]
21
-
22
- ### Added
23
-
24
- * `assert_p1` and `assert_p2` methods to `AoC` class. Used for easily asserting your solutions against sample inputs.
25
- * `part_1`, `part_2` optional arguments to the `AoC` class. Used to pass in a Callable that will return the correct result for the given input. The callable will be called by `assert_p1`, `assert_p2`, `submit_p1` and `submit_p2` methods.
26
- * `part_1_no_splitlines` and `part_2_no_splitlines` optional arguments to `AoC` class. Used as an alternative to `part_1` and `part_2` for the rare cases when the input should not be split into lines.
27
-
28
-
29
- ## [2023.0b0] - 2023-12-07
30
-
31
- Initial release
@@ -1 +0,0 @@
1
- __version__ = "25.0"
@@ -1,127 +0,0 @@
1
- import argparse
2
- import datetime
3
- from pathlib import Path
4
- from textwrap import dedent
5
-
6
- from rich.console import Console
7
-
8
- console = Console()
9
- TEMPLATE = dedent('''\
10
- from adventofcode import AoC
11
-
12
-
13
- def part1(inp: str) -> str | int | None:
14
- return None
15
-
16
-
17
- def part2(inp: str) -> str | int | None:
18
- return None
19
-
20
-
21
- aoc = AoC(part_1=part1, part_2=part2)
22
- inp = """sample input"""
23
- expected_result = None
24
- aoc.assert_p1(inp, expected_result)
25
- aoc.submit_p1()
26
-
27
- expected_result = None
28
- aoc.assert_p2(inp, expected_result)
29
- aoc.submit_p2()
30
- ''')
31
-
32
-
33
- def generate_templates(year: int, output_dir: Path, num_days: int) -> None:
34
- """Generate template files for the specified year."""
35
- output_dir.mkdir(parents=True, exist_ok=True)
36
-
37
- console.log(f"Generating templates for Advent of Code {year}")
38
-
39
- for day in range(1, num_days + 1):
40
- filename = f"{day:02d}.py"
41
- filepath = output_dir / filename
42
-
43
- if filepath.exists():
44
- console.log(f"Skipping {filename} (already exists)")
45
- continue
46
-
47
- filepath.write_text(TEMPLATE)
48
- console.log(f"Created {filename}")
49
-
50
- gitignore_path = output_dir / ".gitignore"
51
- if gitignore_path.exists():
52
- gitignore_content = gitignore_path.read_text()
53
- if ".cache" not in gitignore_content:
54
- with gitignore_path.open("a") as f:
55
- if not gitignore_content.endswith("\n"):
56
- f.write("\n")
57
- f.write(".cache\n")
58
- console.log("Added .cache to .gitignore")
59
- if ".env" not in gitignore_content:
60
- with gitignore_path.open("a") as f:
61
- if not gitignore_content.endswith("\n"):
62
- f.write("\n")
63
- f.write(".env\n")
64
- console.log("Added .env to .gitignore")
65
-
66
- env_path = output_dir / ".env"
67
- if not env_path.exists():
68
- env_path.write_text(
69
- "# Set your Advent of Code session cookie below\n"
70
- "# You can find it in your browser's developer tools after logging in to adventofcode.com. \n"
71
- "# The name of the cookie is `session`.\n"
72
- 'AOC_SESSION=""\n'
73
- f"AOC_YEAR={year}\n"
74
- )
75
- console.log("Created .env file (remember to set your AOC_SESSION)")
76
-
77
-
78
- def main() -> None:
79
- """Main entry point for the CLI."""
80
- parser = argparse.ArgumentParser(
81
- prog="adventofcode",
82
- description="Helper utilities for solving Advent of Code puzzles",
83
- )
84
- subparsers = parser.add_subparsers(dest="command", help="Available commands")
85
-
86
- # Init command
87
- init_parser = subparsers.add_parser(
88
- "init",
89
- help="Initialize template files for Advent of Code",
90
- description=(
91
- "Initialize all template files for a given year. "
92
- "Creates one Python file per day with boilerplate code for solving puzzles."
93
- ),
94
- formatter_class=argparse.RawDescriptionHelpFormatter,
95
- epilog=dedent("""\
96
- Examples:
97
- adventofcode init # Initialize templates for the current year in current directory
98
- adventofcode init --year 2023 # Initialize templates for 2023 in the current directory
99
- adventofcode init --year 2024 ./2024 # Initialize templates for 2024 in the ./2024 directory
100
- """),
101
- )
102
- init_parser.add_argument(
103
- "directory",
104
- type=Path,
105
- nargs="?",
106
- default=Path("."),
107
- help="Directory for generated files (default: current directory)",
108
- )
109
- init_parser.add_argument(
110
- "-y",
111
- "--year",
112
- type=int,
113
- default=datetime.datetime.now(tz=datetime.timezone.utc).year,
114
- help="Year to generate templates for (default: current year)",
115
- )
116
-
117
- args = parser.parse_args()
118
-
119
- match args.command:
120
- case "init":
121
- generate_templates(args.year, args.directory, 12 if args.year >= 2025 else 25)
122
- case _:
123
- parser.print_help()
124
-
125
-
126
- if __name__ == "__main__":
127
- main()
File without changes
File without changes
File without changes
File without changes
File without changes