-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaoc.py
executable file
·295 lines (217 loc) · 7.72 KB
/
aoc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env python
import asyncio
import datetime
import functools
import itertools
import json
import operator
import os
import pathlib
import re
import sys
import time
from collections import defaultdict
from pathlib import Path
import requests
from dotenv import find_dotenv, load_dotenv
from jinja2 import Environment, FileSystemLoader
_ = load_dotenv(find_dotenv())
def download_title(year, day):
meta_file = pathlib.Path("meta.json")
if not meta_file.is_file():
meta_file.write_text(json.dumps({"days": {}, "notes": {}}, indent=2))
try:
days = json.loads(meta_file.read_text())["days"]
if f"{year}/{str(day).zfill(2)}" in days.keys():
return
except Exception as exc:
print(exc)
return
url = f"https://adventofcode.com/{year}/day/{day}"
response = requests.get(url)
if response.status_code != 200:
return None
html_content = response.text
pattern = re.compile(rf"--- Day {day}: (.*?) ---", re.IGNORECASE)
match = pattern.search(html_content)
if match:
puzzle = match.group(1).strip().replace("'", "'")
meta_file_content = json.loads(meta_file.read_text(encoding="utf-8"))
meta_file_content["days"][f"{year}/{str(day).zfill(2)}"] = puzzle
meta_file_content["days"] = dict(
sorted(meta_file_content["days"].items(), key=operator.itemgetter(0))
)
meta_file.write_text(
json.dumps(
meta_file_content,
indent=2,
),
encoding="utf-8",
)
print(f"Zaktualizowano plik meta.json o dane z {year} {day}")
def download_input(year, day):
directory = pathlib.Path(f"data/{year}")
if not directory.is_dir():
directory.mkdir(parents=True, exist_ok=True)
input_file = pathlib.Path(f"data/{year}/{str(day).zfill(2)}.txt")
if input_file.is_file() and len(input_file.read_text().strip()):
return
response = requests.get(
f"https://adventofcode.com/{year}/day/{day}/input",
cookies={"session": os.environ["SESSION"]},
)
if response.status_code != 200:
return None
input_file.write_text(response.text.strip(), encoding="utf-8")
print(f"Zapisano dane wejściowe dla {year} {day}")
def copy_solution_template(year, day):
template = pathlib.Path("day.template.py").read_text()
target = pathlib.Path(f"src/{year}/{str(day).zfill(2)}.py")
if target.is_file() and len(target.read_text()):
return
target.write_text(
template.replace("YYYY", str(year)).replace("DD", str(day).zfill(2)),
encoding="utf-8",
)
def download_all():
today = datetime.date.today()
for year in range(2015, 3000):
if year > today.year:
break
for day in range(1, 26):
if year == today.year and day > today.day:
break
download_input(year, day)
download_title(year, day)
copy_solution_template(year, day)
time.sleep(3)
def download_specific(year: int, day: int):
download_input(year, day)
download_title(year, day)
copy_solution_template(year, day)
def download_today():
today = datetime.date.today()
if today.month == 12 and today.day <= 25:
download_input(today.year, today.day)
download_title(today.year, today.day)
copy_solution_template(today.year, today.day)
def collect_data_for_readme():
meta = json.loads(Path("meta.json").read_text())
extension_to_language = {
"py": "Python",
"rb": "Ruby",
}
days = list(
sorted(
[(*yearday.split("/"), title) for yearday, title in meta["days"].items()],
key=functools.cmp_to_key(
lambda a, b: (
(int(a[1]) - int(b[1])) if a[0] == b[0] else int(b[0]) - int(a[0])
)
),
)
)
available_days = set(meta["days"].keys())
notes = meta["notes"]
events = defaultdict(lambda: defaultdict(lambda: dict()))
collected_stars = 0
available_stars = 0
for year, day, title in days:
events[year][day] = {
"title": f"[{title}](https://adventofcode.com/{year}/day/{int(day)})",
"solutions": [],
"solutions_formatted": "",
"input": "",
"progress": 0,
"note": notes.get(f"{year}/{day}", ""),
}
available_stars += 2
for solution in [
p
for p in Path("src").rglob("*")
if p.suffix in {".py", ".rb"} and "01" <= p.stem <= "25"
]:
if not re.compile(r"src/20\d\d\/[012]\d\.").match(str(solution)):
continue
[year, day, extension] = re.findall(
r"src\/(\d{4})\/(\d\d).(.*)", str(solution)
).pop()
if f"{year}/{day}" not in available_days:
continue
events[year][day]["solutions"].append(
[
extension,
f"https://github.com/0x8b/advent.of.code.each/blob/main/src/{year}/{day}.{extension}",
]
)
events[year][day]["solutions_formatted"] = ", ".join(
f"[{extension_to_language[extension]}]({link})"
for extension, link in sorted(
events[year][day]["solutions"], key=operator.itemgetter(0)
)
)
source_code = solution.read_text(encoding="utf-8")
events[year][day]["progress"] = max(
events[year][day]["progress"],
sum(("part_1" in source_code, "part_2" in source_code)),
)
for solution in [
p
for p in Path("data").rglob("*")
if p.suffix in {".txt"} and "01" <= p.stem <= "25"
]:
[year, day] = re.findall(r"data\/(\d{4})\/(\d\d).txt", str(solution)).pop()
if f"{year}/{day}" not in available_days:
continue
events[year][day][
"input"
] = f"https://github.com/0x8b/advent.of.code.each/blob/main/data/{year}/{day}.txt"
emojis = dict(
zip(
[str(year) for year in range(2015, 2030)],
itertools.cycle(["🎅", "🦌", "🍪", "🎁", "🎄"]),
)
)
stars = defaultdict(int)
solved = defaultdict(int)
for year in events:
for day in events[year]:
stars[year] += events[year][day]["progress"]
solved[year] += 1 if events[year][day]["progress"] == 2 else 0
collected_stars += events[year][day]["progress"]
return {
"range": f"{min(events.keys())}-{max(events.keys())}",
"events": events,
"emojis": emojis,
"stars": stars,
"solved": solved,
"collected_stars": collected_stars,
"available_stars": available_stars,
}
def render_readme(data, template_file, output_file):
env = Environment(loader=FileSystemLoader(os.path.dirname(template_file)))
template = env.get_template(os.path.basename(template_file))
Path(output_file).write_text(template.render(data), encoding="utf-8")
async def main():
if len(sys.argv) < 2:
sys.exit(1)
command = sys.argv[1]
match command:
case "download":
match sys.argv[2:]:
case ["all"]:
download_all()
case year, day if True:
download_specific(year, day)
case ["today"]:
download_today()
case _:
raise SystemExit(
"Unknown command. Usage: ./aoc.py download <all|year day|today>"
)
case "render":
render_readme(collect_data_for_readme(), "README.md.jinja", "README.md")
case _:
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())