From 97459775c7528a5e8315c8007bcf5ba4065f7fc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Priit=20L=C3=A4tt?= Date: Fri, 30 Aug 2024 16:47:39 +0300 Subject: [PATCH] Cache generated fallback enumerations --- src/codemagic/models/enums.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/codemagic/models/enums.py b/src/codemagic/models/enums.py index fa41e543..ba4b448b 100644 --- a/src/codemagic/models/enums.py +++ b/src/codemagic/models/enums.py @@ -1,6 +1,11 @@ +from __future__ import annotations + import contextlib import enum import re +from typing import Any +from typing import Dict +from typing import Tuple from codemagic.utilities import log @@ -19,6 +24,8 @@ class ResourceEnumMeta(enum.EnumMeta): graceful_fallback = True enable_name_transformation = False + __graceful_fallback_cache: Dict[Tuple[str, Any], Any] = {} + def __call__(cls, value, *args, **kwargs): # noqa: N805 try: return super().__call__(value, *args, **kwargs) @@ -29,11 +36,21 @@ def __call__(cls, value, *args, **kwargs): # noqa: N805 logger = log.get_logger(cls, log_to_stream=False) logger.warning("Undefined Resource enumeration: %s", ve) try: - enum_class = ResourceEnum(f"Graceful{cls.__name__}", {value: value}) - return enum_class(value) + return cls._create_graceful_fallback_instance(value) except TypeError: raise ve + def _create_graceful_fallback_instance(cls, value): # noqa: N805 + cache_key = (cls.__name__, value) + + try: + enum_class = cls.__graceful_fallback_cache[cache_key] + except KeyError: + enum_class = ResourceEnum(f"Graceful{cls.__name__}", {value: value}) + cls.__graceful_fallback_cache[cache_key] = enum_class + + return enum_class(value) + def _transform_class_name(cls): # noqa: N805 """ If enabled, transform CamelCase class name 'ClassName' to more