Coretex
range_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, Dict, Optional, Tuple
19 
20 import logging
21 
22 from ..base_parameter import BaseParameter
23 from ..utils import validateRangeStructure
24 from ....project import ProjectType
25 
26 
27 RANGE_LIMIT = 2^32
28 
29 
30 class RangeParameter(BaseParameter[Dict[str, int]]):
31 
32  @property
33  def types(self) -> List[type]:
34  return NotImplemented
35 
36  def validate(self) -> Tuple[bool, Optional[str]]:
37  if not isinstance(self.value, dict):
38  return False, None
39 
40  isValid, message = validateRangeStructure(self.name, self.value, self.required)
41  if not isValid:
42  return isValid, message
43 
44  if self.value["to"] > RANGE_LIMIT:
45  return False, f"Range value \"to\" must not exceed 2^32"
46 
47  if not self.value["to"] > self.value["from"]:
48  return False, f"Range value \"to\" must not be greater then \"from\""
49 
50  if not self.value["step"] <= self.value["to"] - self.value["from"]:
51  return False, f"Range value \"step\" must be lower or equal to the distance between \"from\" and \"to\""
52 
53  return True, None
54 
55  def parseValue(self, type_: ProjectType) -> Optional[Any]:
56  if self.value is None:
57  return None
58 
59  return range(self.value["from"], self.value["to"], self.value["step"])
60 
61  def overrideValue(self, value: Optional[Any]) -> Optional[Any]:
62  if value is None or self.value is None:
63  return None
64 
65  try:
66  args = value.split(" ")
67  parsedValue: Dict[str, int] = {}
68 
69  # In case the only 2 values are entered, they will be treaded as "from" and "to"
70  # Default step is 1
71  if len(args) not in [2, 3]:
72  return None
73 
74  parsedValue["from"] = int(args[0])
75  parsedValue["to"] = int(args[1])
76  parsedValue["step"] = int(args[2]) if len(args) == 3 else 1
77 
78  return parsedValue
79  except ValueError as e:
80  logging.getLogger("coretexpylib").warning(f">> [Coretex] Failed to override range parameter \"{self.name}\". | {e}")
81  return self.value