Skip to content

Commit 0e936d0

Browse files
committed
runner - compacter cli layout
1 parent 19277e0 commit 0e936d0

File tree

2 files changed

+42
-42
lines changed

2 files changed

+42
-42
lines changed

src/main/python/aoc/runner/listener.py

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
import sys
44
from abc import ABC
55
from abc import abstractmethod
6+
from collections.abc import Iterable
7+
from collections.abc import Iterator
68
from datetime import datetime
7-
from typing import Iterable
8-
from typing import Iterator
99
from typing import NamedTuple
10+
from typing import cast
1011

1112
from dateutil import tz
1213
from junitparser import Attr
@@ -214,43 +215,42 @@ def part_finished(
214215
) -> None:
215216
if answer and correct:
216217
icon = colored("✅", "green")
217-
string = f"{answer[:CLIListener.cutoff]}"
218+
string = f"{answer[: CLIListener.cutoff]}"
218219
elif answer and not correct:
219220
if expected is None:
220221
icon = colored("?", "magenta")
221222
correction = "(correct answer unknown)"
222223
else:
223224
icon = colored("❌", "red")
224225
correction = f"(expected: {expected})"
225-
string = f"{answer[:CLIListener.cutoff]} {correction}"
226+
string = f"{answer[: CLIListener.cutoff]} {correction}"
226227
if time is not None:
227228
self.times.append(time)
228229
self._update_part(sum(self.times), part, string, icon)
229230

230231
def stop(self) -> None:
231232
print()
232233
print(
233-
"Total run time: {:8.4f}s\nTook: {:8.4f}s".format(
234-
self.total_time / 1e9, self.total_walltime
235-
)
234+
f"Total run time: {self.total_time / 1e9:8.4f}s\n"
235+
f"Took: {self.total_walltime:8.4f}s"
236236
)
237237

238238
def _init_line(self, time: int) -> None:
239239
runtime = self._format_time(time, self.timeout)
240-
self.line = " ".join([runtime, self.progress])
240+
self.line = f"{runtime} {self.progress}"
241241

242242
def _update_part(
243243
self, time: int, part: str, answer: str, icon: str
244244
) -> None:
245245
if part == "a":
246246
self._init_line(time)
247247
answer = answer.ljust(30)
248-
self.line_a = f" {icon} part {part}: {answer}"
248+
self.line_a = f" {icon} {part}: {answer}"
249249
self.line += self.line_a
250250
else:
251251
self._init_line(time)
252252
self.line += self.line_a
253-
self.line += f" {icon} part {part}: {answer}"
253+
self.line += f" {icon} {part}: {answer}"
254254

255255
def _format_time(self, time: int, timeout: float) -> str:
256256
t = time / 1e9
@@ -261,10 +261,10 @@ def _format_time(self, time: int, timeout: float) -> str:
261261
else:
262262
color = "red"
263263
if t < 0.001:
264-
runtime = colored("{: 7.3f}ms".format(t * 1000), color)
264+
runtime = colored(f"{t * 1000:7.3f}ms", color)
265265
else:
266-
runtime = colored("{: 8.4f}s".format(t), color)
267-
return runtime
266+
runtime = colored("{t:8.4f}s", color)
267+
return cast("str", runtime)
268268

269269

270270
class JUnitXmlListener(Listener):
@@ -298,7 +298,7 @@ def puzzle_finished(self, time: int, walltime: float) -> None:
298298
pass
299299

