| 1 | import re |
| 2 | from abc import ABC, abstractmethod |
| 3 | from dataclasses import dataclass, field |
| 4 | from typing import Union |
| 5 | |
| 6 | from typing_extensions import override |
| 7 | |
| 8 | SLOTS = list[Union[str, set[str], dict[str, str]]] |
| 9 | |
| 10 | |
| 11 | @dataclass |
| 12 | class Formatter(ABC): |
| 13 | slots: SLOTS = field(default_factory=list) |
| 14 | |
| 15 | @abstractmethod |
| 16 | def apply(self, **kwargs) -> SLOTS: |
| 17 | r"""Forms a list of slots according to the inputs to encode.""" |
| 18 | ... |
| 19 | |
| 20 | |
| 21 | @dataclass |
| 22 | class EmptyFormatter(Formatter): |
| 23 | def __post_init__(self): |
| 24 | has_placeholder = False |
| 25 | for slot in filter(lambda s: isinstance(s, str), self.slots): |
| 26 | if re.search(r"\{\{[a-zA-Z_][a-zA-Z0-9_]*\}\}", slot): |
| 27 | has_placeholder = True |
| 28 | |
| 29 | if has_placeholder: |
| 30 | raise ValueError("Empty formatter should not contain any placeholder.") |
| 31 | |
| 32 | @override |
| 33 | def apply(self, **kwargs) -> SLOTS: |
| 34 | return self.slots |
| 35 | |
| 36 | |
| 37 | @dataclass |
| 38 | class StringFormatter(Formatter): |
| 39 | def __post_init__(self): |
| 40 | has_placeholder = False |
| 41 | for slot in filter(lambda s: isinstance(s, str), self.slots): |
| 42 | if re.search(r"\{\{[a-zA-Z_][a-zA-Z0-9_]*\}\}", slot): |
| 43 | has_placeholder = True |
| 44 | |
| 45 | if not has_placeholder: |
| 46 | raise ValueError("A placeholder is required in the string formatter.") |
| 47 | |
| 48 | @override |
| 49 | def apply(self, **kwargs) -> SLOTS: |
| 50 | elements = [] |
| 51 | for slot in self.slots: |
| 52 | if isinstance(slot, str): |
| 53 | for name, value in kwargs.items(): |
| 54 | if not isinstance(value, str): |
| 55 | raise RuntimeError(f"Expected a string, got {value}") |
| 56 | |
| 57 | slot = slot.replace("{{" + name + "}}", value, 1) |
| 58 | elements.append(slot) |
| 59 | elif isinstance(slot, (dict, set)): |
| 60 | elements.append(slot) |
| 61 | else: |
| 62 | raise RuntimeError( |
| 63 | f"Input must be string, set[str] or dict[str, str], got {type(slot)}." |
| 64 | ) |
| 65 | |
| 66 | return elements |