import re import string from enum import Enum from typing import List, Union class Cases(Enum): # Reference: https://stackoverflow.com/a/54330161 Plain = 10 Camel = 1 Snake = 2 Kebab = 3 Flat = 4 Macro = 5 Cobol = 6 Pascal = 7 Custom = 8 # Aliases Caterpillar = 3 Hyphen = 3 Spinal = 3 Dash = 3 Lisp = 3 Css = 3 CapitalCamel = 7 C = 2 Lower = 2 Upper = 5 Train = 6 class FromCase(list): def __init__(self, query: str, case: Cases = Cases.Plain, delimiter: str = ' ') -> List[str]: normalizedQuery = query.translate(str.maketrans('', '', string.punctuation.replace(delimiter, ''))) wordList = [] if case in ([Cases.Camel, Cases.Pascal]): wordList = re.findall('^[a-z]+|[A-Z][^A-Z]*', normalizedQuery) elif case in ([Cases.Snake, Cases.Macro]): wordList = normalizedQuery.split('_') elif case in ([Cases.Kebab, Cases.Cobol]): wordList = normalizedQuery.split('-') elif case is Cases.Plain: wordList = normalizedQuery.split() elif case is Cases.Custom: wordList = normalizedQuery.split(delimiter) else: raise Exception("Case not supported") return super().__init__(wordList) class Convert(str): def __new__(cls, query: Union[str, Union[List[str], FromCase]], case: Cases = Cases.Camel, delimiter: str = ' ') -> str: if isinstance(query, str): query = FromCase(query, Cases.Plain) words = [word.lower() for word in query] convertedStr: str = '' if case is Cases.Camel: convertedStr = words[0] + ''.join([word.capitalize() for word in words[1:]]) elif case is Cases.Snake: convertedStr = '_'.join(words) elif case is Cases.Kebab: convertedStr = '-'.join(words) elif case is Cases.Flat: convertedStr = ''.join(words) elif case is Cases.Macro: convertedStr = '_'.join(words).upper() elif case is Cases.Cobol: convertedStr = '-'.join(words).upper() elif case is Cases.Pascal: convertedStr = ''.join([word.capitalize() for word in words]) elif case is Cases.Plain: convertedStr = ' '.join(words) elif case is Cases.Custom: convertedStr = delimiter.join(words) else: raise Exception("Case not recognised") return super().__new__(cls, convertedStr)