variable.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. from __future__ import annotations
  2. from typing import Any, Dict, List, Optional, Set, TYPE_CHECKING
  3. from urllib.parse import urlparse
  4. import logging
  5. import re
  6. from .exceptions import VariableValidationError, VariableError
  7. if TYPE_CHECKING:
  8. from .section import VariableSection
  9. logger = logging.getLogger(__name__)
  10. TRUE_VALUES = {"true", "1", "yes", "on"}
  11. FALSE_VALUES = {"false", "0", "no", "off"}
  12. EMAIL_REGEX = re.compile(r"^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$")
  13. class Variable:
  14. """Represents a single templating variable with lightweight validation."""
  15. def __init__(self, data: dict[str, Any]) -> None:
  16. """Initialize Variable from a dictionary containing variable specification.
  17. Args:
  18. data: Dictionary containing variable specification with required 'name' key
  19. and optional keys: description, type, options, prompt, value, default, section, origin
  20. Raises:
  21. ValueError: If data is not a dict, missing 'name' key, or has invalid default value
  22. """
  23. # Validate input
  24. if not isinstance(data, dict):
  25. raise VariableError("Variable data must be a dictionary")
  26. if "name" not in data:
  27. raise VariableError("Variable data must contain 'name' key")
  28. # Track which fields were explicitly provided in source data
  29. self._explicit_fields: Set[str] = set(data.keys())
  30. # Initialize fields
  31. self.name: str = data["name"]
  32. # Reference to parent section (set by VariableCollection)
  33. self.parent_section: Optional["VariableSection"] = data.get("parent_section")
  34. self.description: Optional[str] = data.get("description") or data.get(
  35. "display", ""
  36. )
  37. self.type: str = data.get("type", "str")
  38. self.options: Optional[List[Any]] = data.get("options", [])
  39. self.prompt: Optional[str] = data.get("prompt")
  40. if "value" in data:
  41. self.value: Any = data.get("value")
  42. elif "default" in data:
  43. self.value: Any = data.get("default")
  44. else:
  45. self.value: Any = None
  46. self.origin: Optional[str] = data.get("origin")
  47. self.sensitive: bool = data.get("sensitive", False)
  48. # Optional extra explanation used by interactive prompts
  49. self.extra: Optional[str] = data.get("extra")
  50. # Flag indicating this variable should be auto-generated when empty
  51. self.autogenerated: bool = data.get("autogenerated", False)
  52. # Flag indicating this variable is required even when section is disabled
  53. self.required: bool = data.get("required", False)
  54. # Flag indicating this variable can be empty/optional
  55. self.optional: bool = data.get("optional", False)
  56. # Original value before config override (used for display)
  57. self.original_value: Optional[Any] = data.get("original_value")
  58. # Variable dependencies - can be string or list of strings in format "var_name=value"
  59. # Supports semicolon-separated multiple conditions: "var1=value1;var2=value2,value3"
  60. needs_value = data.get("needs")
  61. if needs_value:
  62. if isinstance(needs_value, str):
  63. # Split by semicolon to support multiple AND conditions in a single string
  64. # Example: "traefik_enabled=true;network_mode=bridge,macvlan"
  65. self.needs: List[str] = [
  66. need.strip() for need in needs_value.split(";") if need.strip()
  67. ]
  68. elif isinstance(needs_value, list):
  69. self.needs: List[str] = needs_value
  70. else:
  71. raise VariableError(
  72. f"Variable '{self.name}' has invalid 'needs' value: must be string or list"
  73. )
  74. else:
  75. self.needs: List[str] = []
  76. # Validate and convert the default/initial value if present
  77. if self.value is not None:
  78. try:
  79. self.value = self.convert(self.value)
  80. except ValueError as exc:
  81. raise VariableValidationError(self.name, f"Invalid default value: {exc}")
  82. def convert(self, value: Any) -> Any:
  83. """Validate and convert a raw value based on the variable type.
  84. This method performs type conversion but does NOT check if the value
  85. is required. Use validate_and_convert() for full validation including
  86. required field checks.
  87. """
  88. if value is None:
  89. return None
  90. # Treat empty strings as None to avoid storing "" for missing values.
  91. if isinstance(value, str) and value.strip() == "":
  92. return None
  93. # Type conversion mapping for cleaner code
  94. converters = {
  95. "bool": self._convert_bool,
  96. "int": self._convert_int,
  97. "float": self._convert_float,
  98. "enum": self._convert_enum,
  99. "url": self._convert_url,
  100. "email": self._convert_email,
  101. }
  102. converter = converters.get(self.type)
  103. if converter:
  104. return converter(value)
  105. # Default to string conversion
  106. return str(value)
  107. def validate_and_convert(self, value: Any, check_required: bool = True) -> Any:
  108. """Validate and convert a value with comprehensive checks.
  109. This method combines type conversion with validation logic including
  110. required field checks. It's the recommended method for user input validation.
  111. Args:
  112. value: The raw value to validate and convert
  113. check_required: If True, raises ValueError for required fields with empty values
  114. Returns:
  115. The converted and validated value
  116. Raises:
  117. ValueError: If validation fails (invalid format, required field empty, etc.)
  118. Examples:
  119. # Basic validation
  120. var.validate_and_convert("example@email.com") # Returns validated email
  121. # Required field validation
  122. var.validate_and_convert("", check_required=True) # Raises ValueError if required
  123. # Autogenerated variables - allow empty values
  124. var.validate_and_convert("", check_required=False) # Returns None for autogeneration
  125. """
  126. # First, convert the value using standard type conversion
  127. converted = self.convert(value)
  128. # Special handling for autogenerated variables
  129. # Allow empty values as they will be auto-generated later
  130. if self.autogenerated and (
  131. converted is None
  132. or (
  133. isinstance(converted, str) and (converted == "" or converted == "*auto")
  134. )
  135. ):
  136. return None # Signal that auto-generation should happen
  137. # Allow empty values for optional variables
  138. if self.optional and (
  139. converted is None or (isinstance(converted, str) and converted == "")
  140. ):
  141. return None
  142. # Check if this is a required field and the value is empty
  143. if check_required and self.is_required():
  144. if converted is None or (isinstance(converted, str) and converted == ""):
  145. raise ValueError("This field is required and cannot be empty")
  146. return converted
  147. def _convert_bool(self, value: Any) -> bool:
  148. """Convert value to boolean."""
  149. if isinstance(value, bool):
  150. return value
  151. if isinstance(value, str):
  152. lowered = value.strip().lower()
  153. if lowered in TRUE_VALUES:
  154. return True
  155. if lowered in FALSE_VALUES:
  156. return False
  157. raise ValueError("value must be a boolean (true/false)")
  158. def _convert_int(self, value: Any) -> Optional[int]:
  159. """Convert value to integer."""
  160. if isinstance(value, int):
  161. return value
  162. if isinstance(value, str) and value.strip() == "":
  163. return None
  164. try:
  165. return int(value)
  166. except (TypeError, ValueError) as exc:
  167. raise ValueError("value must be an integer") from exc
  168. def _convert_float(self, value: Any) -> Optional[float]:
  169. """Convert value to float."""
  170. if isinstance(value, float):
  171. return value
  172. if isinstance(value, str) and value.strip() == "":
  173. return None
  174. try:
  175. return float(value)
  176. except (TypeError, ValueError) as exc:
  177. raise ValueError("value must be a float") from exc
  178. def _convert_enum(self, value: Any) -> Optional[str]:
  179. if value == "":
  180. return None
  181. val = str(value)
  182. if self.options and val not in self.options:
  183. raise ValueError(f"value must be one of: {', '.join(self.options)}")
  184. return val
  185. def _convert_url(self, value: Any) -> str:
  186. val = str(value).strip()
  187. if not val:
  188. return None
  189. parsed = urlparse(val)
  190. if not (parsed.scheme and parsed.netloc):
  191. raise ValueError("value must be a valid URL (include scheme and host)")
  192. return val
  193. def _convert_email(self, value: Any) -> str:
  194. val = str(value).strip()
  195. if not val:
  196. return None
  197. if not EMAIL_REGEX.fullmatch(val):
  198. raise ValueError("value must be a valid email address")
  199. return val
  200. def to_dict(self) -> Dict[str, Any]:
  201. """Serialize Variable to a dictionary for storage."""
  202. result = {}
  203. # Always include type
  204. if self.type:
  205. result["type"] = self.type
  206. # Include value/default if not None
  207. if self.value is not None:
  208. result["default"] = self.value
  209. # Include string fields if truthy
  210. for field in ("description", "prompt", "extra", "origin"):
  211. if value := getattr(self, field):
  212. result[field] = value
  213. # Include boolean/list fields if truthy (but empty list is OK for options)
  214. if self.sensitive:
  215. result["sensitive"] = True
  216. if self.autogenerated:
  217. result["autogenerated"] = True
  218. if self.required:
  219. result["required"] = True
  220. if self.optional:
  221. result["optional"] = True
  222. if self.options is not None: # Allow empty list
  223. result["options"] = self.options
  224. # Store dependencies (single value if only one, list otherwise)
  225. if self.needs:
  226. result["needs"] = self.needs[0] if len(self.needs) == 1 else self.needs
  227. return result
  228. def get_display_value(
  229. self, mask_sensitive: bool = True, max_length: int = 30, show_none: bool = True
  230. ) -> str:
  231. """Get formatted display value with optional masking and truncation.
  232. Args:
  233. mask_sensitive: If True, mask sensitive values with asterisks
  234. max_length: Maximum length before truncation (0 = no limit)
  235. show_none: If True, display "(none)" for None values instead of empty string
  236. Returns:
  237. Formatted string representation of the value
  238. """
  239. if self.value is None or self.value == "":
  240. # Show (*auto) for autogenerated variables instead of (none)
  241. if self.autogenerated:
  242. return "[dim](*auto)[/dim]" if show_none else ""
  243. return "[dim](none)[/dim]" if show_none else ""
  244. # Mask sensitive values
  245. if self.sensitive and mask_sensitive:
  246. return "********"
  247. # Convert to string
  248. display = str(self.value)
  249. # Truncate if needed
  250. if max_length > 0 and len(display) > max_length:
  251. return display[: max_length - 3] + "..."
  252. return display
  253. def get_normalized_default(self) -> Any:
  254. """Get normalized default value suitable for prompts and display."""
  255. try:
  256. typed = self.convert(self.value)
  257. except Exception:
  258. typed = self.value
  259. # Autogenerated: return display hint
  260. if self.autogenerated and not typed:
  261. return "*auto"
  262. # Type-specific handlers
  263. if self.type == "enum":
  264. if not self.options:
  265. return typed
  266. return (
  267. self.options[0]
  268. if typed is None or str(typed) not in self.options
  269. else str(typed)
  270. )
  271. if self.type == "bool":
  272. return (
  273. typed
  274. if isinstance(typed, bool)
  275. else (None if typed is None else bool(typed))
  276. )
  277. if self.type == "int":
  278. try:
  279. return int(typed) if typed not in (None, "") else None
  280. except Exception:
  281. return None
  282. # Default: return string or None
  283. return None if typed is None else str(typed)
  284. def get_prompt_text(self) -> str:
  285. """Get formatted prompt text for interactive input.
  286. Returns:
  287. Prompt text with optional type hints and descriptions
  288. """
  289. prompt_text = self.prompt or self.description or self.name
  290. # Add type hint for semantic types if there's a default
  291. if self.value is not None and self.type in ["email", "url"]:
  292. prompt_text += f" ({self.type})"
  293. return prompt_text
  294. def get_validation_hint(self) -> Optional[str]:
  295. """Get validation hint for prompts (e.g., enum options).
  296. Returns:
  297. Formatted hint string or None if no hint needed
  298. """
  299. hints = []
  300. # Add enum options
  301. if self.type == "enum" and self.options:
  302. hints.append(f"Options: {', '.join(self.options)}")
  303. # Add extra help text
  304. if self.extra:
  305. hints.append(self.extra)
  306. return " — ".join(hints) if hints else None
  307. def is_required(self) -> bool:
  308. """Check if this variable requires a value (cannot be empty/None).
  309. A variable is considered required if:
  310. - It has an explicit 'required: true' flag (highest precedence)
  311. - OR it doesn't have a default value (value is None)
  312. AND it's not marked as autogenerated (which can be empty and generated later)
  313. AND it's not marked as optional (which can be empty)
  314. AND it's not a boolean type (booleans default to False if not set)
  315. Returns:
  316. True if the variable must have a non-empty value, False otherwise
  317. """
  318. # Optional variables can always be empty
  319. if self.optional:
  320. return False
  321. # Explicit required flag takes highest precedence
  322. if self.required:
  323. # But autogenerated variables can still be empty (will be generated later)
  324. if self.autogenerated:
  325. return False
  326. return True
  327. # Autogenerated variables can be empty (will be generated later)
  328. if self.autogenerated:
  329. return False
  330. # Boolean variables always have a value (True or False)
  331. if self.type == "bool":
  332. return False
  333. # Variables with a default value are not required
  334. if self.value is not None:
  335. return False
  336. # No default value and not autogenerated = required
  337. return True
  338. def get_parent(self) -> Optional["VariableSection"]:
  339. """Get the parent VariableSection that contains this variable.
  340. Returns:
  341. The parent VariableSection if set, None otherwise
  342. """
  343. return self.parent_section
  344. def clone(self, update: Optional[Dict[str, Any]] = None) -> "Variable":
  345. """Create a deep copy of the variable with optional field updates.
  346. This is more efficient than converting to dict and back when copying variables.
  347. Args:
  348. update: Optional dictionary of field updates to apply to the clone
  349. Returns:
  350. New Variable instance with copied data
  351. Example:
  352. var2 = var1.clone(update={'origin': 'template'})
  353. """
  354. data = {
  355. "name": self.name,
  356. "type": self.type,
  357. "value": self.value,
  358. "description": self.description,
  359. "prompt": self.prompt,
  360. "options": self.options.copy() if self.options else None,
  361. "origin": self.origin,
  362. "sensitive": self.sensitive,
  363. "extra": self.extra,
  364. "autogenerated": self.autogenerated,
  365. "required": self.required,
  366. "optional": self.optional,
  367. "original_value": self.original_value,
  368. "needs": self.needs.copy() if self.needs else None,
  369. "parent_section": self.parent_section,
  370. }
  371. # Apply updates if provided
  372. if update:
  373. data.update(update)
  374. # Create new variable
  375. cloned = Variable(data)
  376. # Preserve explicit fields from original, and add any update keys
  377. cloned._explicit_fields = self._explicit_fields.copy()
  378. if update:
  379. cloned._explicit_fields.update(update.keys())
  380. return cloned