Skip to content

Commit

Permalink
feat: Add a decorator for platform support
Browse files Browse the repository at this point in the history
  • Loading branch information
rumpelsepp committed Dec 9, 2024
1 parent 55f8594 commit 8f4cd44
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
6 changes: 2 additions & 4 deletions src/gallia/net.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
# SPDX-License-Identifier: Apache-2.0

import subprocess
import sys

import pydantic
from pydantic.networks import IPvAnyAddress

from gallia.log import get_logger
from gallia.utils import supports_platform

logger = get_logger(__name__)

Expand Down Expand Up @@ -47,10 +47,8 @@ def can_broadcast(self) -> bool:
return "BROADCAST" in self.flags


@supports_platform("linux")
def net_if_addrs() -> list[Interface]:
if sys.platform != "linux":
raise NotImplementedError("net_if_addrs() is only supported on Linux platforms")

p = subprocess.run(["ip", "-j", "address", "show"], capture_output=True, check=True)

try:
Expand Down
21 changes: 21 additions & 0 deletions src/gallia/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import re
import sys
from collections.abc import Awaitable, Callable
from functools import wraps
from pathlib import Path
from types import ModuleType
from typing import TYPE_CHECKING, Any, TypeVar
Expand Down Expand Up @@ -307,3 +308,23 @@ def handle_task_error(fut: asyncio.Future[Any]) -> None:

# Info level is enough, since our aim is only to consume the stack trace
logger.info(f"{task_name} ended with error: {e!r}")


def supports_platform[T, **P](*platform: str) -> Callable[[Callable[P, T]], Callable[P, T]]:
def decorator(function: Callable[P, T]) -> Callable[P, T]:
@wraps(function)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
supported = False
for p in platform:
if sys.platform == p:
supported = True
if supported is False:
raise NotImplementedError(
f"`{function.__name__}()` is not supported on: \"{sys.platform}\""
)

return function(*args, **kwargs)

return wrapper

return decorator

0 comments on commit 8f4cd44

Please sign in to comment.