-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprep
executable file
·90 lines (67 loc) · 2.27 KB
/
prep
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
#!/usr/bin/env python
import signal
import sys
import time
import tomllib
import urllib.request
from datetime import datetime, timedelta
from pathlib import Path
def trace(*args, **kwargs):
print(*args, file=sys.stderr, flush=True, **kwargs)
def prep(day=None, year=None):
now = datetime.utcnow()
if year is None:
year = now.year
if day is None:
day = (now - datetime(year, 12, 1)).days + 1
else:
day = int(day)
mydir = Path(__file__).resolve().parent
dayin = mydir / 'days' / f'day{day}.in'
dayurl = f'https://adventofcode.com/{year}/day/{day}/input'
headers = None
if Path('.env').is_file():
with open('.env', 'rb') as fp:
config = tomllib.load(fp)
headers = config['wget']['headers']
if dayin.is_file():
yn = input(f'{dayin}\nFile already exists. Overwrite? [N/y] ')
overwrite = yn.strip().lower() in ('y', 'yes')
if not overwrite:
return
that_moment = datetime(year, 12, day, 5)
sleep_until(that_moment)
problem = wget(dayurl, headers=headers)
with open(dayin, 'wb') as fp:
fp.write(problem)
def sleep_until(that_moment):
def restore_cursor(*args):
exit()
sig = signal.signal(signal.SIGINT, restore_cursor)
subsec = 2
while (dt := that_moment - datetime.utcnow()) > timedelta():
dt = timedelta(seconds=round(dt.total_seconds()))
trace(f'T-{dt} ' , end='')
time.sleep(1/subsec)
trace('\x1b[1K\x1b[G', end='')
signal.signal(signal.SIGINT, sig)
def wget(url, headers=None):
trace(url)
delay = 1
while True:
try:
req = urllib.request.Request(url, headers=headers or dict())
with urllib.request.urlopen(req, timeout=5) as r:
trace(r.url, r.status, r.reason)
return r.read()
except Exception as e:
trace(e)
time.sleep(delay)
delay *= 1.44
if __name__ == '__main__':
import argparse
cli = argparse.ArgumentParser(description='Download a daily challenge')
cli.add_argument('day', type=int, nargs='?', help='Day number')
cli.add_argument('--year', type=int, default=None, help='Year')
args = cli.parse_args()
prep(year=args.year, day=args.day)