-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaoc-helper
executable file
·154 lines (129 loc) · 4.57 KB
/
aoc-helper
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
#!venv/bin/python
import logging
import os
import shutil
import subprocess
import pytest
import requests
import typer
from bs4 import BeautifulSoup
app = typer.Typer()
logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s")
def get_sample_input(day: int) -> None:
try:
res = requests.get(f"https://adventofcode.com/2021/day/{day}")
except requests.exceptions.RequestException as e:
logging.error(e)
soup = BeautifulSoup(res.text, "html.parser")
sample = soup.find("pre")
try:
per_line = 64
data = sample.text.strip()
new_line = "\n"
logging.info(
f"""{new_line.join(
repr(data[i : i + per_line])
for i in range(0, len(data), per_line)
)}"""
)
except AttributeError:
logging.error("Couldn't find sample.")
def download_input(day: int) -> None:
try:
res = requests.get(
f"https://adventofcode.com/2021/day/{day}/input",
cookies={"session": os.environ["AOC_COOKIE"]},
timeout=10,
)
except KeyError:
raise KeyError("AOC_COOKIE environment variable not set.")
except requests.exceptions.RequestException:
raise
if res.status_code != 200:
raise requests.exceptions.RequestException(
f"Failed to download input for day {day}"
)
logging.info("Downloading input...")
with open(f"day{day}/input.txt", "w") as f:
f.write(res.text)
logging.info("Done!")
def submit_solution(day: int, part: int, solution: str) -> None:
input("Press enter to continue or Ctrl+C to cancel.")
try:
res = requests.post(
f"https://adventofcode.com/2021/day/{day}/answer",
cookies={"session": os.environ["AOC_COOKIE"]},
data={"level": part, "answer": solution},
timeout=10,
)
except KeyError:
raise KeyError("AOC_COOKIE environment variable not set.")
except requests.exceptions.RequestException:
raise
if res.status_code != 200:
raise requests.exceptions.RequestException(
f"Failed to submit solution for day {day}"
)
soup = BeautifulSoup(res.text, "html.parser")
message = soup.find("article").text
if "That's not the right answer" in message:
logging.error(f"Incorrect submission!\n{message.strip()}")
elif "You gave an answer too recently" in message:
logging.error(f"Time penalty active!\n{message.strip()}")
else:
logging.info("SUCCESS!")
@app.command(help="Setups structue for day")
def setup(day: int = typer.Option(..., "--day", "-d")) -> None:
os.makedirs(f"day{day}", exist_ok=True)
shutil.copy("template.py", f"day{day}/part1.py")
shutil.copy("template.py", f"day{day}/part2.py")
res = subprocess.run(["touch", "__init__.py"], cwd=f"day{day}")
if res.returncode != 0:
raise subprocess.CalledProcessError(res.returncode, "touch")
@app.command(help="Downloads input for day")
def get_data(day: int = typer.Option(..., "--day", "-d")) -> None:
try:
get_sample_input(day)
except requests.exceptions.RequestException as e:
logging.error(e)
try:
download_input(day)
except requests.exceptions.RequestException:
raise
@app.command(
help="Runs test, and if test passes, submits solution on prompt confirmation"
)
def autorun(
day: int = typer.Option(..., "--day", "-d"),
part: int = typer.Option(..., "--part", "-p"),
submit: bool = typer.Option(False, "--submit"),
) -> None:
logging.info("Running test...")
retcode = pytest.main(["-v", "-s", "--no-header", f"day{day}/part{part}.py"])
if retcode:
return
logging.info("Running solution...")
res = subprocess.run(
["venv/bin/python", "-m", f"day{day}.part{part}"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if res.returncode:
logging.error(res.stderr.decode("utf-8", errors="backslashreplace").strip())
return
*solution, time_info = res.stdout.decode("utf-8").strip().split("\n")
logging.info(time_info)
if len(solution) != 1:
logging.info("Solution:")
for solution_line in solution[:-1]:
logging.info(solution_line)
return
logging.info(f"Solution: {solution[0]}")
if submit:
logging.info(f"Submitting solution {solution[0]} for day {day} part {part}")
try:
submit_solution(day, part, solution[0])
except requests.exceptions.RequestException:
raise
if __name__ == "__main__":
app()