Skip to content

Commit e56a5a0

Browse files
committed
Fix typing
1 parent 429919a commit e56a5a0

File tree

1 file changed

+31
-13
lines changed

1 file changed

+31
-13
lines changed

src/aoc/main.py

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
import importlib
22
import shutil
33
from pathlib import Path
4-
from typing import Optional
4+
from typing import Literal, Optional
55

66
import aocd
77
import pytest
88
import typer
99
from aocd import AocdError
1010
from aocd.exceptions import PuzzleLockedError
1111
from aocd.models import Puzzle
12+
from mypy.nodes import TypeGuard
1213

1314
app = typer.Typer(no_args_is_help=True)
1415

@@ -129,6 +130,32 @@ def verify(
129130
pytest.main(pytest_args)
130131

131132

133+
def _check_type_of_part(part: str) -> TypeGuard[Literal["a", "b"]]:
134+
if part in ("a", "b"):
135+
return True
136+
return False
137+
138+
139+
def _transform_part(part: str) -> str:
140+
if part in ("1", "2"):
141+
return chr(ord("a") + int(part) - 1)
142+
return part
143+
144+
145+
def _full_validate(part: str) -> Literal["a", "b"]:
146+
part = _transform_part(part)
147+
if _check_type_of_part(part):
148+
return part
149+
150+
typer.echo(
151+
typer.style(
152+
f"Invalid part {part}. Must be one of 1, 2, a, b.",
153+
fg=typer.colors.RED,
154+
)
155+
)
156+
raise typer.Exit(1)
157+
158+
132159
@app.command()
133160
def submit(
134161
day: int,
@@ -137,22 +164,13 @@ def submit(
137164
"You can use numbers 1/2 or letters a/b."
138165
),
139166
):
140-
if part in ("1", "2"):
141-
part = chr(ord("a") + int(part) - 1)
142-
if part not in ("a", "b"):
143-
typer.echo(
144-
typer.style(
145-
f"Invalid part {part}. Must be one of 1, 2, a, b.",
146-
fg=typer.colors.RED,
147-
)
148-
)
149-
raise typer.Exit(1)
167+
validated_part = _full_validate(part)
150168
module = import_challenge_module(day)
151-
if part == "a":
169+
if validated_part == "a":
152170
solution = module.Challenge(use_test_data=False).part_1()
153171
else:
154172
solution = module.Challenge(use_test_data=False).part_2()
155-
aocd.submit(solution, day=day, year=2023, part=part)
173+
aocd.submit(solution, day=day, year=2023, part=validated_part)
156174

157175

158176
@app.command()

0 commit comments

Comments
 (0)