Coretex
enum_parameter.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import Any, List, Optional, Tuple, Dict
19 
20 import logging
21 
22 from ..base_parameter import BaseParameter
23 from ..utils import validateEnumStructure
24 from ....project import ProjectType
25 
26 
27 class EnumParameter(BaseParameter[Dict[str, Any]]):
28 
29  @property
30  def types(self) -> List[type]:
31  return NotImplemented
32 
33  def validate(self) -> Tuple[bool, Optional[str]]:
34  isValid, message = validateEnumStructure(self.name, self.value, self.required)
35  if not isValid:
36  return isValid, message
37 
38  # validateEnumStructure already checks if value is of correct type
39  value: Dict[str, Any] = self.value # type: ignore[assignment]
40 
41  selected = value["selected"]
42  options = value["options"]
43 
44  if selected is None and not self.required:
45  return True, None
46 
47  if not type(selected) is int:
48  return False, f"Enum parameter \"{self.name}.selected\" has invalid type. Expected \"int\", got \"{type(selected).__name__}\""
49 
50  if selected >= len(options) or selected < 0:
51  return False, f"Enum parameter \"{self.name}.selected\" has out of range value"
52 
53  return True, None
54 
55  def parseValue(self, type_: ProjectType) -> Optional[Any]:
56  if self.value is None:
57  return self.value
58 
59  selected: Optional[int] = self.value.get("selected")
60  if selected is None:
61  return None
62 
63  return self.value["options"][selected]
64 
65  def overrideValue(self, value: Optional[Any]) -> Optional[Any]:
66  if value is None or self.value is None:
67  return None
68 
69  try:
70  parsedValue: Dict[str, Any] = self.value
71  parsedValue["selected"] = int(value)
72  return parsedValue
73  except ValueError as e:
74  logging.getLogger("coretexpylib").warning(f">> [Coretex] Failed to override enum parameter \"{self.name}\". | {e}")
75  return self.value