300300
def puzzle_finished_with_error(
301-
self, time: int, walltime: float, error: str
301+
self, _time: int, walltime: float, error: str
302302
) -> None:
303303
case = TestCase(
304304
name=f"{self.year}/{self.day:02}/{self.plugin}/{self.user_id}"
@@ -314,9 +314,9 @@ def puzzle_finished_with_error(
314314
def part_missing(self, time: int, part: str) -> None:
315315
pass
316316

317-
def part_skipped(self, time: int, part: str) -> None:
317+
def part_skipped(self, _time: int, part: str) -> None:
318318
case = TestCase(
319-
name=f"{self.year}/{self.day:02}/{part}/{self.plugin}/{self.user_id}" # noqa E501
319+
name=f"{self.year}/{self.day:02}/{part}/{self.plugin}/{self.user_id}"
320320
)
321321
case.year = self.year
322322
case.day = self.day
@@ -335,14 +335,15 @@ def part_finished(
335335
correct: bool,
336336
) -> None:
337337
case = TestCase(
338-
name=f"{self.year}/{self.day:02}/{part}/{self.plugin}/{self.user_id}" # noqa E501
338+
name=f"{self.year}/{self.day:02}/{part}/{self.plugin}/{self.user_id}"
339339
)
340340
case.year = self.year
341341
case.day = self.day
342342
case.part = part
343343
case.plugin = self.plugin
344344
case.user_id = self.user_id
345-
case.time = time / 1e9
345+
if time is not None:
346+
case.time = time / 1e9
346347
if not correct:
347348
case.result = [Failure(f"Expected '{expected}', was: '{answer}'")]
348349
self.suite.add_testcase(case)
@@ -366,7 +367,7 @@ def __init__(self) -> None:
366367
self.part_runs = list[BenchmarkListener.PartRun]()
367368

368369
def puzzle_started(
369-
self, year: int, day: int, title: str, plugin: str, user_id: str
370+
self, year: int, day: int, _title: str, plugin: str, user_id: str
370371
) -> None:
371372
self.year = year
372373
self.day = day
@@ -397,9 +398,9 @@ def part_finished(
397398
self,
398399
time: int | None,
399400
part: str,
400-
answer: str | None,
401-
expected: str | None,
402-
correct: bool,
401+
_answer: str | None,
402+
_expected: str | None,
403+
_correct: bool,
403404
) -> None:
404405
if time is None:
405406
return

src/main/python/aoc/runner/runner.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
"""
2-
Copyright (c) 2016 wim glenn
1+
"""Copyright (c) 2016 wim glenn.
32
43
Permission is hereby granted, free of charge, to any person obtaining a copy
54
of this software and associated documentation files (the "Software"), to deal
@@ -28,12 +27,12 @@
2827
import time
2928
from argparse import ArgumentParser
3029
from collections import OrderedDict
30+
from collections.abc import Callable
31+
from collections.abc import Generator
3132
from contextlib import contextmanager
3233
from datetime import datetime
3334
from pathlib import Path
3435
from typing import Any
35-
from typing import Callable
36-
from typing import Generator
3736

3837
import pebble
3938
from dateutil.tz import gettz
@@ -190,7 +189,7 @@ def main() -> None:
190189

191190
if "slowest" in args:
192191
print()
193-
by_time = [_ for _ in bench.get_by_time()]
192+
by_time = list(bench.get_by_time())
194193
by_time.reverse()
195194
for i in range(args.slowest):
196195
print(
@@ -203,7 +202,7 @@ def main() -> None:
203202

204203

205204
def run_with_timeout(
206-
callable: Callable[[int, int, str], tuple[Result, Result]],
205+
callable_: Callable[[int, int, str], tuple[Result, Result]],
207206
args: dict[str, Any],
208207
timeout: int,
209208
listener: Listener,
@@ -212,7 +211,7 @@ def run_with_timeout(
212211
elapsed = 0
213212
t0 = time.time_ns()
214213
future = pebble.concurrent.process(daemon=False, timeout=timeout)(
215-
callable
214+
callable_
216215
)(**args)
217216
while not future.done():
218217
listener.run_elapsed(elapsed)
@@ -222,7 +221,7 @@ def run_with_timeout(
222221
try:
223222
result_a, result_b = future.result()
224223
except Exception as err:
225-
log.error(err)
224+
log.exception("Exception in run_with_timeout")
226225
result_a = Result.ok("")
227226
result_b = Result.ok("")
228227
error = repr(err)
@@ -233,22 +232,22 @@ def run_with_timeout(
233232

234233

235234
@contextmanager
236-
def use_plugins(plugins: dict[str, Plugin]) -> Generator[None, None, None]:
237-
for p in plugins:
238-
plugins[p].start()
235+
def use_plugins(plugins: dict[str, Plugin]) -> Generator[None]:
236+
for plugin in plugins.values():
237+
plugin.start()
239238
try:
240239
yield
241240
finally:
242-
for p in plugins:
243-
plugins[p].stop()
241+
for plugin in plugins.values():
242+
plugin.stop()
244243

245244

246245
@contextmanager
247246
def scratch_file(
248247
name: str, year: int, day: int, input_data: str
249-
) -> Generator[None, None, None]:
250-
prev = os.getcwd()
251-
scratch = tempfile.mkdtemp(prefix=f"{year}-{day:02d}-")
248+
) -> Generator[None]:
249+
prev = Path.cwd()
250+
scratch = Path(tempfile.mkdtemp(prefix=f"{year}-{day:02d}-"))
252251
os.chdir(scratch)
253252
input_path = Path(name)
254253
assert not input_path.exists()
@@ -259,8 +258,8 @@ def scratch_file(
259258
input_path.unlink(missing_ok=True)
260259
os.chdir(prev)
261260
try:
262-
os.rmdir(scratch)
263-
except Exception as err:
261+
scratch.rmdir()
262+
except Exception as err: # noqa:BLE001
264263
log.warning(
265264
"failed to remove scratch %s (%s: %s)", scratch, type(err), err
266265
)
@@ -296,7 +295,7 @@ def run_for(
296295
else:
297296
with scratch_file(config.scratch_file, year, day, input_data):
298297
result_a, result_b, walltime, error = run_with_timeout(
299-
callable=plugin[1].run,
298+
callable_=plugin[1].run,
300299
args={"year": year, "day": day, "data": input_data},
301300
timeout=timeout,
302301
listener=listener,
@@ -309,7 +308,7 @@ def run_for(
309308
n_incorrect += 1
310309
listener.puzzle_finished_with_error(time, walltime, error)
311310
else:
312-
for result, part in zip((result_a, result_b), "ab"):
311+
for result, part in zip((result_a, result_b), "ab", strict=True):
313312
if day == 25 and part == "b":
314313
# there's no part b on christmas day, skip
315314
continue

0 commit comments

Comments
 (0)