diff --git a/genopts/genopts.py b/genopts/genopts.py index 9c1fff8b02f3af618aa07889a577fe769c974fa7..f0859b22185c7972c49fe5a97d791054cd1974fc 100755 --- a/genopts/genopts.py +++ b/genopts/genopts.py @@ -287,10 +287,26 @@ class Config: f"keywords_config={self.keywords_config})" -class Option: +class Option(ABC): name: str type: str required: bool + + def __init__(self, name: str, type: str, required: bool): + self.name = name + self.type = type + self.required = required + + @abstractmethod + def __repr__(self) -> str: + return NotImplemented + + @abstractmethod + def __str__(self) -> str: + return NotImplemented + + +class ConvertibleOption(Option): converter: Optional[str] template: str = """\ declare_option<{type}>( @@ -300,9 +316,7 @@ declare_option<{type}>( """ def __init__(self, name: str, type: str, required: bool, converter: Optional[str] = None): - self.name = name - self.type = type - self.required = required + super().__init__(name, type, required) self.converter = converter def __repr__(self) -> str: @@ -314,6 +328,33 @@ declare_option<{type}>( converter=self.converter) +class NonConvertibleOption(Option): + template: str = """\ + declare_option<{type}>( + keywords::{name}, + opt_type::{required}) + """ + + def __init__(self, name: str, type: str, required: bool): + super().__init__(name, type, required) + + def __repr__(self) -> str: + return f"Option(name='{self.name}', type='{self.type}', required={self.required})" + + def __str__(self) -> str: + return self.template.format(name=self.name, type=self.type, + required="mandatory" if self.required else "optional") + + +class OptionFactory: + @staticmethod + def create_option(name: str, type: str, required: bool, converter: Optional[str] = None) -> Option: + if converter: + return ConvertibleOption(name, type, required, converter) + else: + return NonConvertibleOption(name, type, required) + + class Section: name: str required: bool @@ -378,10 +419,10 @@ class Generator: for opt in s['options']: options.append( - Option(opt['name'], - opt['type'], - opt['required'], - opt.get('converter', None))) + OptionFactory.create_option(opt['name'], + opt['type'], + opt['required'], + opt.get('converter', None))) if section_name not in self.keywords_by_section: self.keywords_by_section[section_name] = []