adventofcode 23.0b1__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.
@@ -13,7 +13,7 @@ jobs:
13
13
  runs-on: ubuntu-latest
14
14
  strategy:
15
15
  matrix:
16
- python-version: ["3.12"]
16
+ python-version: ["3.14"]
17
17
 
18
18
  environment: release
19
19
  permissions:
@@ -2,7 +2,7 @@
2
2
  # See https://pre-commit.com/hooks.html for more hooks
3
3
  repos:
4
4
  - repo: https://github.com/pre-commit/pre-commit-hooks
5
- rev: v4.5.0
5
+ rev: v6.0.0
6
6
  hooks:
7
7
  - id: trailing-whitespace
8
8
  - id: end-of-file-fixer
@@ -10,7 +10,7 @@ repos:
10
10
  - id: check-added-large-files
11
11
  - repo: https://github.com/astral-sh/ruff-pre-commit
12
12
  # Ruff version.
13
- rev: v0.1.7
13
+ rev: v0.14.6
14
14
  hooks:
15
15
  - id: ruff
16
16
  - id: ruff-format
@@ -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
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: adventofcode
3
- Version: 23.0b1
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
@@ -12,14 +12,14 @@ License-Expression: MIT
12
12
  License-File: LICENSE
13
13
  Classifier: Development Status :: 4 - Beta
14
14
  Classifier: Programming Language :: Python
15
- Classifier: Programming Language :: Python :: 3.8
16
- Classifier: Programming Language :: Python :: 3.9
17
15
  Classifier: Programming Language :: Python :: 3.10
18
16
  Classifier: Programming Language :: Python :: 3.11
19
17
  Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
20
  Classifier: Programming Language :: Python :: Implementation :: CPython
21
21
  Classifier: Programming Language :: Python :: Implementation :: PyPy
22
- Requires-Python: >=3.8
22
+ Requires-Python: >=3.10
23
23
  Requires-Dist: beautifulsoup4
24
24
  Requires-Dist: percache
25
25
  Requires-Dist: python-dotenv
@@ -31,64 +31,89 @@ Description-Content-Type: text/markdown
31
31
 
32
32
  Helper utilities for solving Advent of Code puzzles.
33
33
 
34
+ * Project scaffolding with `adventofcode init`
34
35
  * No copy-pasting puzzle inputs into files.
35
36
  * No need to use low-level file APIs to read your inputs.
36
37
  * Performance reports for example inputs and puzzle inputs.
37
- * Submit the answer immediately when your code returns the result 🏎️
38
+ * Submit the answer immediately when your code returns the result 🏅
38
39
 
39
40
  ## Usage
40
41
 
41
- ### Install the package
42
+ ### Setup
42
43
 
43
- Install the package with pip:
44
44
  ```bash
45
- pip install adventofcode
45
+ uv init
46
+ uv add adventofcode
47
+ adventofcode init
46
48
  ```
47
49
 
