variable.py 17 KB

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