collection.py 44 KB

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