OpoTests/Python/Modules/Format/MixFormat.py

77 lines
2.3 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Self, Any, Optional
from Interfaces.FormatModuleInterface import FormatModuleInterface
from Utils.Patterns import RE
from Utils.Check import Check
from Utils.Utils import Utils
class MixFormat:
def __init__(self:Self,
format:FormatModuleInterface,
options:Optional[dict[str, Any|None]] = None
) -> None:
self.format:FormatModuleInterface = format
self.capitalize:bool = bool(options and options.get("capitalized"))
def __get_separator_and_items(self:Self, i:int, inputs:str|list[Any|None]) -> tuple[str, list[str]]:
separator:str
original_items:list[str]
separator, original_items = (
(lambda _, separator, options:(
separator, str(options).split("|")
))(*RE.BASIC_MODE_SPLIT.match(inputs).groups()) if Check.is_string(inputs) else
inputs if Check.is_array(inputs) else
(None, None))
return separator, self.format.get_list(i, original_items)
def get(self:Self,
i:int,
inputs:str|list[Any|None],
shared:dict[str, Any|None] = {},
fragments:list[str] = []
) -> str:
separator:str
items:list[str]
l:int
results:str
separator, items = self.__get_separator_and_items(i, inputs)
l = len(items)
Utils.randomize_array(items)
results = self.format.execute(i, (
"".join(items) if l < 2 else
", ".join(items[:l - 1]) + (
" " if not separator else
" " + separator.strip() + " " if RE.IS_SEPARATOR.match(separator) else
separator) + items[l - 1]), shared, fragments)
return RE.CAPITAL_CASE.sub(lambda matches:(
matches.group(1).upper()
), results) if self.capitalize else results
def check(self:Self,
i:int,
string:str,
inputs:str|list[Any|None],
shared:dict[str, Any|None] = {},
fragments:list[str] = []
) -> int:
separator:str
items:list[str]
l:int
separator, items = self.__get_separator_and_items(i, inputs)
l = len(items)
return self.format.check_select(i, string, ((l, l), separator, items), shared, fragments)