48
- ### Set your session cookie
49
-
50
- Add the [adventofcode.com](https://adventofcode.com) session cookie value to your env:
50
+ This will generate the scripts for each day:
51
51
 
52
52
  ```bash
53
- export AOC_SESSION="..."
53
+ .
54
+ ├── 01.py
55
+ ├── 02.py
56
+ ├── 03.py
57
+ ├── 04.py
58
+ ├── 05.py
59
+ ├── 06.py
60
+ ├── 07.py
61
+ ├── 08.py
62
+ ├── 09.py
63
+ ├── 10.py
64
+ ├── 11.py
65
+ ├── 12.py
66
+ ├── main.py
67
+ ├── pyproject.toml
68
+ ├── README.md
69
+ └── uv.lock
70
+
71
+ 1 directory, 16 files
54
72
  ```
55
73
 
56
- Alternatively, you can save your `AOC_SESSION="******"` value in a `.env` file.
57
-
58
- > [!NOTE]
59
- > Setting AOC_SESSION will allow you to get your personal puzzle output (`aoc.get_input()`) and submit your answers with `aoc.submit_p1()` and `aoc.submit_p2()`.
60
-
61
- ### Use a template to solve puzzles
62
-
63
- I use the following template to start solving puzzles, see my examples in [my repo for 2023](https://github.com/anze3db/adventofcode2023).
74
+ All the py files look like this:
64
75
 
65
76
  ```python
66
77
  from adventofcode import AoC
67
78
 
68
79
 
69
- def part1(inp):
80
+ def part1(inp: str):
70
81
  return None
71
82
 
72
83
 
73
- def part2(inp):
84
+ def part2(inp: str):
74
85
  return None
75
86
 
76
87
 
77
88
  aoc = AoC(part_1=part1, part_2=part2)
78
89
  inp = """sample input"""
79
- # Run your part1 function with sample input and assert the expected result:
80
- aoc.assert_p1(inp, 42)
81
- # Run your part1 function on puzzle input and submit the answer returned:
90
+ expected_result = None
91
+ aoc.assert_p1(inp, expected_result)
82
92
  aoc.submit_p1()
83
93
 
84
- # Run your part2 function with sample input and assert the expected result:
85
- aoc.assert_p2(inp, 6*7)
86
- # Run your part2 function on puzzle input and submit the answer returned:
94
+ expected_result = None
95
+ aoc.assert_p2(inp, expected_result)
87
96
  aoc.submit_p2()
88
97
  ```
89
98
 
99
+ You write your solution in part1 and part2 functions.
100
+
101
+ `aoc.assert_p1(inp, expected_result)` will call your part1 function with inp and assert that the return matches expected_result.
102
+
103
+ `aoc.submit_p1()` will fetch your puzzle input from the adventofcode.com, cache it locally and call `part1` with your puzzle input. If `part1` returns a value that isn't `None` that value will be submitted as your puzzle answer.
104
+
105
+
106
+ ### Set your session cookie
107
+
108
+ Add the [adventofcode.com](https://adventofcode.com) session cookie value to your `.env` file or to your active session:
109
+
110
+ ```bash
111
+ export AOC_SESSION="..."
112
+ ```
113
+
90
114
  > [!NOTE]
91
- > All submissions and fetched results are cached locally in the `.cache.db` file so that we don't spam the AoC servers or resubmit the same answer multiple times.
115
+ > Setting AOC_SESSION will allow you to get your personal puzzle output (`aoc.get_input()`) and submit your answers with `aoc.submit_p1()` and `aoc.submit_p2()`.
116
+
92
117
 
93
118
  ### Or build your workflow using the AoC class
94
119
 
@@ -2,64 +2,89 @@
2
2
 
3
3
  Helper utilities for solving Advent of Code puzzles.
4
4
 
5
+ * Project scaffolding with `adventofcode init`
5
6
  * No copy-pasting puzzle inputs into files.
6
7
  * No need to use low-level file APIs to read your inputs.
7
8
  * Performance reports for example inputs and puzzle inputs.
8
- * Submit the answer immediately when your code returns the result 🏎️
9
+ * Submit the answer immediately when your code returns the result 🏅
9
10
 
10
11
  ## Usage
11
12
 
12
- ### Install the package
13
+ ### Setup
13
14
 
14
- Install the package with pip:
15
15
  ```bash
16
- pip install adventofcode
16
+ uv init
17
+ uv add adventofcode
18
+ adventofcode init
17
19
  ```
18
20
 
19
- ### Set your session cookie
20
-
21
- Add the [adventofcode.com](https://adventofcode.com) session cookie value to your env:
21
+ This will generate the scripts for each day:
22
22
 
23
23
  ```bash
24
- export AOC_SESSION="..."
24
+ .
25
+ ├── 01.py
26
+ ├── 02.py
27
+ ├── 03.py
28
+ ├── 04.py
29
+ ├── 05.py
30
+ ├── 06.py
31
+ ├── 07.py
32
+ ├── 08.py
33
+ ├── 09.py
34
+ ├── 10.py
35
+ ├── 11.py
36
+ ├── 12.py
37
+ ├── main.py
38
+ ├── pyproject.toml
39
+ ├── README.md
40
+ └── uv.lock
41
+
42
+ 1 directory, 16 files
25
43
  ```
26
44
 
27
- Alternatively, you can save your `AOC_SESSION="******"` value in a `.env` file.
28
-
29
- > [!NOTE]
30
- > Setting AOC_SESSION will allow you to get your personal puzzle output (`aoc.get_input()`) and submit your answers with `aoc.submit_p1()` and `aoc.submit_p2()`.
31
-
32
- ### Use a template to solve puzzles
33
-
34
- I use the following template to start solving puzzles, see my examples in [my repo for 2023](https://github.com/anze3db/adventofcode2023).
45
+ All the py files look like this:
35
46
 
36
47
  ```python
37
48
  from adventofcode import AoC
38
49
 
39
50
 
40
- def part1(inp):
51
+ def part1(inp: str):
41
52
  return None
42
53
 
43
54
 
44
- def part2(inp):
55
+ def part2(inp: str):
45
56
  return None
46
57
 
47
58
 
48
59
  aoc = AoC(part_1=part1, part_2=part2)
49
60
  inp = """sample input"""
50
- # Run your part1 function with sample input and assert the expected result:
51
- aoc.assert_p1(inp, 42)
52
- # Run your part1 function on puzzle input and submit the answer returned:
61
+ expected_result = None
62
+ aoc.assert_p1(inp, expected_result)
53
63
  aoc.submit_p1()
54
64
 
55
- # Run your part2 function with sample input and assert the expected result:
56
- aoc.assert_p2(inp, 6*7)
57
- # Run your part2 function on puzzle input and submit the answer returned:
65
+ expected_result = None
66
+ aoc.assert_p2(inp, expected_result)
58
67
  aoc.submit_p2()
59
68
  ```
60
69
 
70
+ You write your solution in part1 and part2 functions.
71
+
72
+ `aoc.assert_p1(inp, expected_result)` will call your part1 function with inp and assert that the return matches expected_result.
73
+
74
+ `aoc.submit_p1()` will fetch your puzzle input from the adventofcode.com, cache it locally and call `part1` with your puzzle input. If `part1` returns a value that isn't `None` that value will be submitted as your puzzle answer.
75
+
76
+
77
+ ### Set your session cookie
78
+
79
+ Add the [adventofcode.com](https://adventofcode.com) session cookie value to your `.env` file or to your active session:
80
+
81
+ ```bash
82
+ export AOC_SESSION="..."
83
+ ```
84
+
61
85
  > [!NOTE]
62
- > All submissions and fetched results are cached locally in the `.cache.db` file so that we don't spam the AoC servers or resubmit the same answer multiple times.
86
+ > Setting AOC_SESSION will allow you to get your personal puzzle output (`aoc.get_input()`) and submit your answers with `aoc.submit_p1()` and `aoc.submit_p2()`.
87
+
63
88
 
64
89
  ### Or build your workflow using the AoC class
65
90
 
@@ -7,7 +7,7 @@ name = "adventofcode"
7
7
  dynamic = ["version"]
8
8
  description = 'Helper utilities for solving Advent of Code puzzles'
9
9
  readme = "README.md"
10
- requires-python = ">=3.8"
10
+ requires-python = ">=3.10"
11
11
  license = "MIT"
12
12
  keywords = []
13
13
  authors = [
@@ -16,11 +16,11 @@ authors = [
16
16
  classifiers = [
17
17
  "Development Status :: 4 - Beta",
18
18
  "Programming Language :: Python",
19
- "Programming Language :: Python :: 3.8",
20
- "Programming Language :: Python :: 3.9",
21
19
  "Programming Language :: Python :: 3.10",
22
20
  "Programming Language :: Python :: 3.11",
23
21
  "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
24
  "Programming Language :: Python :: Implementation :: CPython",
25
25
  "Programming Language :: Python :: Implementation :: PyPy",
26
26
  ]
@@ -39,6 +39,10 @@ Source = "https://github.com/anze3db/adventofcode"
39
39
  Mastodon = "https://fosstodon.org/@anze3db"
40
40
  Twitter = "https://twitter.com/anze3db"
41
41
 
42
+ [project.scripts]
43
+ adventofcode = "adventofcode.cli:main"
44
+ aoc = "adventofcode.cli:main"
45
+
42
46
  [tool.hatch.version]
43
47
  path = "src/adventofcode/__about__.py"
44
48
 
@@ -61,7 +65,7 @@ cov = [
61
65
  ]
62
66
 
63
67
  [[tool.hatch.envs.all.matrix]]
64
- python = ["3.8", "3.9", "3.10", "3.11", "3.12"]
68
+ python = ["3.10", "3.11", "3.12", "3.13", "3.14"]
65
69
 
66
70
  [tool.hatch.envs.lint]
67
71
  detached = true
@@ -85,7 +89,7 @@ all = [
85
89
  ]
86
90
 
87
91
  [tool.ruff]
88
- target-version = "py38"
92
+ target-version = "py310"
89
93
  line-length = 120
90
94
  select = [
91
95
  "A",
@@ -0,0 +1 @@
1
+ __version__ = "25.1"
@@ -3,9 +3,10 @@ import os
3
3
  import re
4
4
  import sys
5
5
  import time
6
+ from collections.abc import Callable
6
7
  from contextlib import contextmanager
7
8
  from pathlib import Path
8
- from typing import Any, Callable
9
+ from typing import Any
9
10
 
10
11
  import percache
11
12
  import requests
@@ -13,7 +14,7 @@ from bs4 import BeautifulSoup
13
14
  from dotenv import load_dotenv
14
15
  from rich.console import Console
15
16
 
16
- load_dotenv()
17
+ load_dotenv(Path(".env").absolute().as_posix())
17
18
  cache = percache.Cache(".cache", livesync=True)
18
19
  console = Console()
19
20
 
@@ -21,9 +22,14 @@ AOC_URL = "https://adventofcode.com"
21
22
 
22
23
 
23
24
  AOC_SESSION = os.getenv("AOC_SESSION")
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)))
24
29
 
25
30
  AOC_NOT_SET_MSG = (
26
- "Set AOC_SESSION env variable to your session cookie on adventofcode.com (export AOC_SESSION='your session cookie')"
31
+ "Set AOC_SESSION to your `session` cookie on adventofcode.com. You can add it to your .env file or "
32
+ "export it in your shell (export AOC_SESSION='your session cookie')"
27
33
  )
28
34
 
29
35
 
@@ -38,28 +44,24 @@ def print_perf(typ=""):
38
44
  class AoC:
39
45
  def __init__(
40
46
  self,
47
+ part_1: Callable[[str], str | int | None],
48
+ part_2: Callable[[str], str | int | None],
49
+ *,
41
50
  day: int | None = None,
42
51
  year: int | None = None,
43
- *,
44
- part_1: Callable[[list[str]], Any] | None = None,
45
- part_2: Callable[[list[str]], Any] | None = None,
46
- part_1_no_splitlines: Callable[[str], Any] | None = None,
47
- part_2_no_splitlines: Callable[[str], Any] | None = None,
48
52
  ):
49
53
  if day is None:
50
54
  current_filename = Path(sys.argv[0]).stem
51
55
  current_filename_numbers = re.sub(r"[^0-9.]", "", current_filename)
52
56
  day = int(current_filename_numbers)
53
57
  if year is None:
54
- year = datetime.datetime.now(tz=datetime.timezone.utc).year
58
+ year = AOC_YEAR
55
59
 
56
60
  console.log(f"Solving {day=} {year=}")
57
61
  self.day = day
58
62
  self.year = year
59
63
  self.part_1 = part_1
60
64
  self.part_2 = part_2
61
- self.part_1_no_splitlines = part_1_no_splitlines
62
- self.part_2_no_splitlines = part_2_no_splitlines
63
65
 
64
66
  def print_p1(self):
65
67
  console.log(get_puzzle(self.day, self.year, part=1))
@@ -68,66 +70,33 @@ class AoC:
68
70
  console.log(get_puzzle(self.day, self.year, part=2))
69
71
 
70
72
  def get_input(self):
71
- return get_input(year=self.year, day=self.day).splitlines()
72
-
73
- def get_input_no_splitlines(self):
74
73
  return get_input(year=self.year, day=self.day)
75
74
 
76
75
  def assert_p1(self, inp: str, expected: Any):
77
- if self.part_1 is None and self.part_1_no_splitlines is None:
78
- msg = "Set part_1 when initializing AoC()"
79
- raise Exception(msg)
80
-
81
76
  res = None
82
77
  with print_perf("assert_p1"):
83
- if self.part_1 is not None:
84
- res = self.part_1(inp.splitlines())
85
- elif self.part_1_no_splitlines is not None:
86
- res = self.part_1_no_splitlines(inp)
78
+ res = self.part_1(inp)
87
79
 
88
80
  assert res is not None, "Result of part_1 should not be None"
89
81
  assert res == expected, f"{res} != {expected}"
90
82
 
91
83
  def assert_p2(self, inp: str, expected: Any):
92
- if self.part_2 is None and self.part_2_no_splitlines is None:
93
- msg = "Set part_2 when initializing AoC()"
94
- raise Exception(msg)
95
-
96
84
  res = None
97
85
  with print_perf("assert_p2"):
98
- if self.part_2 is not None:
99
- res = self.part_2(inp.splitlines())
100
- elif self.part_2_no_splitlines is not None:
101
- res = self.part_2_no_splitlines(inp)
86
+ res = self.part_2(inp)
102
87
 
103
88
  assert res is not None, "Result of part_2 should not be None"
104
89
  assert res == expected, f"{res} != {expected}"
105
90
 
106
91
  def submit_p1(self, answer: Any | None = None):
107
- if answer is not None:
108
- ...
109
- elif self.part_1 is not None:
110
- inp = self.get_input()
111
- with print_perf("submit_p1"):
112
- answer = self.part_1(inp)
113
- elif self.part_1_no_splitlines is not None:
114
- inp = self.get_input_no_splitlines()
115
- with print_perf("submit_p1"):
116
- answer = self.part_1_no_splitlines(inp)
92
+ with print_perf("submit_p1"):
93
+ answer = self.part_1(self.get_input())
117
94
 
118
95
  submit(year=self.year, day=self.day, level=1, answer=answer)
119
96
 
120
97
  def submit_p2(self, answer: Any | None = None):
121
- if answer is not None:
122
- ...
123
- elif self.part_2 is not None:
124
- inp = self.get_input()
125
- with print_perf("submit_p2"):
126
- answer = self.part_2(inp)
127
- elif self.part_2_no_splitlines is not None:
128
- inp = self.get_input_no_splitlines()
129
- with print_perf("submit_p2"):
130
- answer = self.part_2_no_splitlines(inp)
98
+ with print_perf("submit_p2"):
99
+ answer = self.part_2(self.get_input())
131
100
 
132
101
  submit(year=self.year, day=self.day, level=2, answer=answer)
133
102
 
@@ -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()
@@ -0,0 +1,4 @@
1
+ def test_version():
2
+ from src.adventofcode.__about__ import __version__ # noqa: PLC0415
3
+
4
+ assert __version__
@@ -1,19 +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
- ## [23.0b1]
9
-
10
- ### Added
11
-
12
- * `assert_p1` and `assert_p2` methods to `AoC` class. Used for easily asserting your solutions against sample inputs.
13
- * `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.
14
- * `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.
15
-
16
-
17
- ## [2023.0b0] - 2023-12-07
18
-
19
- Initial release
@@ -1 +0,0 @@
1
- __version__ = "23.0b1"
@@ -1,4 +0,0 @@
1
- def test_version():
2
- from src.adventofcode.__about__ import __version__
3
-
4
- assert __version__
File without changes
File without changes