variables.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. from __future__ import annotations
  2. from collections import OrderedDict
  3. from dataclasses import dataclass, field
  4. from typing import Any, Dict, List, Optional, Set, Union
  5. from urllib.parse import urlparse
  6. import logging
  7. import re
  8. logger = logging.getLogger(__name__)
  9. # -----------------------
  10. # SECTION: Constants
  11. # -----------------------
  12. TRUE_VALUES = {"true", "1", "yes", "on"}
  13. FALSE_VALUES = {"false", "0", "no", "off"}
  14. HOSTNAME_REGEX = re.compile(r"^(?=.{1,253}$)(?!-)[A-Za-z0-9_-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9_-]{1,63}(?<!-))*$")
  15. EMAIL_REGEX = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
  16. # !SECTION
  17. # ----------------------
  18. # SECTION: Variable Class
  19. # ----------------------
  20. class Variable:
  21. """Represents a single templating variable with lightweight validation."""
  22. def __init__(self, data: dict[str, Any]) -> None:
  23. """Initialize Variable from a dictionary containing variable specification.
  24. Args:
  25. data: Dictionary containing variable specification with required 'name' key
  26. and optional keys: description, type, options, prompt, value, default, section, origin
  27. Raises:
  28. ValueError: If data is not a dict, missing 'name' key, or has invalid default value
  29. """
  30. # Validate input
  31. if not isinstance(data, dict):
  32. raise ValueError("Variable data must be a dictionary")
  33. if "name" not in data:
  34. raise ValueError("Variable data must contain 'name' key")
  35. # Track which fields were explicitly provided in source data
  36. self._explicit_fields: Set[str] = set(data.keys())
  37. # Initialize fields
  38. self.name: str = data["name"]
  39. self.description: Optional[str] = data.get("description") or data.get("display", "")
  40. self.type: str = data.get("type", "str")
  41. self.options: Optional[List[Any]] = data.get("options", [])
  42. self.prompt: Optional[str] = data.get("prompt")
  43. self.value: Any = data.get("value") if data.get("value") is not None else data.get("default")
  44. self.section: Optional[str] = data.get("section")
  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. # Validate and convert the default/initial value if present
  52. if self.value is not None:
  53. try:
  54. self.value = self.convert(self.value)
  55. except ValueError as exc:
  56. raise ValueError(f"Invalid default for variable '{self.name}': {exc}")
  57. # -------------------------
  58. # SECTION: Validation Helpers
  59. # -------------------------
  60. def _validate_not_empty(self, value: Any, converted_value: Any) -> None:
  61. """Validate that a value is not empty for non-boolean types."""
  62. if self.type not in ["bool"] and (converted_value is None or converted_value == ""):
  63. raise ValueError("value cannot be empty")
  64. def _validate_enum_option(self, value: str) -> None:
  65. """Validate that a value is in the allowed enum options."""
  66. if self.options and value not in self.options:
  67. raise ValueError(f"value must be one of: {', '.join(self.options)}")
  68. def _validate_regex_pattern(self, value: str, pattern: re.Pattern, error_msg: str) -> None:
  69. """Validate that a value matches a regex pattern."""
  70. if not pattern.fullmatch(value):
  71. raise ValueError(error_msg)
  72. def _validate_url_structure(self, parsed_url) -> None:
  73. """Validate that a parsed URL has required components."""
  74. if not (parsed_url.scheme and parsed_url.netloc):
  75. raise ValueError("value must be a valid URL (include scheme and host)")
  76. # !SECTION
  77. # -------------------------
  78. # SECTION: Type Conversion
  79. # -------------------------
  80. def convert(self, value: Any) -> Any:
  81. """Validate and convert a raw value based on the variable type."""
  82. if value is None:
  83. return None
  84. # Treat empty strings as None to avoid storing "" for missing values.
  85. if isinstance(value, str) and value.strip() == "":
  86. return None
  87. # Type conversion mapping for cleaner code
  88. converters = {
  89. "bool": self._convert_bool,
  90. "int": self._convert_int,
  91. "float": self._convert_float,
  92. "enum": self._convert_enum,
  93. "hostname": self._convert_hostname,
  94. "url": self._convert_url,
  95. "email": self._convert_email,
  96. }
  97. converter = converters.get(self.type)
  98. if converter:
  99. return converter(value)
  100. # Default to string conversion
  101. return str(value)
  102. def _convert_bool(self, value: Any) -> bool:
  103. """Convert value to boolean."""
  104. if isinstance(value, bool):
  105. return value
  106. if isinstance(value, str):
  107. lowered = value.strip().lower()
  108. if lowered in TRUE_VALUES:
  109. return True
  110. if lowered in FALSE_VALUES:
  111. return False
  112. raise ValueError("value must be a boolean (true/false)")
  113. def _convert_int(self, value: Any) -> Optional[int]:
  114. """Convert value to integer."""
  115. if isinstance(value, int):
  116. return value
  117. if isinstance(value, str) and value.strip() == "":
  118. return None
  119. try:
  120. return int(value)
  121. except (TypeError, ValueError) as exc:
  122. raise ValueError("value must be an integer") from exc
  123. def _convert_float(self, value: Any) -> Optional[float]:
  124. """Convert value to float."""
  125. if isinstance(value, float):
  126. return value
  127. if isinstance(value, str) and value.strip() == "":
  128. return None
  129. try:
  130. return float(value)
  131. except (TypeError, ValueError) as exc:
  132. raise ValueError("value must be a float") from exc
  133. def _convert_enum(self, value: Any) -> Optional[str]:
  134. """Convert value to enum option."""
  135. if value == "":
  136. return None
  137. val = str(value)
  138. self._validate_enum_option(val)
  139. return val
  140. def _convert_hostname(self, value: Any) -> str:
  141. """Convert and validate hostname."""
  142. val = str(value).strip()
  143. if not val:
  144. return None
  145. if val.lower() != "localhost":
  146. self._validate_regex_pattern(val, HOSTNAME_REGEX, "value must be a valid hostname")
  147. return val
  148. def _convert_url(self, value: Any) -> str:
  149. """Convert and validate URL."""
  150. val = str(value).strip()
  151. if not val:
  152. return None
  153. parsed = urlparse(val)
  154. self._validate_url_structure(parsed)
  155. return val
  156. def _convert_email(self, value: Any) -> str:
  157. """Convert and validate email."""
  158. val = str(value).strip()
  159. if not val:
  160. return None
  161. self._validate_regex_pattern(val, EMAIL_REGEX, "value must be a valid email address")
  162. return val
  163. def get_typed_value(self) -> Any:
  164. """Return the stored value converted to the appropriate Python type."""
  165. return self.convert(self.value)
  166. def to_dict(self) -> Dict[str, Any]:
  167. """Serialize Variable to a dictionary for storage.
  168. Returns:
  169. Dictionary representation of the variable with only relevant fields.
  170. """
  171. var_dict = {}
  172. if self.type:
  173. var_dict["type"] = self.type
  174. if self.value is not None:
  175. var_dict["default"] = self.value
  176. if self.description:
  177. var_dict["description"] = self.description
  178. if self.prompt:
  179. var_dict["prompt"] = self.prompt
  180. if self.sensitive:
  181. var_dict["sensitive"] = self.sensitive
  182. if self.extra:
  183. var_dict["extra"] = self.extra
  184. if self.autogenerated:
  185. var_dict["autogenerated"] = self.autogenerated
  186. if self.options:
  187. var_dict["options"] = self.options
  188. if self.origin:
  189. var_dict["origin"] = self.origin
  190. return var_dict
  191. # -------------------------
  192. # SECTION: Display Methods
  193. # -------------------------
  194. def get_display_value(self, mask_sensitive: bool = True, max_length: int = 30) -> str:
  195. """Get formatted display value with optional masking and truncation.
  196. Args:
  197. mask_sensitive: If True, mask sensitive values with asterisks
  198. max_length: Maximum length before truncation (0 = no limit)
  199. Returns:
  200. Formatted string representation of the value
  201. """
  202. if self.value is None:
  203. return ""
  204. # Mask sensitive values
  205. if self.sensitive and mask_sensitive:
  206. return "********"
  207. # Convert to string
  208. display = str(self.value)
  209. # Truncate if needed
  210. if max_length > 0 and len(display) > max_length:
  211. return display[:max_length - 3] + "..."
  212. return display
  213. def get_normalized_default(self) -> Any:
  214. """Get normalized default value suitable for prompts and display.
  215. Handles type conversion and provides sensible defaults for different types.
  216. Especially useful for enum, bool, and int types in interactive prompts.
  217. Returns:
  218. Normalized default value appropriate for the variable type
  219. """
  220. try:
  221. typed = self.get_typed_value()
  222. except Exception:
  223. typed = self.value
  224. # Enum: ensure default is valid option
  225. if self.type == "enum":
  226. if not self.options:
  227. return typed
  228. # If typed is invalid or missing, use first option
  229. if typed is None or str(typed) not in self.options:
  230. return self.options[0]
  231. return str(typed)
  232. # Boolean: return as bool type
  233. if self.type == "bool":
  234. if isinstance(typed, bool):
  235. return typed
  236. return None if typed is None else bool(typed)
  237. # Integer: return as int type
  238. if self.type == "int":
  239. try:
  240. return int(typed) if typed is not None and typed != "" else None
  241. except Exception:
  242. return None
  243. # Default: return string or None
  244. return None if typed is None else str(typed)
  245. def get_prompt_text(self) -> str:
  246. """Get formatted prompt text for interactive input.
  247. Returns:
  248. Prompt text with optional type hints and descriptions
  249. """
  250. prompt_text = self.prompt or self.description or self.name
  251. # Add type hint for semantic types if there's a default
  252. if self.value is not None and self.type in ["hostname", "email", "url"]:
  253. prompt_text += f" ({self.type})"
  254. return prompt_text
  255. def get_validation_hint(self) -> Optional[str]:
  256. """Get validation hint for prompts (e.g., enum options).
  257. Returns:
  258. Formatted hint string or None if no hint needed
  259. """
  260. hints = []
  261. # Add enum options
  262. if self.type == "enum" and self.options:
  263. hints.append(f"Options: {', '.join(self.options)}")
  264. # Add extra help text
  265. if self.extra:
  266. hints.append(self.extra)
  267. return " — ".join(hints) if hints else None
  268. def clone(self, update: Optional[Dict[str, Any]] = None) -> 'Variable':
  269. """Create a deep copy of the variable with optional field updates.
  270. This is more efficient than converting to dict and back when copying variables.
  271. Args:
  272. update: Optional dictionary of field updates to apply to the clone
  273. Returns:
  274. New Variable instance with copied data
  275. Example:
  276. var2 = var1.clone(update={'origin': 'template'})
  277. """
  278. data = {
  279. 'name': self.name,
  280. 'type': self.type,
  281. 'value': self.value,
  282. 'description': self.description,
  283. 'prompt': self.prompt,
  284. 'options': self.options.copy() if self.options else None,
  285. 'section': self.section,
  286. 'origin': self.origin,
  287. 'sensitive': self.sensitive,
  288. 'extra': self.extra,
  289. 'autogenerated': self.autogenerated,
  290. }
  291. # Apply updates if provided
  292. if update:
  293. data.update(update)
  294. # Create new variable
  295. cloned = Variable(data)
  296. # Preserve explicit fields from original, and add any update keys
  297. cloned._explicit_fields = self._explicit_fields.copy()
  298. if update:
  299. cloned._explicit_fields.update(update.keys())
  300. return cloned
  301. # !SECTION
  302. # !SECTION
  303. # ----------------------------
  304. # SECTION: VariableSection Class
  305. # ----------------------------
  306. class VariableSection:
  307. """Groups variables together with shared metadata for presentation."""
  308. def __init__(self, data: dict[str, Any]) -> None:
  309. """Initialize VariableSection from a dictionary.
  310. Args:
  311. data: Dictionary containing section specification with required 'key' and 'title' keys
  312. """
  313. if not isinstance(data, dict):
  314. raise ValueError("VariableSection data must be a dictionary")
  315. if "key" not in data:
  316. raise ValueError("VariableSection data must contain 'key'")
  317. if "title" not in data:
  318. raise ValueError("VariableSection data must contain 'title'")
  319. self.key: str = data["key"]
  320. self.title: str = data["title"]
  321. self.variables: OrderedDict[str, Variable] = OrderedDict()
  322. self.description: Optional[str] = data.get("description")
  323. self.toggle: Optional[str] = data.get("toggle")
  324. # Default "general" section to required=True, all others to required=False
  325. self.required: bool = data.get("required", data["key"] == "general")
  326. # Section dependencies - can be string or list of strings
  327. needs_value = data.get("needs")
  328. if needs_value:
  329. if isinstance(needs_value, str):
  330. self.needs: List[str] = [needs_value]
  331. elif isinstance(needs_value, list):
  332. self.needs: List[str] = needs_value
  333. else:
  334. raise ValueError(f"Section '{self.key}' has invalid 'needs' value: must be string or list")
  335. else:
  336. self.needs: List[str] = []
  337. def variable_names(self) -> list[str]:
  338. return list(self.variables.keys())
  339. def to_dict(self) -> Dict[str, Any]:
  340. """Serialize VariableSection to a dictionary for storage.
  341. Returns:
  342. Dictionary representation of the section with all metadata and variables.
  343. """
  344. section_dict = {}
  345. if self.title:
  346. section_dict["title"] = self.title
  347. if self.description:
  348. section_dict["description"] = self.description
  349. if self.toggle:
  350. section_dict["toggle"] = self.toggle
  351. # Always store required flag
  352. section_dict["required"] = self.required
  353. # Store dependencies if any
  354. if self.needs:
  355. section_dict["needs"] = self.needs if len(self.needs) > 1 else self.needs[0]
  356. # Serialize all variables using their own to_dict method
  357. section_dict["vars"] = {}
  358. for var_name, variable in self.variables.items():
  359. section_dict["vars"][var_name] = variable.to_dict()
  360. return section_dict
  361. # -------------------------
  362. # SECTION: State Methods
  363. # -------------------------
  364. def is_enabled(self) -> bool:
  365. """Check if section is currently enabled based on toggle variable.
  366. Returns:
  367. True if section is enabled (no toggle or toggle is True), False otherwise
  368. """
  369. if not self.toggle:
  370. return True
  371. toggle_var = self.variables.get(self.toggle)
  372. if not toggle_var:
  373. return True
  374. try:
  375. return bool(toggle_var.get_typed_value())
  376. except Exception:
  377. return False
  378. def get_toggle_value(self) -> Optional[bool]:
  379. """Get the current value of the toggle variable.
  380. Returns:
  381. Boolean value of toggle variable, or None if no toggle exists
  382. """
  383. if not self.toggle:
  384. return None
  385. toggle_var = self.variables.get(self.toggle)
  386. if not toggle_var:
  387. return None
  388. try:
  389. return bool(toggle_var.get_typed_value())
  390. except Exception:
  391. return None
  392. def clone(self, origin_update: Optional[str] = None) -> 'VariableSection':
  393. """Create a deep copy of the section with all variables.
  394. This is more efficient than converting to dict and back when copying sections.
  395. Args:
  396. origin_update: Optional origin string to apply to all cloned variables
  397. Returns:
  398. New VariableSection instance with deep-copied variables
  399. Example:
  400. section2 = section1.clone(origin_update='template')
  401. """
  402. # Create new section with same metadata
  403. cloned = VariableSection({
  404. 'key': self.key,
  405. 'title': self.title,
  406. 'description': self.description,
  407. 'toggle': self.toggle,
  408. 'required': self.required,
  409. 'needs': self.needs.copy() if self.needs else None,
  410. })
  411. # Deep copy all variables
  412. for var_name, variable in self.variables.items():
  413. if origin_update:
  414. cloned.variables[var_name] = variable.clone(update={'origin': origin_update})
  415. else:
  416. cloned.variables[var_name] = variable.clone()
  417. return cloned
  418. # !SECTION
  419. # !SECTION
  420. # --------------------------------
  421. # SECTION: VariableCollection Class
  422. # --------------------------------
  423. class VariableCollection:
  424. """Manages variables grouped by sections and builds Jinja context."""
  425. def __init__(self, spec: dict[str, Any]) -> None:
  426. """Initialize VariableCollection from a specification dictionary.
  427. Args:
  428. spec: Dictionary containing the complete variable specification structure
  429. Expected format (as used in compose.py):
  430. {
  431. "section_key": {
  432. "title": "Section Title",
  433. "prompt": "Optional prompt text",
  434. "toggle": "optional_toggle_var_name",
  435. "description": "Optional description",
  436. "vars": {
  437. "var_name": {
  438. "description": "Variable description",
  439. "type": "str",
  440. "default": "default_value",
  441. ...
  442. }
  443. }
  444. }
  445. }
  446. """
  447. if not isinstance(spec, dict):
  448. raise ValueError("Spec must be a dictionary")
  449. self._sections: Dict[str, VariableSection] = {}
  450. # NOTE: The _variable_map provides a flat, O(1) lookup for any variable by its name,
  451. # avoiding the need to iterate through sections. It stores references to the same
  452. # Variable objects contained in the _set structure.
  453. self._variable_map: Dict[str, Variable] = {}
  454. self._initialize_sections(spec)
  455. # Validate dependencies after all sections are loaded
  456. self._validate_dependencies()
  457. def _initialize_sections(self, spec: dict[str, Any]) -> None:
  458. """Initialize sections from the spec."""
  459. for section_key, section_data in spec.items():
  460. if not isinstance(section_data, dict):
  461. continue
  462. section = self._create_section(section_key, section_data)
  463. # Guard against None from empty YAML sections (vars: with no content)
  464. vars_data = section_data.get("vars") or {}
  465. self._initialize_variables(section, vars_data)
  466. self._sections[section_key] = section
  467. def _create_section(self, key: str, data: dict[str, Any]) -> VariableSection:
  468. """Create a VariableSection from data."""
  469. section_init_data = {
  470. "key": key,
  471. "title": data.get("title", key.replace("_", " ").title()),
  472. "description": data.get("description"),
  473. "toggle": data.get("toggle"),
  474. "required": data.get("required", key == "general"),
  475. "needs": data.get("needs")
  476. }
  477. return VariableSection(section_init_data)
  478. def _initialize_variables(self, section: VariableSection, vars_data: dict[str, Any]) -> None:
  479. """Initialize variables for a section."""
  480. # Guard against None from empty YAML sections
  481. if vars_data is None:
  482. vars_data = {}
  483. for var_name, var_data in vars_data.items():
  484. var_init_data = {"name": var_name, **var_data}
  485. variable = Variable(var_init_data)
  486. section.variables[var_name] = variable
  487. # NOTE: Populate the direct lookup map for efficient access.
  488. self._variable_map[var_name] = variable
  489. # Validate toggle variable after all variables are added
  490. self._validate_section_toggle(section)
  491. # FIXME: Add more section-level validation here as needed:
  492. # - Validate that variable names don't conflict across sections (currently allowed but could be confusing)
  493. # - Validate that required sections have at least one non-toggle variable
  494. # - Validate that enum variables have non-empty options lists
  495. # - Validate that variable names follow naming conventions (e.g., lowercase_with_underscores)
  496. # - Validate that default values are compatible with their type definitions
  497. def _validate_section_toggle(self, section: VariableSection) -> None:
  498. """Validate that toggle variable is of type bool if it exists.
  499. If the toggle variable doesn't exist (e.g., filtered out), removes the toggle.
  500. Args:
  501. section: The section to validate
  502. Raises:
  503. ValueError: If toggle variable exists but is not boolean type
  504. """
  505. if not section.toggle:
  506. return
  507. toggle_var = section.variables.get(section.toggle)
  508. if not toggle_var:
  509. # Toggle variable doesn't exist (e.g., was filtered out) - remove toggle metadata
  510. section.toggle = None
  511. return
  512. if toggle_var.type != "bool":
  513. raise ValueError(
  514. f"Section '{section.key}' toggle variable '{section.toggle}' must be type 'bool', "
  515. f"but is type '{toggle_var.type}'"
  516. )
  517. def _validate_dependencies(self) -> None:
  518. """Validate section dependencies for cycles and missing references.
  519. Raises:
  520. ValueError: If circular dependencies or missing section references are found
  521. """
  522. # Check for missing dependencies
  523. for section_key, section in self._sections.items():
  524. for dep in section.needs:
  525. if dep not in self._sections:
  526. raise ValueError(
  527. f"Section '{section_key}' depends on '{dep}', but '{dep}' does not exist"
  528. )
  529. # Check for circular dependencies using depth-first search
  530. visited = set()
  531. rec_stack = set()
  532. def has_cycle(section_key: str) -> bool:
  533. visited.add(section_key)
  534. rec_stack.add(section_key)
  535. section = self._sections[section_key]
  536. for dep in section.needs:
  537. if dep not in visited:
  538. if has_cycle(dep):
  539. return True
  540. elif dep in rec_stack:
  541. raise ValueError(
  542. f"Circular dependency detected: '{section_key}' depends on '{dep}', "
  543. f"which creates a cycle"
  544. )
  545. rec_stack.remove(section_key)
  546. return False
  547. for section_key in self._sections:
  548. if section_key not in visited:
  549. has_cycle(section_key)
  550. def is_section_satisfied(self, section_key: str) -> bool:
  551. """Check if all dependencies for a section are satisfied.
  552. A dependency is satisfied if:
  553. 1. The dependency section exists
  554. 2. The dependency section is enabled (if it has a toggle)
  555. Args:
  556. section_key: The key of the section to check
  557. Returns:
  558. True if all dependencies are satisfied, False otherwise
  559. """
  560. section = self._sections.get(section_key)
  561. if not section:
  562. return False
  563. # No dependencies = always satisfied
  564. if not section.needs:
  565. return True
  566. # Check each dependency
  567. for dep_key in section.needs:
  568. dep_section = self._sections.get(dep_key)
  569. if not dep_section:
  570. logger.warning(f"Section '{section_key}' depends on missing section '{dep_key}'")
  571. return False
  572. # Check if dependency is enabled
  573. if not dep_section.is_enabled():
  574. logger.debug(f"Section '{section_key}' dependency '{dep_key}' is disabled")
  575. return False
  576. return True
  577. def sort_sections(self) -> None:
  578. """Sort sections with the following priority:
  579. 1. Dependencies come before dependents (topological sort)
  580. 2. Required sections first (in their original order)
  581. 3. Enabled sections with satisfied dependencies next (in their original order)
  582. 4. Disabled sections or sections with unsatisfied dependencies last (in their original order)
  583. This maintains the original ordering within each group while organizing
  584. sections logically for display and user interaction, and ensures that
  585. sections are prompted in the correct dependency order.
  586. """
  587. # First, perform topological sort to respect dependencies
  588. sorted_keys = self._topological_sort()
  589. # Then apply priority sorting within dependency groups
  590. section_items = [(key, self._sections[key]) for key in sorted_keys]
  591. # Define sort key: (priority, original_index)
  592. # Priority: 0 = required, 1 = enabled with satisfied dependencies, 2 = disabled or unsatisfied dependencies
  593. def get_sort_key(item_with_index):
  594. index, (key, section) = item_with_index
  595. if section.required:
  596. priority = 0
  597. elif section.is_enabled() and self.is_section_satisfied(key):
  598. priority = 1
  599. else:
  600. priority = 2
  601. return (priority, index)
  602. # Sort with original index to maintain order within each priority group
  603. # Note: This preserves the topological order from earlier
  604. sorted_items = sorted(
  605. enumerate(section_items),
  606. key=get_sort_key
  607. )
  608. # Rebuild _sections dict in new order
  609. self._sections = {key: section for _, (key, section) in sorted_items}
  610. def _topological_sort(self) -> List[str]:
  611. """Perform topological sort on sections based on dependencies.
  612. Uses Kahn's algorithm to ensure dependencies come before dependents.
  613. Preserves original order when no dependencies exist.
  614. Returns:
  615. List of section keys in topologically sorted order
  616. """
  617. # Calculate in-degree (number of dependencies) for each section
  618. in_degree = {key: len(section.needs) for key, section in self._sections.items()}
  619. # Find all sections with no dependencies
  620. queue = [key for key, degree in in_degree.items() if degree == 0]
  621. result = []
  622. # Process sections in order
  623. while queue:
  624. # Sort queue to preserve original order when possible
  625. queue.sort(key=lambda k: list(self._sections.keys()).index(k))
  626. current = queue.pop(0)
  627. result.append(current)
  628. # Find sections that depend on current
  629. for key, section in self._sections.items():
  630. if current in section.needs:
  631. in_degree[key] -= 1
  632. if in_degree[key] == 0:
  633. queue.append(key)
  634. # If not all sections processed, there's a cycle (shouldn't happen due to validation)
  635. if len(result) != len(self._sections):
  636. logger.warning("Topological sort incomplete - possible dependency cycle")
  637. return list(self._sections.keys())
  638. return result
  639. # -------------------------
  640. # SECTION: Public API Methods
  641. # -------------------------
  642. def get_sections(self) -> Dict[str, VariableSection]:
  643. """Get all sections in the collection."""
  644. return self._sections.copy()
  645. def get_section(self, key: str) -> Optional[VariableSection]:
  646. """Get a specific section by its key."""
  647. return self._sections.get(key)
  648. def has_sections(self) -> bool:
  649. """Check if the collection has any sections."""
  650. return bool(self._sections)
  651. def get_all_values(self) -> dict[str, Any]:
  652. """Get all variable values as a dictionary."""
  653. # NOTE: This method is optimized to use the _variable_map for direct O(1) access
  654. # to each variable, which is much faster than iterating through sections.
  655. all_values = {}
  656. for var_name, variable in self._variable_map.items():
  657. all_values[var_name] = variable.get_typed_value()
  658. return all_values
  659. def get_satisfied_values(self) -> dict[str, Any]:
  660. """Get variable values only from sections with satisfied dependencies.
  661. This respects both toggle states and section dependencies, ensuring that:
  662. - Variables from disabled sections (toggle=false) are excluded
  663. - Variables from sections with unsatisfied dependencies are excluded
  664. Returns:
  665. Dictionary of variable names to values for satisfied sections only
  666. """
  667. satisfied_values = {}
  668. for section_key, section in self._sections.items():
  669. # Skip sections with unsatisfied dependencies
  670. if not self.is_section_satisfied(section_key):
  671. logger.debug(f"Excluding variables from section '{section_key}' - dependencies not satisfied")
  672. continue
  673. # Skip disabled sections (toggle check)
  674. if not section.is_enabled():
  675. logger.debug(f"Excluding variables from section '{section_key}' - section is disabled")
  676. continue
  677. # Include all variables from this satisfied section
  678. for var_name, variable in section.variables.items():
  679. satisfied_values[var_name] = variable.get_typed_value()
  680. return satisfied_values
  681. def get_sensitive_variables(self) -> Dict[str, Any]:
  682. """Get only the sensitive variables with their values."""
  683. return {name: var.value for name, var in self._variable_map.items() if var.sensitive and var.value}
  684. # !SECTION
  685. # -------------------------
  686. # SECTION: Helper Methods
  687. # -------------------------
  688. # NOTE: These helper methods reduce code duplication across module.py and prompt.py
  689. # by centralizing common variable collection operations
  690. def apply_defaults(self, defaults: dict[str, Any], origin: str = "cli") -> list[str]:
  691. """Apply default values to variables, updating their origin.
  692. Args:
  693. defaults: Dictionary mapping variable names to their default values
  694. origin: Source of these defaults (e.g., 'config', 'cli')
  695. Returns:
  696. List of variable names that were successfully updated
  697. """
  698. # NOTE: This method uses the _variable_map for a significant performance gain,
  699. # as it allows direct O(1) lookup of variables instead of iterating
  700. # through all sections to find a match.
  701. successful = []
  702. errors = []
  703. for var_name, value in defaults.items():
  704. try:
  705. variable = self._variable_map.get(var_name)
  706. if not variable:
  707. logger.warning(f"Variable '{var_name}' not found in template")
  708. continue
  709. # Convert and set the new value
  710. converted_value = variable.convert(value)
  711. variable.value = converted_value
  712. # Set origin to the current source (not a chain)
  713. variable.origin = origin
  714. successful.append(var_name)
  715. except ValueError as e:
  716. error_msg = f"Invalid value for '{var_name}': {value} - {e}"
  717. errors.append(error_msg)
  718. logger.error(error_msg)
  719. if errors:
  720. logger.warning(f"Some defaults failed to apply: {'; '.join(errors)}")
  721. return successful
  722. def validate_all(self) -> None:
  723. """Validate all variables in the collection, skipping disabled and unsatisfied sections."""
  724. errors: list[str] = []
  725. for section_key, section in self._sections.items():
  726. # Skip sections with unsatisfied dependencies
  727. if not self.is_section_satisfied(section_key):
  728. logger.debug(f"Skipping validation for section '{section_key}' - dependencies not satisfied")
  729. continue
  730. # Check if the section is disabled by a toggle
  731. if section.toggle:
  732. toggle_var = section.variables.get(section.toggle)
  733. if toggle_var and not toggle_var.get_typed_value():
  734. logger.debug(f"Skipping validation for disabled section: '{section.key}'")
  735. continue # Skip this entire section
  736. # Validate each variable in the section
  737. for var_name, variable in section.variables.items():
  738. try:
  739. # Skip validation for autogenerated variables when empty/None
  740. if variable.autogenerated and (variable.value is None or variable.value == ""):
  741. logger.debug(f"Skipping validation for autogenerated variable: '{section.key}.{var_name}'")
  742. continue
  743. # If value is None, treat as missing
  744. if variable.value is None:
  745. errors.append(f"{section.key}.{var_name} (missing)")
  746. continue
  747. # Attempt to convert/validate typed value
  748. typed = variable.get_typed_value()
  749. # For non-boolean types, treat None or empty string as invalid
  750. if variable.type not in ("bool",) and (typed is None or typed == ""):
  751. errors.append(f"{section.key}.{var_name} (empty)")
  752. except ValueError as e:
  753. errors.append(f"{section.key}.{var_name} (invalid: {e})")
  754. if errors:
  755. error_msg = "Variable validation failed: " + ", ".join(errors)
  756. logger.error(error_msg)
  757. raise ValueError(error_msg)
  758. def merge(self, other_spec: Union[Dict[str, Any], 'VariableCollection'], origin: str = "override") -> 'VariableCollection':
  759. """Merge another spec or VariableCollection into this one with precedence tracking.
  760. OPTIMIZED: Works directly on objects without dict conversions for better performance.
  761. The other spec/collection has higher precedence and will override values in self.
  762. Creates a new VariableCollection with merged data.
  763. Args:
  764. other_spec: Either a spec dictionary or another VariableCollection to merge
  765. origin: Origin label for variables from other_spec (e.g., 'template', 'config')
  766. Returns:
  767. New VariableCollection with merged data
  768. Example:
  769. module_vars = VariableCollection(module_spec)
  770. template_vars = module_vars.merge(template_spec, origin='template')
  771. # Variables from template_spec override module_spec
  772. # Origins tracked: 'module' or 'module -> template'
  773. """
  774. # Convert dict to VariableCollection if needed (only once)
  775. if isinstance(other_spec, dict):
  776. other = VariableCollection(other_spec)
  777. else:
  778. other = other_spec
  779. # Create new collection without calling __init__ (optimization)
  780. merged = VariableCollection.__new__(VariableCollection)
  781. merged._sections = {}
  782. merged._variable_map = {}
  783. # First pass: clone sections from self
  784. for section_key, self_section in self._sections.items():
  785. if section_key in other._sections:
  786. # Section exists in both - will merge
  787. merged._sections[section_key] = self._merge_sections(
  788. self_section,
  789. other._sections[section_key],
  790. origin
  791. )
  792. else:
  793. # Section only in self - clone it
  794. merged._sections[section_key] = self_section.clone()
  795. # Second pass: add sections that only exist in other
  796. for section_key, other_section in other._sections.items():
  797. if section_key not in merged._sections:
  798. # New section from other - clone with origin update
  799. merged._sections[section_key] = other_section.clone(origin_update=origin)
  800. # Rebuild variable map for O(1) lookups
  801. for section in merged._sections.values():
  802. for var_name, variable in section.variables.items():
  803. merged._variable_map[var_name] = variable
  804. return merged
  805. def _infer_origin_from_context(self) -> str:
  806. """Infer origin from existing variables (fallback)."""
  807. for section in self._sections.values():
  808. for variable in section.variables.values():
  809. if variable.origin:
  810. return variable.origin
  811. return "template"
  812. def _merge_sections(self, self_section: VariableSection, other_section: VariableSection, origin: str) -> VariableSection:
  813. """Merge two sections, with other_section taking precedence.
  814. Args:
  815. self_section: Base section
  816. other_section: Section to merge in (takes precedence)
  817. origin: Origin label for merged variables
  818. Returns:
  819. New merged VariableSection
  820. """
  821. # Start with a clone of self_section
  822. merged_section = self_section.clone()
  823. # Update section metadata from other (other takes precedence)
  824. if other_section.title:
  825. merged_section.title = other_section.title
  826. if other_section.description:
  827. merged_section.description = other_section.description
  828. if other_section.toggle:
  829. merged_section.toggle = other_section.toggle
  830. # Required flag always updated
  831. merged_section.required = other_section.required
  832. # Needs/dependencies always updated
  833. if other_section.needs:
  834. merged_section.needs = other_section.needs.copy()
  835. # Merge variables
  836. for var_name, other_var in other_section.variables.items():
  837. if var_name in merged_section.variables:
  838. # Variable exists in both - merge with other taking precedence
  839. self_var = merged_section.variables[var_name]
  840. # Build update dict with ONLY explicitly provided fields from other
  841. update = {}
  842. if 'type' in other_var._explicit_fields and other_var.type:
  843. update['type'] = other_var.type
  844. if ('value' in other_var._explicit_fields or 'default' in other_var._explicit_fields) and other_var.value is not None:
  845. update['value'] = other_var.value
  846. if 'description' in other_var._explicit_fields and other_var.description:
  847. update['description'] = other_var.description
  848. if 'prompt' in other_var._explicit_fields and other_var.prompt:
  849. update['prompt'] = other_var.prompt
  850. if 'options' in other_var._explicit_fields and other_var.options:
  851. update['options'] = other_var.options
  852. if 'sensitive' in other_var._explicit_fields and other_var.sensitive:
  853. update['sensitive'] = other_var.sensitive
  854. if 'extra' in other_var._explicit_fields and other_var.extra:
  855. update['extra'] = other_var.extra
  856. # Update origin tracking (only keep the current source, not the chain)
  857. update['origin'] = origin
  858. # Clone with updates
  859. merged_section.variables[var_name] = self_var.clone(update=update)
  860. else:
  861. # New variable from other - clone with origin
  862. merged_section.variables[var_name] = other_var.clone(update={'origin': origin})
  863. return merged_section
  864. def filter_to_used(self, used_variables: Set[str], keep_sensitive: bool = True) -> 'VariableCollection':
  865. """Filter collection to only variables that are used (or sensitive).
  866. OPTIMIZED: Works directly on objects without dict conversions for better performance.
  867. Creates a new VariableCollection containing only the variables in used_variables.
  868. Sections with no remaining variables are removed.
  869. Args:
  870. used_variables: Set of variable names that are actually used
  871. keep_sensitive: If True, also keep sensitive variables even if not in used set
  872. Returns:
  873. New VariableCollection with filtered variables
  874. Example:
  875. all_vars = VariableCollection(spec)
  876. used_vars = all_vars.filter_to_used({'var1', 'var2', 'var3'})
  877. # Only var1, var2, var3 (and any sensitive vars) remain
  878. """
  879. # Create new collection without calling __init__ (optimization)
  880. filtered = VariableCollection.__new__(VariableCollection)
  881. filtered._sections = {}
  882. filtered._variable_map = {}
  883. # Filter each section
  884. for section_key, section in self._sections.items():
  885. # Create a new section with same metadata
  886. filtered_section = VariableSection({
  887. 'key': section.key,
  888. 'title': section.title,
  889. 'description': section.description,
  890. 'toggle': section.toggle,
  891. 'required': section.required,
  892. 'needs': section.needs.copy() if section.needs else None,
  893. })
  894. # Clone only the variables that should be included
  895. for var_name, variable in section.variables.items():
  896. # Include if used OR if sensitive (and keep_sensitive is True)
  897. should_include = (
  898. var_name in used_variables or
  899. (keep_sensitive and variable.sensitive)
  900. )
  901. if should_include:
  902. filtered_section.variables[var_name] = variable.clone()
  903. # Only add section if it has variables
  904. if filtered_section.variables:
  905. filtered._sections[section_key] = filtered_section
  906. # Add variables to map
  907. for var_name, variable in filtered_section.variables.items():
  908. filtered._variable_map[var_name] = variable
  909. return filtered
  910. def get_all_variable_names(self) -> Set[str]:
  911. """Get set of all variable names across all sections.
  912. Returns:
  913. Set of all variable names
  914. """
  915. return set(self._variable_map.keys())
  916. # !SECTION
  917. # !SECTION