-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaoc.py
More file actions
221 lines (182 loc) · 6.46 KB
/
aoc.py
File metadata and controls
221 lines (182 loc) · 6.46 KB
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
#!/usr/bin/env python3
import os, sys
import argparse
import asyncio
import subprocess
import time
from pathlib import Path
from typing import List
CWD = Path(__file__).parent
class Time:
def __init__(self, time_ns):
self.time_ns = time_ns
@property
def ms(self):
return self.time_ns // 1_000_000
class Runner:
def __init__(self, prog: Path, verbose=False):
self.prog = prog
self.dir = prog.parent
self.day = prog.parent.name
self.rc: int = None
self.time: Time = Time(0)
self._part1: str = None
self._part2: str = None
if verbose:
self._vprint = print
else:
self._vprint = lambda *args: None
@property
def part1(self):
return self._part1 or "N/A"
@property
def part2(self):
return self._part2 or "N/A"
def compile(self):
pass
def run(self):
raise NotImplementedError()
def _run_exec(self, prog: Path, *args):
start = time.time_ns()
self._vprint("[RUN]", prog, " ".join(str(x) for x in args))
asyncio.run(self._async_run(prog, args))
self.time = Time(time.time_ns() - start)
async def _async_run(self, prog: Path, args = []):
proc = await asyncio.create_subprocess_exec(
prog, *args, stdout=asyncio.subprocess.PIPE,
cwd=self.dir,
)
extract_part = lambda l: l.decode().split(":", 1)[1].strip()
async for l in proc.stdout:
self._vprint(l.decode().strip())
if l.startswith(b"Part 1"):
self._part1 = extract_part(l)
elif l.startswith(b"Part 2"):
self._part2 = extract_part(l)
elif self._part1 is None and b":" in l:
self._part1 = extract_part(l)
elif self._part2 is None and b":" in l:
self._part2 = extract_part(l)
self.rc = await proc.wait()
def __repr__(self):
return "Runner({}, time={}, rc={}, part1={!r}, part2={!r})".format(
self.prog.name, self.time.ms, self.rc, self.part1, self.part2)
class Python(Runner):
def run(self):
self._run_exec(sys.executable, "-u", self.prog)
class Awk(Runner):
def run(self):
self._run_exec("awk", "-f", self.prog, "--", "input")
class ELisp(Runner):
def run(self):
if (self.prog.parent / "input").is_file():
self._run_exec("emacs", "-Q", "--script", self.prog, "--", "input")
else:
self._run_exec("emacs", "-Q", "--script", self.prog)
class Bash(Runner):
def run(self):
self._run_exec("bash", self.prog, "input")
class C(Runner):
def __init__(self, prog, *args, **kwargs):
super().__init__(prog, *args, **kwargs)
self.prog = self.prog.with_suffix('')
def compile(self):
subprocess.run(["make", self.prog.relative_to(self.dir).with_suffix('')],
cwd=self.dir)
def run(self):
self._run_exec(self.prog)
class Rs(C):
def compile(self):
subprocess.run(["rustc", self.prog.relative_to(self.dir).with_suffix('.rs')],
cwd=self.dir)
class Go(C):
def compile(self):
subprocess.run(["go", "build"], cwd=self.dir)
class Zig(Runner):
def compile(self):
subprocess.run(["zig", "build-exe", self.prog.name], cwd=self.dir)
def run(self):
self._run_exec(self.prog.with_suffix(''), "input")
class Rust(Runner):
def __init__(self, prog, *args, **kwargs):
super().__init__(prog, *args, **kwargs)
self.prog = self.prog.parent / "target" / "debug" / "Jour{}".format(self.prog.parent.name)
def compile(self):
subprocess.run(["cargo", "build"], cwd=self.dir)
def run(self):
self._run_exec(self.prog, "input")
class Java(Runner):
def compile(self):
cmd = ["javac", self.prog.name]
self._vprint("[Compile]", *cmd)
subprocess.run(cmd, cwd=self.dir)
def run(self):
self._run_exec("java", self.prog.with_suffix('').name, "input")
run_formats = {
".py": Python,
".c": C,
".cpp": C,
".awk": Awk,
".el": ELisp,
".rs": Rs,
".sh": Bash,
".go": Go,
".zig": Zig,
".java": Java,
}
def parse_days(year, day, verbose=False):
year = CWD/"{}".format(year)
if day:
days = [year/"{:02}".format(day)]
if not days[0].is_dir():
raise ValueError("Invalid day {}".format(day))
else:
days = sorted(d for d in year.iterdir() if d.is_dir())
r = []
for i, d in enumerate(days):
for f in sorted(d.iterdir()):
if f.name == ".ignore":
break
elif f.name.startswith("Jour{:02}.".format(d.name)) and f.suffix in run_formats:
r.append(run_formats[f.suffix](f, verbose))
break
elif f.name == "Cargo.toml":
r.append(Rust(f, verbose))
break
else:
print("Warning: No source found to run {}".format(d))
return r
def report_table(runs: List[Runner]):
cols = [" day", "Part 1", "Part 2", "Time (ms)"]
alen = [len(c) for c in cols]
align = [">", "^", "^", ">"]
fmt = ["", "", "", ","]
for r in runs:
alen[1] = max(alen[1], len(r.part1))
alen[2] = max(alen[2], len(r.part2))
alen[3] = max(alen[3], len("{:{}}".format(r.time.ms, fmt[3])))
length = sum(alen) + len(alen) * 3 - 1
print(" | ".join("{:^{}}".format(c, a) for c, a in zip(cols, alen)))
print("-" * length)
for r in runs:
print(" | ".join("{:{}{}{}}".format(c, a, l, f)
for c, f, a, l in zip([r.day, r.part1, r.part2, r.time.ms], fmt, align, alen)))
def main():
years = sorted(d.name for d in CWD.iterdir() if len(d.name) == 4 and d.name.startswith("20"))
parser = argparse.ArgumentParser(description='Simple interface to run AoC pprograms')
parser.add_argument("year", choices=years, help="Which year to run")
parser.add_argument("-d", "--day", type=int, help="Run a single day of the year")
parser.add_argument("-v", "--verbose", action="store_true", help="Let prog output be printed")
args = parser.parse_args()
runners = parse_days(args.year, args.day, args.verbose)
for i, r in enumerate(runners):
print("{} / {}".format(i+1, len(runners)))
r.verbose = args.verbose
r.compile()
r.run()
if args.verbose:
print(runners)
else:
report_table(runners)
if __name__=="__main__":
main()