From d83b8ada922c11f79ff8f1b373b766f3d7c7d570 Mon Sep 17 00:00:00 2001 From: Alexey Kotlyarov Date: Mon, 12 Aug 2024 18:06:39 +1000 Subject: [PATCH] fix: Extract 'matches if specified' logic --- mybox/package/base.py | 11 ++++------- mybox/utils.py | 4 ++++ tests/test_utils.py | 15 ++++++++++++++- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/mybox/package/base.py b/mybox/package/base.py index a002c92b..60cc5b42 100644 --- a/mybox/package/base.py +++ b/mybox/package/base.py @@ -8,7 +8,7 @@ from ..parallel import gather_ from ..state import DB from ..tracker import Tracker -from ..utils import allow_singular, async_cached +from ..utils import allow_singular, async_cached, matches_if_specified class Package(BaseModel, ABC): @@ -63,12 +63,9 @@ async def install(self, *, tracker: Tracker) -> None: pass async def applicable(self) -> bool: - def check_os(name: str) -> bool: - return self.os is None or name in self.os - os = await self.driver.os() return os.switch_( - linux=lambda linux: check_os("linux") - and (self.distribution is None or linux.distribution in self.distribution), - macos=lambda: check_os("darwin"), + linux=lambda linux: matches_if_specified(self.os, "linux") + and matches_if_specified(self.distribution, linux.distribution), + macos=lambda: matches_if_specified(self.os, "darwin"), ) diff --git a/mybox/utils.py b/mybox/utils.py index 47fecdc9..9bd8fd84 100644 --- a/mybox/utils.py +++ b/mybox/utils.py @@ -35,6 +35,10 @@ def allow_singular_none(field: str) -> Any: return field_validator(field, mode="before")(lambda cls, x: unsome(x)) +def matches_if_specified(possibilities: Optional[list[T]], value: T) -> bool: + return possibilities is None or value in possibilities + + def intercalate(delimiter: T, items: Iterable[Iterable[T]]) -> list[T]: it = iter(items) try: diff --git a/tests/test_utils.py b/tests/test_utils.py index 74efa7f0..3799ff02 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,6 +1,12 @@ import pytest -from mybox.utils import flatten, intercalate, run_ok, with_extensions +from mybox.utils import ( + flatten, + intercalate, + matches_if_specified, + run_ok, + with_extensions, +) class TestRunOK: @@ -39,3 +45,10 @@ def test_with_extensions(): extensions = ["com", "exe"] assert with_extensions("foo", extensions) == ["foo.com", "foo.exe"] assert with_extensions("foo.com", extensions) == ["foo.com"] + + +def test_matches_if_specified(): + assert matches_if_specified(None, "anything") + assert not matches_if_specified([], "anything") + assert matches_if_specified(["alpha", "beta"], "alpha") + assert not matches_if_specified(["alpha", "beta"], "gamma")