variable.py 17 KB

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