-
Notifications
You must be signed in to change notification settings - Fork 2
/
aoc
404 lines (313 loc) · 11.1 KB
/
aoc
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/bin/env python3
import fire
import os
from pathlib import Path
import re
import requests
import sys
import json
import subprocess
from io import BufferedReader
from typing import Optional, Callable
from glob import glob
import time
from tqdm import tqdm
CHALLENGES_DIR = "challenges"
SAMPLE_TEST_JSON = "{}"
RUNNERS = {
"py": (None, ["./runners/py.sh"]),
"go": (["./runners/buildGo.sh"], None),
"kt": (["./runners/buildKotlin.sh"], ["./runners/jar.sh"]),
}
def convert_to_camel_case(inp: str) -> str:
parts = list(
map(lambda x: x.lower(), filter(lambda x: len(x) != 0, inp.split(" ")))
)
for i, st in enumerate(parts):
if i == 0:
continue
parts[i] = st[0].upper() + st[1:]
return "".join(parts)
def filter_for_filename(inp: str) -> str:
return "".join(filter(lambda x: x.isalpha() or x.isdigit() or x == "-", inp))
def load_credentials() -> dict[str, str]:
with open("credentials.json") as f:
return json.load(f)
def set_terminal_colour(*colours: str):
colcodes = {
"bold": "1",
"italic": "3",
"red": "31",
"green": "32",
"grey": "37",
"reset": "0",
}
for colour in colours:
if colour not in colcodes:
continue
sys.stdout.write(f"\033[{colcodes[colour]}m")
sys.stdout.flush()
known_runs = {}
def time_command(args: list[str], stdin=None) -> tuple[int, float]:
kwargs = {}
if type(stdin) == str:
kwargs["input"] = stdin.encode()
else:
kwargs["stdin"] = stdin
st = time.time()
proc = subprocess.run(args, stdout=subprocess.PIPE, **kwargs)
dur = time.time() - st
return proc.returncode, dur
def run_command(args: list[str], stdin=None, cache=True) -> tuple[int, str]:
if cache:
ah = hash("".join(args))
sh = hash(stdin)
if (ah, sh) in known_runs:
return known_runs[(ah, sh)]
kwargs = {}
if type(stdin) == str:
kwargs["input"] = stdin.encode()
else:
kwargs["stdin"] = stdin
proc = subprocess.run(args, stdout=subprocess.PIPE, **kwargs)
if cache:
known_runs[((ah, sh))] = (proc.returncode, proc.stdout)
return proc.returncode, proc.stdout
def format_result(v: str) -> str:
if len(v) == len(
"".join(filter(lambda x: x.isalpha() or x.isdigit() or x == "-", v))
):
return v
return repr(v)
def run_part(command: list[str], label: str, spec: dict[str, str | BufferedReader]):
set_terminal_colour("grey")
exit_status, buf_cont = run_command(command, stdin=spec.get("input"))
set_terminal_colour("reset")
print(f"{label}: ", end="")
if exit_status != 0:
set_terminal_colour("red")
print(f"exited with a non-zero status code ({exit_status})")
set_terminal_colour("reset")
return
result_str = buf_cont.decode().strip()
formatted_result_str = format_result(result_str)
if result_str == "":
set_terminal_colour("red")
print("nothing outputted")
set_terminal_colour("reset")
return
else:
if expected := spec.get("is"):
if expected == result_str:
set_terminal_colour("green")
print(f"pass", end="")
set_terminal_colour("grey")
print(f" ({formatted_result_str})")
else:
set_terminal_colour("red")
print(f"fail", end="")
set_terminal_colour("grey")
print(
f" (got {formatted_result_str}, expected {format_result(expected)})"
)
set_terminal_colour("reset")
else:
print(formatted_result_str)
def get_runner_command(
file_name: str,
) -> tuple[list[str], Optional[Callable[[], None]]]:
"""
Builds a solution using `command` then returns a path to the executable.
"""
file_extension = file_name.split(".")[-1].lower()
if file_extension not in RUNNERS:
print("No compatible runner found", file=sys.stderr)
raise SystemExit(1)
(runner_build, runner_run) = RUNNERS[file_extension]
if runner_build is None:
if runner_run is not None:
return runner_run + [file_name], None
print(f"No build or run command specified for runner {file_extension}")
raise SystemExit(1)
# if runner_run is not None and runner_build is not None:
# print(
# f"Build command and run command specified for {file_extension} - cannot determine path forwards."
# )
# raise SystemExit(1)
command = runner_build + [file_name]
set_terminal_colour("grey")
print("Building...", end="\r")
set_terminal_colour("reset")
exit_code, fpath = run_command(command, cache=False)
if exit_code != 0:
print(f"Failed to build: `{command}` returned exit code {exit_code}")
raise SystemExit(1)
fpstr = fpath.decode().strip()
if runner_run is None:
return [fpstr], lambda: os.unlink(fpstr)
return runner_run + [fpstr], lambda: os.unlink(fpstr)
class CLI(object):
@staticmethod
def init(year: int, day: int):
"""
Initialise a day's AoC challenge
"""
# Load day's page to verify that it has been released and to get the
# challenge title
day_url = f"https://adventofcode.com/{year}/day/{day}"
page_resp = requests.get(day_url)
if page_resp.status_code == 404:
print(
"Challenge page not found: has that day been released yet?",
file=sys.stderr,
)
raise SystemExit(1)
page_resp.raise_for_status()
matches = re.findall(
r"--- Day \d{1,2}: ([\w\- \?!]+) ---", page_resp.content.decode()
)
assert len(matches) >= 1, "must be able to discover at least one day title"
day_title = matches[0].replace("-", " ")
# Work out the challenge's directory.
p = Path(CHALLENGES_DIR)
p /= str(year)
p /= (
str(day).zfill(2)
+ "-"
+ filter_for_filename(convert_to_camel_case(day_title))
)
os.makedirs(p)
# Drop a basic README and tests file
with open(p / "README.md", "w") as f:
f.write(f"# [Day {day}: {day_title}]({day_url})\n")
with open(p / "tests.json", "w") as f:
f.write(SAMPLE_TEST_JSON)
# Download input and drop it in the challenge's directory
creds = load_credentials()
input_resp = requests.get(
day_url + "/input",
cookies={"session": creds["session"]},
headers={"User-Agent": creds["userAgent"]},
)
input_resp.raise_for_status()
with open(p / "input.txt", "wb") as f:
f.write(input_resp.content)
# Output the challenge's directory
print(p)
@staticmethod
def run(
fpath: str,
test_only: bool = False,
no_test: bool = False,
select_part: Optional[int] = None,
):
"""
Execute a day's code
"""
if test_only and no_test:
print(
f"Conflicting arguments (test-only and no-test both set)",
file=sys.stderr,
)
raise SystemExit(1)
if select_part:
select_part = str(select_part)
try:
os.stat(fpath)
except FileNotFoundError:
print(f"Could not stat {fpath}", file=sys.stderr)
raise SystemExit(1)
cmd, cleanup = get_runner_command(fpath)
challenge_dir = Path(os.path.dirname(fpath))
input_file = open(challenge_dir / "input.txt", "rb")
if test_only or not no_test:
test_specs = json.load(open(challenge_dir / "tests.json"))
for part in ["1", "2"]:
if select_part and select_part != part:
continue
for i, spec in enumerate(test_specs.get(part, [])):
run_part(cmd + [part], f"Test {part}.{i+1}", spec)
if no_test or not test_only:
if (select_part and select_part == "1") or not select_part:
run_part(cmd + ["1"], "Run 1", {"input": input_file})
input_file.seek(0)
if (select_part and select_part == "2") or not select_part:
run_part(cmd + ["2"], "Run 2", {"input": input_file})
input_file.close()
if cleanup is not None:
cleanup()
@staticmethod
def bench(fpath: str, n: int = 100):
try:
os.stat(fpath)
except FileNotFoundError:
print(f"Could not stat {fpath}", file=sys.stderr)
raise SystemExit(1)
file_extension = fpath.split(".")[-1].lower()
challenge_dir = Path(os.path.dirname(fpath))
input_file = open(challenge_dir / "input.txt", "rb")
cmd, cleanup = get_runner_command(fpath)
benchmark_file = (
Path(CHALLENGES_DIR) / challenge_dir.parts[1] / "benchmarks.jsonl"
)
benchmark_fd = open(benchmark_file, "a")
for part in ["1", "2"]:
durs = []
r_c = cmd + [part]
for _ in tqdm(range(n), ncols=0, leave=False, desc=f"Part {part}"):
exit_status, run_duration = time_command(r_c, stdin=input_file)
if exit_status != 0:
set_terminal_colour("red")
print(f"Exited with a non-zero status code ({exit_status})")
set_terminal_colour("reset")
return
input_file.seek(0)
durs.append(run_duration)
mi, mx, avg = min(durs), max(durs), sum(durs) / len(durs)
json.dump(
{
"day": int(challenge_dir.parts[-1].split("-")[0]),
"part": int(part),
"runner": file_extension,
"min": mi,
"max": mx,
"avg": avg,
"n": n,
},
benchmark_fd,
)
benchmark_fd.write("\n")
print(
f"Part {part}: min {round(mi, 4)} seconds, max {round(mx, 4)} seconds, avg {round(avg, 4)}"
)
benchmark_fd.close()
input_file.close()
if cleanup is not None:
cleanup()
@staticmethod
def addtest(year: int, day: int, part: int, output: str):
"""
Add a test to a challenge's test case file
"""
p = Path(CHALLENGES_DIR)
p /= str(year)
p /= glob(str(day).zfill(2) + "-*", root_dir=p)[0]
p /= "tests.json"
existing_tests = {}
try:
with open(p) as f:
existing_tests = json.load(f)
except FileNotFoundError:
pass
if (sp := str(part)) not in existing_tests:
existing_tests[sp] = []
existing_tests[sp].append(
{
"is": str(output),
"input": sys.stdin.read(),
}
)
with open(p, "w") as f:
json.dump(existing_tests, f, indent=" ")
if __name__ == "__main__":
fire.Fire(CLI)