collection.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. from __future__ import annotations
  2. from collections import defaultdict
  3. from typing import Any, Dict, List, Optional, Set, Union
  4. import logging
  5. from .variable import Variable
  6. from .section import VariableSection
  7. logger = logging.getLogger(__name__)
  8. class VariableCollection:
  9. """Manages variables grouped by sections and builds Jinja context."""
  10. def __init__(self, spec: dict[str, Any]) -> None:
  11. """Initialize VariableCollection from a specification dictionary.
  12. Args:
  13. spec: Dictionary containing the complete variable specification structure
  14. Expected format (as used in compose.py):
  15. {
  16. "section_key": {
  17. "title": "Section Title",
  18. "prompt": "Optional prompt text",
  19. "toggle": "optional_toggle_var_name",
  20. "description": "Optional description",
  21. "vars": {
  22. "var_name": {
  23. "description": "Variable description",
  24. "type": "str",
  25. "default": "default_value",
  26. ...
  27. }
  28. }
  29. }
  30. }
  31. """
  32. if not isinstance(spec, dict):
  33. raise ValueError("Spec must be a dictionary")
  34. self._sections: Dict[str, VariableSection] = {}
  35. # NOTE: The _variable_map provides a flat, O(1) lookup for any variable by its name,
  36. # avoiding the need to iterate through sections. It stores references to the same
  37. # Variable objects contained in the _set structure.
  38. self._variable_map: Dict[str, Variable] = {}
  39. self._initialize_sections(spec)
  40. # Validate dependencies after all sections are loaded
  41. self._validate_dependencies()
  42. def _initialize_sections(self, spec: dict[str, Any]) -> None:
  43. """Initialize sections from the spec."""
  44. for section_key, section_data in spec.items():
  45. if not isinstance(section_data, dict):
  46. continue
  47. section = self._create_section(section_key, section_data)
  48. # Guard against None from empty YAML sections (vars: with no content)
  49. vars_data = section_data.get("vars") or {}
  50. self._initialize_variables(section, vars_data)
  51. self._sections[section_key] = section
  52. # Validate all variable names are unique across sections
  53. self._validate_unique_variable_names()
  54. def _create_section(self, key: str, data: dict[str, Any]) -> VariableSection:
  55. """Create a VariableSection from data."""
  56. # Build section init data with only explicitly provided fields
  57. # This prevents None values from overriding module spec values during merge
  58. section_init_data = {
  59. "key": key,
  60. "title": data.get("title", key.replace("_", " ").title()),
  61. }
  62. # Only add optional fields if explicitly provided in the source data
  63. if "description" in data:
  64. section_init_data["description"] = data["description"]
  65. if "toggle" in data:
  66. section_init_data["toggle"] = data["toggle"]
  67. if "required" in data:
  68. section_init_data["required"] = data["required"]
  69. elif key == "general":
  70. section_init_data["required"] = True
  71. if "needs" in data:
  72. section_init_data["needs"] = data["needs"]
  73. return VariableSection(section_init_data)
  74. def _initialize_variables(
  75. self, section: VariableSection, vars_data: dict[str, Any]
  76. ) -> None:
  77. """Initialize variables for a section."""
  78. # Guard against None from empty YAML sections
  79. if vars_data is None:
  80. vars_data = {}
  81. for var_name, var_data in vars_data.items():
  82. var_init_data = {"name": var_name, **var_data}
  83. variable = Variable(var_init_data)
  84. section.variables[var_name] = variable
  85. # NOTE: Populate the direct lookup map for efficient access.
  86. self._variable_map[var_name] = variable
  87. # Validate toggle variable after all variables are added
  88. self._validate_section_toggle(section)
  89. # TODO: Add more section-level validation:
  90. # - Validate that required sections have at least one non-toggle variable
  91. # - Validate that enum variables have non-empty options lists
  92. # - Validate that variable names follow naming conventions (e.g., lowercase_with_underscores)
  93. # - Validate that default values are compatible with their type definitions
  94. def _validate_unique_variable_names(self) -> None:
  95. """Validate that all variable names are unique across all sections."""
  96. var_to_sections: Dict[str, List[str]] = defaultdict(list)
  97. # Build mapping of variable names to sections
  98. for section_key, section in self._sections.items():
  99. for var_name in section.variables:
  100. var_to_sections[var_name].append(section_key)
  101. # Find duplicates and format error
  102. duplicates = {
  103. var: sections
  104. for var, sections in var_to_sections.items()
  105. if len(sections) > 1
  106. }
  107. if duplicates:
  108. errors = [
  109. "Variable names must be unique across all sections, but found duplicates:"
  110. ]
  111. errors.extend(
  112. f" - '{var}' appears in sections: {', '.join(secs)}"
  113. for var, secs in sorted(duplicates.items())
  114. )
  115. errors.append(
  116. "\nPlease rename variables to be unique or consolidate them into a single section."
  117. )
  118. error_msg = "\n".join(errors)
  119. logger.error(error_msg)
  120. raise ValueError(error_msg)
  121. def _validate_section_toggle(self, section: VariableSection) -> None:
  122. """Validate that toggle variable is of type bool if it exists.
  123. If the toggle variable doesn't exist (e.g., filtered out), removes the toggle.
  124. Args:
  125. section: The section to validate
  126. Raises:
  127. ValueError: If toggle variable exists but is not boolean type
  128. """
  129. if not section.toggle:
  130. return
  131. toggle_var = section.variables.get(section.toggle)
  132. if not toggle_var:
  133. # Toggle variable doesn't exist (e.g., was filtered out) - remove toggle metadata
  134. section.toggle = None
  135. return
  136. if toggle_var.type != "bool":
  137. raise ValueError(
  138. f"Section '{section.key}' toggle variable '{section.toggle}' must be type 'bool', "
  139. f"but is type '{toggle_var.type}'"
  140. )
  141. @staticmethod
  142. def _parse_need(need_str: str) -> tuple[str, Optional[Any]]:
  143. """Parse a need string into variable name and expected value(s).
  144. Supports three formats:
  145. 1. New format with multiple values: "variable_name=value1,value2" - checks if variable equals any value
  146. 2. New format with single value: "variable_name=value" - checks if variable equals value
  147. 3. Old format (backwards compatibility): "section_name" - checks if section is enabled
  148. Args:
  149. need_str: Need specification string
  150. Returns:
  151. Tuple of (variable_or_section_name, expected_value)
  152. For old format, expected_value is None (means check section enabled)
  153. For new format, expected_value is the string value(s) after '=' (string or list)
  154. Examples:
  155. "traefik_enabled=true" -> ("traefik_enabled", "true")
  156. "storage_mode=nfs" -> ("storage_mode", "nfs")
  157. "network_mode=bridge,macvlan" -> ("network_mode", ["bridge", "macvlan"])
  158. "traefik" -> ("traefik", None) # Old format: section name
  159. """
  160. if "=" in need_str:
  161. # New format: variable=value or variable=value1,value2
  162. parts = need_str.split("=", 1)
  163. var_name = parts[0].strip()
  164. value_part = parts[1].strip()
  165. # Check if multiple values are provided (comma-separated)
  166. if "," in value_part:
  167. values = [v.strip() for v in value_part.split(",")]
  168. return (var_name, values)
  169. else:
  170. return (var_name, value_part)
  171. else:
  172. # Old format: section name (backwards compatibility)
  173. return (need_str.strip(), None)
  174. def _is_need_satisfied(self, need_str: str) -> bool:
  175. """Check if a single need condition is satisfied.
  176. Args:
  177. need_str: Need specification ("variable=value", "variable=value1,value2" or "section_name")
  178. Returns:
  179. True if need is satisfied, False otherwise
  180. """
  181. var_or_section, expected_value = self._parse_need(need_str)
  182. if expected_value is None:
  183. # Old format: check if section is enabled (backwards compatibility)
  184. section = self._sections.get(var_or_section)
  185. if not section:
  186. logger.warning(f"Need references missing section '{var_or_section}'")
  187. return False
  188. return section.is_enabled()
  189. else:
  190. # New format: check if variable has expected value(s)
  191. variable = self._variable_map.get(var_or_section)
  192. if not variable:
  193. logger.warning(f"Need references missing variable '{var_or_section}'")
  194. return False
  195. # Convert actual value for comparison
  196. try:
  197. actual_value = variable.convert(variable.value)
  198. # Handle multiple expected values (comma-separated in needs)
  199. if isinstance(expected_value, list):
  200. # Check if actual value matches any of the expected values
  201. for expected in expected_value:
  202. expected_converted = variable.convert(expected)
  203. # Handle boolean comparisons specially
  204. if variable.type == "bool":
  205. if bool(actual_value) == bool(expected_converted):
  206. return True
  207. else:
  208. # String comparison for other types
  209. if actual_value is not None and str(actual_value) == str(
  210. expected_converted
  211. ):
  212. return True
  213. return False # None of the expected values matched
  214. else:
  215. # Single expected value (original behavior)
  216. expected_converted = variable.convert(expected_value)
  217. # Handle boolean comparisons specially
  218. if variable.type == "bool":
  219. return bool(actual_value) == bool(expected_converted)
  220. # String comparison for other types
  221. return (
  222. str(actual_value) == str(expected_converted)
  223. if actual_value is not None
  224. else False
  225. )
  226. except Exception as e:
  227. logger.debug(f"Failed to compare need '{need_str}': {e}")
  228. return False
  229. def _validate_dependencies(self) -> None:
  230. """Validate section dependencies for cycles and missing references.
  231. Raises:
  232. ValueError: If circular dependencies or missing section references are found
  233. """
  234. # Check for missing dependencies in sections
  235. for section_key, section in self._sections.items():
  236. for dep in section.needs:
  237. var_or_section, expected_value = self._parse_need(dep)
  238. if expected_value is None:
  239. # Old format: validate section exists
  240. if var_or_section not in self._sections:
  241. raise ValueError(
  242. f"Section '{section_key}' depends on '{var_or_section}', but '{var_or_section}' does not exist"
  243. )
  244. else:
  245. # New format: validate variable exists
  246. # NOTE: We only warn here, not raise an error, because the variable might be
  247. # added later during merge with module spec. The actual runtime check in
  248. # _is_need_satisfied() will handle missing variables gracefully.
  249. if var_or_section not in self._variable_map:
  250. logger.debug(
  251. f"Section '{section_key}' has need '{dep}', but variable '{var_or_section}' "
  252. f"not found (might be added during merge)"
  253. )
  254. # Check for missing dependencies in variables
  255. for var_name, variable in self._variable_map.items():
  256. for dep in variable.needs:
  257. dep_var, expected_value = self._parse_need(dep)
  258. if expected_value is not None: # Only validate new format
  259. if dep_var not in self._variable_map:
  260. raise ValueError(
  261. f"Variable '{var_name}' has need '{dep}', but variable '{dep_var}' does not exist"
  262. )
  263. # Check for circular dependencies using depth-first search
  264. # Note: Only checks section-level dependencies in old format (section names)
  265. # Variable-level dependencies (variable=value) don't create cycles in the same way
  266. visited = set()
  267. rec_stack = set()
  268. def has_cycle(section_key: str) -> bool:
  269. visited.add(section_key)
  270. rec_stack.add(section_key)
  271. section = self._sections[section_key]
  272. for dep in section.needs:
  273. # Only check circular deps for old format (section references)
  274. dep_name, expected_value = self._parse_need(dep)
  275. if expected_value is None and dep_name in self._sections:
  276. # Old format section dependency - check for cycles
  277. if dep_name not in visited:
  278. if has_cycle(dep_name):
  279. return True
  280. elif dep_name in rec_stack:
  281. raise ValueError(
  282. f"Circular dependency detected: '{section_key}' depends on '{dep_name}', "
  283. f"which creates a cycle"
  284. )
  285. rec_stack.remove(section_key)
  286. return False
  287. for section_key in self._sections:
  288. if section_key not in visited:
  289. has_cycle(section_key)
  290. def is_section_satisfied(self, section_key: str) -> bool:
  291. """Check if all dependencies for a section are satisfied.
  292. Supports both formats:
  293. - Old format: "section_name" - checks if section is enabled (backwards compatible)
  294. - New format: "variable=value" - checks if variable has specific value
  295. Args:
  296. section_key: The key of the section to check
  297. Returns:
  298. True if all dependencies are satisfied, False otherwise
  299. """
  300. section = self._sections.get(section_key)
  301. if not section:
  302. return False
  303. # No dependencies = always satisfied
  304. if not section.needs:
  305. return True
  306. # Check each dependency using the unified need satisfaction logic
  307. for need in section.needs:
  308. if not self._is_need_satisfied(need):
  309. logger.debug(f"Section '{section_key}' need '{need}' is not satisfied")
  310. return False
  311. return True
  312. def is_variable_satisfied(self, var_name: str) -> bool:
  313. """Check if all dependencies for a variable are satisfied.
  314. A variable is satisfied if all its needs are met.
  315. Needs are specified as "variable_name=value".
  316. Args:
  317. var_name: The name of the variable to check
  318. Returns:
  319. True if all dependencies are satisfied, False otherwise
  320. """
  321. variable = self._variable_map.get(var_name)
  322. if not variable:
  323. return False
  324. # No dependencies = always satisfied
  325. if not variable.needs:
  326. return True
  327. # Check each dependency
  328. for need in variable.needs:
  329. if not self._is_need_satisfied(need):
  330. logger.debug(f"Variable '{var_name}' need '{need}' is not satisfied")
  331. return False
  332. return True
  333. def sort_sections(self) -> None:
  334. """Sort sections with the following priority:
  335. 1. Dependencies come before dependents (topological sort)
  336. 2. Required sections first (in their original order)
  337. 3. Enabled sections with satisfied dependencies next (in their original order)
  338. 4. Disabled sections or sections with unsatisfied dependencies last (in their original order)
  339. This maintains the original ordering within each group while organizing
  340. sections logically for display and user interaction, and ensures that
  341. sections are prompted in the correct dependency order.
  342. """
  343. # First, perform topological sort to respect dependencies
  344. sorted_keys = self._topological_sort()
  345. # Then apply priority sorting within dependency groups
  346. section_items = [(key, self._sections[key]) for key in sorted_keys]
  347. # Define sort key: (priority, original_index)
  348. # Priority: 0 = required, 1 = enabled with satisfied dependencies, 2 = disabled or unsatisfied dependencies
  349. def get_sort_key(item_with_index):
  350. index, (key, section) = item_with_index
  351. if section.required:
  352. priority = 0
  353. elif section.is_enabled() and self.is_section_satisfied(key):
  354. priority = 1
  355. else:
  356. priority = 2
  357. return (priority, index)
  358. # Sort with original index to maintain order within each priority group
  359. # Note: This preserves the topological order from earlier
  360. sorted_items = sorted(enumerate(section_items), key=get_sort_key)
  361. # Rebuild _sections dict in new order
  362. self._sections = {key: section for _, (key, section) in sorted_items}
  363. # NOTE: Sort variables within each section by their dependencies.
  364. # This is critical for correct behavior in both display and prompts:
  365. # 1. DISPLAY: Variables are shown in logical order (dependencies before dependents)
  366. # 2. PROMPTS: Users are asked for dependency values BEFORE dependent values
  367. # Example: network_mode (bridge/host/macvlan) is prompted before
  368. # network_macvlan_ipv4_address (which needs network_mode=macvlan)
  369. # 3. VALIDATION: Ensures config/CLI overrides can be checked in correct order
  370. # Without this sorting, users would be prompted for irrelevant variables or see
  371. # confusing variable order in the UI.
  372. for section in self._sections.values():
  373. section.sort_variables(self._is_need_satisfied)
  374. def _topological_sort(self) -> List[str]:
  375. """Perform topological sort on sections based on dependencies using Kahn's algorithm."""
  376. in_degree = {key: len(section.needs) for key, section in self._sections.items()}
  377. queue = [key for key, degree in in_degree.items() if degree == 0]
  378. queue.sort(
  379. key=lambda k: list(self._sections.keys()).index(k)
  380. ) # Preserve original order
  381. result = []
  382. while queue:
  383. current = queue.pop(0)
  384. result.append(current)
  385. # Update in-degree for dependent sections
  386. for key, section in self._sections.items():
  387. if current in section.needs:
  388. in_degree[key] -= 1
  389. if in_degree[key] == 0:
  390. queue.append(key)
  391. # Fallback to original order if cycle detected
  392. if len(result) != len(self._sections):
  393. logger.warning("Topological sort incomplete - using original order")
  394. return list(self._sections.keys())
  395. return result
  396. def get_sections(self) -> Dict[str, VariableSection]:
  397. """Get all sections in the collection."""
  398. return self._sections.copy()
  399. def get_section(self, key: str) -> Optional[VariableSection]:
  400. """Get a specific section by its key."""
  401. return self._sections.get(key)
  402. def has_sections(self) -> bool:
  403. """Check if the collection has any sections."""
  404. return bool(self._sections)
  405. def get_all_values(self) -> dict[str, Any]:
  406. """Get all variable values as a dictionary."""
  407. # NOTE: Uses _variable_map for O(1) access
  408. return {
  409. name: var.convert(var.value) for name, var in self._variable_map.items()
  410. }
  411. def get_satisfied_values(self) -> dict[str, Any]:
  412. """Get variable values only from sections with satisfied dependencies.
  413. This respects both toggle states and section dependencies, ensuring that:
  414. - Variables from disabled sections (toggle=false) are excluded EXCEPT required variables
  415. - Variables from sections with unsatisfied dependencies are excluded
  416. - Required variables are always included if their section dependencies are satisfied
  417. Returns:
  418. Dictionary of variable names to values for satisfied sections only
  419. """
  420. satisfied_values = {}
  421. for section_key, section in self._sections.items():
  422. # Skip sections with unsatisfied dependencies (even required variables need satisfied deps)
  423. if not self.is_section_satisfied(section_key):
  424. logger.debug(
  425. f"Excluding variables from section '{section_key}' - dependencies not satisfied"
  426. )
  427. continue
  428. # Check if section is enabled
  429. is_enabled = section.is_enabled()
  430. if is_enabled:
  431. # Include all variables from enabled section
  432. for var_name, variable in section.variables.items():
  433. satisfied_values[var_name] = variable.convert(variable.value)
  434. else:
  435. # Section is disabled - only include required variables
  436. logger.debug(
  437. f"Section '{section_key}' is disabled - including only required variables"
  438. )
  439. for var_name, variable in section.variables.items():
  440. if variable.required:
  441. logger.debug(
  442. f"Including required variable '{var_name}' from disabled section '{section_key}'"
  443. )
  444. satisfied_values[var_name] = variable.convert(variable.value)
  445. return satisfied_values
  446. def get_sensitive_variables(self) -> Dict[str, Any]:
  447. """Get only the sensitive variables with their values."""
  448. return {
  449. name: var.value
  450. for name, var in self._variable_map.items()
  451. if var.sensitive and var.value
  452. }
  453. def apply_defaults(
  454. self, defaults: dict[str, Any], origin: str = "cli"
  455. ) -> list[str]:
  456. """Apply default values to variables, updating their origin.
  457. Args:
  458. defaults: Dictionary mapping variable names to their default values
  459. origin: Source of these defaults (e.g., 'config', 'cli')
  460. Returns:
  461. List of variable names that were successfully updated
  462. """
  463. # NOTE: This method uses the _variable_map for a significant performance gain,
  464. # as it allows direct O(1) lookup of variables instead of iterating
  465. # through all sections to find a match.
  466. successful = []
  467. errors = []
  468. for var_name, value in defaults.items():
  469. try:
  470. variable = self._variable_map.get(var_name)
  471. if not variable:
  472. logger.warning(f"Variable '{var_name}' not found in template")
  473. continue
  474. # Check if this is a toggle variable for a required section
  475. # If trying to set it to false, warn and skip
  476. for section in self._sections.values():
  477. if (
  478. section.required
  479. and section.toggle
  480. and section.toggle == var_name
  481. ):
  482. # Convert value to bool to check if it's false
  483. try:
  484. bool_value = variable.convert(value)
  485. if not bool_value:
  486. logger.warning(
  487. f"Ignoring attempt to disable toggle '{var_name}' for required section '{section.key}' via {origin}"
  488. )
  489. continue
  490. except Exception:
  491. pass # If conversion fails, let normal validation handle it
  492. # Check if variable's needs are satisfied
  493. # If not, warn that the override will have no effect
  494. if not self.is_variable_satisfied(var_name):
  495. # Build a friendly message about which needs aren't satisfied
  496. unmet_needs = []
  497. for need in variable.needs:
  498. if not self._is_need_satisfied(need):
  499. unmet_needs.append(need)
  500. needs_str = ", ".join(unmet_needs) if unmet_needs else "unknown"
  501. logger.warning(
  502. f"Setting '{var_name}' via {origin} will have no effect - needs not satisfied: {needs_str}"
  503. )
  504. # Continue anyway to store the value (it might become relevant later)
  505. # Store original value before overriding (for display purposes)
  506. # Only store if this is the first time config is being applied
  507. if origin == "config" and not hasattr(variable, "_original_stored"):
  508. variable.original_value = variable.value
  509. variable._original_stored = True
  510. # Convert and set the new value
  511. converted_value = variable.convert(value)
  512. variable.value = converted_value
  513. # Set origin to the current source (not a chain)
  514. variable.origin = origin
  515. successful.append(var_name)
  516. except ValueError as e:
  517. error_msg = f"Invalid value for '{var_name}': {value} - {e}"
  518. errors.append(error_msg)
  519. logger.error(error_msg)
  520. if errors:
  521. logger.warning(f"Some defaults failed to apply: {'; '.join(errors)}")
  522. return successful
  523. def validate_all(self) -> None:
  524. """Validate all variables in the collection.
  525. Validates:
  526. - All variables in enabled sections with satisfied dependencies
  527. - Required variables even if their section is disabled (but dependencies must be satisfied)
  528. """
  529. errors: list[str] = []
  530. for section_key, section in self._sections.items():
  531. # Skip sections with unsatisfied dependencies (even for required variables)
  532. if not self.is_section_satisfied(section_key):
  533. logger.debug(
  534. f"Skipping validation for section '{section_key}' - dependencies not satisfied"
  535. )
  536. continue
  537. # Check if section is enabled
  538. is_enabled = section.is_enabled()
  539. if not is_enabled:
  540. logger.debug(
  541. f"Section '{section_key}' is disabled - validating only required variables"
  542. )
  543. # Validate variables in the section
  544. for var_name, variable in section.variables.items():
  545. # Skip non-required variables in disabled sections
  546. if not is_enabled and not variable.required:
  547. continue
  548. try:
  549. # Skip autogenerated variables when empty
  550. if variable.autogenerated and not variable.value:
  551. continue
  552. # Check required fields
  553. if variable.value is None:
  554. # Optional variables can be None/empty
  555. if hasattr(variable, "optional") and variable.optional:
  556. continue
  557. if variable.is_required():
  558. errors.append(
  559. f"{section.key}.{var_name} (required - no default provided)"
  560. )
  561. continue
  562. # Validate typed value
  563. typed = variable.convert(variable.value)
  564. if variable.type not in ("bool",) and not typed:
  565. msg = f"{section.key}.{var_name}"
  566. errors.append(
  567. f"{msg} (required - cannot be empty)"
  568. if variable.is_required()
  569. else f"{msg} (empty)"
  570. )
  571. except ValueError as e:
  572. errors.append(f"{section.key}.{var_name} (invalid format: {e})")
  573. if errors:
  574. error_msg = "Variable validation failed: " + ", ".join(errors)
  575. logger.error(error_msg)
  576. raise ValueError(error_msg)
  577. def merge(
  578. self,
  579. other_spec: Union[Dict[str, Any], "VariableCollection"],
  580. origin: str = "override",
  581. ) -> "VariableCollection":
  582. """Merge another spec or VariableCollection into this one with precedence tracking.
  583. OPTIMIZED: Works directly on objects without dict conversions for better performance.
  584. The other spec/collection has higher precedence and will override values in self.
  585. Creates a new VariableCollection with merged data.
  586. Args:
  587. other_spec: Either a spec dictionary or another VariableCollection to merge
  588. origin: Origin label for variables from other_spec (e.g., 'template', 'config')
  589. Returns:
  590. New VariableCollection with merged data
  591. Example:
  592. module_vars = VariableCollection(module_spec)
  593. template_vars = module_vars.merge(template_spec, origin='template')
  594. # Variables from template_spec override module_spec
  595. # Origins tracked: 'module' or 'module -> template'
  596. """
  597. # Convert dict to VariableCollection if needed (only once)
  598. if isinstance(other_spec, dict):
  599. other = VariableCollection(other_spec)
  600. else:
  601. other = other_spec
  602. # Create new collection without calling __init__ (optimization)
  603. merged = VariableCollection.__new__(VariableCollection)
  604. merged._sections = {}
  605. merged._variable_map = {}
  606. # First pass: clone sections from self
  607. for section_key, self_section in self._sections.items():
  608. if section_key in other._sections:
  609. # Section exists in both - will merge
  610. merged._sections[section_key] = self._merge_sections(
  611. self_section, other._sections[section_key], origin
  612. )
  613. else:
  614. # Section only in self - clone it
  615. merged._sections[section_key] = self_section.clone()
  616. # Second pass: add sections that only exist in other
  617. for section_key, other_section in other._sections.items():
  618. if section_key not in merged._sections:
  619. # New section from other - clone with origin update
  620. merged._sections[section_key] = other_section.clone(
  621. origin_update=origin
  622. )
  623. # Rebuild variable map for O(1) lookups
  624. for section in merged._sections.values():
  625. for var_name, variable in section.variables.items():
  626. merged._variable_map[var_name] = variable
  627. return merged
  628. def _merge_sections(
  629. self, self_section: VariableSection, other_section: VariableSection, origin: str
  630. ) -> VariableSection:
  631. """Merge two sections, with other_section taking precedence."""
  632. merged_section = self_section.clone()
  633. # Update section metadata from other (other takes precedence)
  634. # Only override if explicitly provided in other AND has a value
  635. for attr in ("title", "description", "toggle"):
  636. other_value = getattr(other_section, attr)
  637. if (
  638. hasattr(other_section, "_explicit_fields")
  639. and attr in other_section._explicit_fields
  640. and other_value
  641. ):
  642. setattr(merged_section, attr, other_value)
  643. merged_section.required = other_section.required
  644. # Respect explicit clears for dependencies (explicit null/empty clears, missing field preserves)
  645. if (
  646. hasattr(other_section, "_explicit_fields")
  647. and "needs" in other_section._explicit_fields
  648. ):
  649. merged_section.needs = (
  650. other_section.needs.copy() if other_section.needs else []
  651. )
  652. # Merge variables
  653. for var_name, other_var in other_section.variables.items():
  654. if var_name in merged_section.variables:
  655. # Variable exists in both - merge with other taking precedence
  656. self_var = merged_section.variables[var_name]
  657. # Build update dict with ONLY explicitly provided fields from other
  658. update = {"origin": origin}
  659. field_map = {
  660. "type": other_var.type,
  661. "description": other_var.description,
  662. "prompt": other_var.prompt,
  663. "options": other_var.options,
  664. "sensitive": other_var.sensitive,
  665. "extra": other_var.extra,
  666. }
  667. # Add fields that were explicitly provided, even if falsy/empty
  668. for field, value in field_map.items():
  669. if field in other_var._explicit_fields:
  670. update[field] = value
  671. # For boolean flags, only copy if explicitly provided in other
  672. # This prevents False defaults from overriding True values
  673. for bool_field in ("optional", "autogenerated", "required"):
  674. if bool_field in other_var._explicit_fields:
  675. update[bool_field] = getattr(other_var, bool_field)
  676. # Special handling for value/default (allow explicit null to clear)
  677. if "value" in other_var._explicit_fields:
  678. update["value"] = other_var.value
  679. elif "default" in other_var._explicit_fields:
  680. update["value"] = other_var.value
  681. merged_section.variables[var_name] = self_var.clone(update=update)
  682. else:
  683. # New variable from other - clone with origin
  684. merged_section.variables[var_name] = other_var.clone(
  685. update={"origin": origin}
  686. )
  687. return merged_section
  688. def filter_to_used(
  689. self, used_variables: Set[str], keep_sensitive: bool = True
  690. ) -> "VariableCollection":
  691. """Filter collection to only variables that are used (or sensitive).
  692. OPTIMIZED: Works directly on objects without dict conversions for better performance.
  693. Creates a new VariableCollection containing only the variables in used_variables.
  694. Sections with no remaining variables are removed.
  695. Args:
  696. used_variables: Set of variable names that are actually used
  697. keep_sensitive: If True, also keep sensitive variables even if not in used set
  698. Returns:
  699. New VariableCollection with filtered variables
  700. Example:
  701. all_vars = VariableCollection(spec)
  702. used_vars = all_vars.filter_to_used({'var1', 'var2', 'var3'})
  703. # Only var1, var2, var3 (and any sensitive vars) remain
  704. """
  705. # Create new collection without calling __init__ (optimization)
  706. filtered = VariableCollection.__new__(VariableCollection)
  707. filtered._sections = {}
  708. filtered._variable_map = {}
  709. # Filter each section
  710. for section_key, section in self._sections.items():
  711. # Create a new section with same metadata
  712. filtered_section = VariableSection(
  713. {
  714. "key": section.key,
  715. "title": section.title,
  716. "description": section.description,
  717. "toggle": section.toggle,
  718. "required": section.required,
  719. "needs": section.needs.copy() if section.needs else None,
  720. }
  721. )
  722. # Clone only the variables that should be included
  723. for var_name, variable in section.variables.items():
  724. # Include if used OR if sensitive (and keep_sensitive is True)
  725. should_include = var_name in used_variables or (
  726. keep_sensitive and variable.sensitive
  727. )
  728. if should_include:
  729. filtered_section.variables[var_name] = variable.clone()
  730. # Only add section if it has variables
  731. if filtered_section.variables:
  732. filtered._sections[section_key] = filtered_section
  733. # Add variables to map
  734. for var_name, variable in filtered_section.variables.items():
  735. filtered._variable_map[var_name] = variable
  736. return filtered
  737. def get_all_variable_names(self) -> Set[str]:
  738. """Get set of all variable names across all sections.
  739. Returns:
  740. Set of all variable names
  741. """
  742. return set(self._variable_map.keys())