From 8f4cd44fc9e0b150f6517496154e4e7c781c320d Mon Sep 17 00:00:00 2001 From: Stefan Tatschner Date: Mon, 9 Dec 2024 10:11:21 +0100 Subject: [PATCH] feat: Add a decorator for platform support --- src/gallia/net.py | 6 ++---- src/gallia/utils.py | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/gallia/net.py b/src/gallia/net.py index ddef3d3c3..8446a33d1 100644 --- a/src/gallia/net.py +++ b/src/gallia/net.py @@ -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__) @@ -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: diff --git a/src/gallia/utils.py b/src/gallia/utils.py index 2beaf6c7b..da4961364 100644 --- a/src/gallia/utils.py +++ b/src/gallia/utils.py @@ -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 @@ -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