enum_helper.py: Import the name conversion helpers from jw-pkg #5
1 changed files with 8 additions and 10 deletions
|
|
@ -1,22 +1,20 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from jw.pkg.lib.util import kebab_to_pascal, pascal_to_kebab
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import TypeVar
|
from typing import TypeVar
|
||||||
EnumType = TypeVar("EnumType", bound = Enum)
|
EnumType = TypeVar("EnumType", bound = Enum)
|
||||||
|
|
||||||
def kebab_to_pascal(value: str) -> str:
|
__all__ = [
|
||||||
return "".join(part.capitalize() for part in value.split("-"))
|
"kebab_to_pascal",
|
||||||
|
"pascal_to_kebab",
|
||||||
def pascal_to_kebab(value: str) -> str:
|
"enum_from_kebab",
|
||||||
# Handles normal CamelCase / PascalCase, including many acronym cases
|
"enum_to_kebab",
|
||||||
s1 = re.sub(r"(.)([A-Z][a-z]+)", r"\1-\2", value)
|
]
|
||||||
s2 = re.sub(r"([a-z0-9])([A-Z])", r"\1-\2", s1)
|
|
||||||
return s2.lower()
|
|
||||||
|
|
||||||
def enum_from_kebab(enum_cls: type[EnumType], value: str) -> EnumType:
|
def enum_from_kebab(enum_cls: type[EnumType], value: str) -> EnumType:
|
||||||
return enum_cls[kebab_to_pascal(value)]
|
return enum_cls[kebab_to_pascal(value)]
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue