collection.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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, "parent_section": section, **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. # NOTE: We only warn here, not raise an error, because the variable might be
  261. # added later during merge with module spec. The actual runtime check in
  262. # _is_need_satisfied() will handle missing variables gracefully.
  263. logger.debug(
  264. f"Variable '{var_name}' has need '{dep}', but variable '{dep_var}' "
  265. f"not found (might be added during merge)"
  266. )
  267. # Check for circular dependencies using depth-first search
  268. # Note: Only checks section-level dependencies in old format (section names)
  269. # Variable-level dependencies (variable=value) don't create cycles in the same way
  270. visited = set()
  271. rec_stack = set()
  272. def has_cycle(section_key: str) -> bool:
  273. visited.add(section_key)
  274. rec_stack.add(section_key)
  275. section = self._sections[section_key]
  276. for dep in section.needs:
  277. # Only check circular deps for old format (section references)
  278. dep_name, expected_value = self._parse_need(dep)
  279. if expected_value is None and dep_name in self._sections:
  280. # Old format section dependency - check for cycles
  281. if dep_name not in visited:
  282. if has_cycle(dep_name):
  283. return True
  284. elif dep_name in rec_stack:
  285. raise ValueError(
  286. f"Circular dependency detected: '{section_key}' depends on '{dep_name}', "
  287. f"which creates a cycle"
  288. )
  289. rec_stack.remove(section_key)
  290. return False
  291. for section_key in self._sections:
  292. if section_key not in visited:
  293. has_cycle(section_key)
  294. def is_section_satisfied(self, section_key: str) -> bool:
  295. """Check if all dependencies for a section are satisfied.
  296. Supports both formats:
  297. - Old format: "section_name" - checks if section is enabled (backwards compatible)
  298. - New format: "variable=value" - checks if variable has specific value
  299. Args:
  300. section_key: The key of the section to check
  301. Returns:
  302. True if all dependencies are satisfied, False otherwise
  303. """
  304. section = self._sections.get(section_key)
  305. if not section:
  306. return False
  307. # No dependencies = always satisfied
  308. if not section.needs:
  309. return True
  310. # Check each dependency using the unified need satisfaction logic
  311. for need in section.needs:
  312. if not self._is_need_satisfied(need):
  313. logger.debug(f"Section '{section_key}' need '{need}' is not satisfied")
  314. return False
  315. return True
  316. def is_variable_satisfied(self, var_name: str) -> bool:
  317. """Check if all dependencies for a variable are satisfied.
  318. A variable is satisfied if all its needs are met.
  319. Needs are specified as "variable_name=value".
  320. Args:
  321. var_name: The name of the variable to check
  322. Returns:
  323. True if all dependencies are satisfied, False otherwise
  324. """
  325. variable = self._variable_map.get(var_name)
  326. if not variable:
  327. return False
  328. # No dependencies = always satisfied
  329. if not variable.needs:
  330. return True
  331. # Check each dependency
  332. for need in variable.needs:
  333. if not self._is_need_satisfied(need):
  334. logger.debug(f"Variable '{var_name}' need '{need}' is not satisfied")
  335. return False
  336. return True
  337. def reset_disabled_bool_variables(self) -> list[str]:
  338. """Reset bool variables with unsatisfied dependencies to False.
  339. This ensures that disabled bool variables don't accidentally remain True
  340. and cause confusion in templates or configuration.
  341. Note: CLI-provided variables are NOT reset here - they are validated
  342. later in validate_all() to provide better error messages.
  343. Returns:
  344. List of variable names that were reset
  345. """
  346. reset_vars = []
  347. for section_key, section in self._sections.items():
  348. # Check if section dependencies are satisfied
  349. section_satisfied = self.is_section_satisfied(section_key)
  350. is_enabled = section.is_enabled()
  351. for var_name, variable in section.variables.items():
  352. # Only process bool variables
  353. if variable.type != "bool":
  354. continue
  355. # Check if variable's own dependencies are satisfied
  356. var_satisfied = self.is_variable_satisfied(var_name)
  357. # If section is disabled OR variable dependencies aren't met, reset to False
  358. if not section_satisfied or not is_enabled or not var_satisfied:
  359. # Only reset if current value is not already False
  360. if variable.value is not False:
  361. # Don't reset CLI-provided variables - they'll be validated later
  362. if variable.origin == "cli":
  363. continue
  364. # Store original value if not already stored (for display purposes)
  365. if not hasattr(variable, "_original_disabled"):
  366. variable._original_disabled = variable.value
  367. variable.value = False
  368. reset_vars.append(var_name)
  369. logger.debug(
  370. f"Reset disabled bool variable '{var_name}' to False "
  371. f"(section satisfied: {section_satisfied}, enabled: {is_enabled}, "
  372. f"var satisfied: {var_satisfied})"
  373. )
  374. return reset_vars
  375. def sort_sections(self) -> None:
  376. """Sort sections with the following priority:
  377. 1. Dependencies come before dependents (topological sort)
  378. 2. Required sections first (in their original order)
  379. 3. Enabled sections with satisfied dependencies next (in their original order)
  380. 4. Disabled sections or sections with unsatisfied dependencies last (in their original order)
  381. This maintains the original ordering within each group while organizing
  382. sections logically for display and user interaction, and ensures that
  383. sections are prompted in the correct dependency order.
  384. """
  385. # First, perform topological sort to respect dependencies
  386. sorted_keys = self._topological_sort()
  387. # Then apply priority sorting within dependency groups
  388. section_items = [(key, self._sections[key]) for key in sorted_keys]
  389. # Define sort key: (priority, original_index)
  390. # Priority: 0 = required, 1 = enabled with satisfied dependencies, 2 = disabled or unsatisfied dependencies
  391. def get_sort_key(item_with_index):
  392. index, (key, section) = item_with_index
  393. if section.required:
  394. priority = 0
  395. elif section.is_enabled() and self.is_section_satisfied(key):
  396. priority = 1
  397. else:
  398. priority = 2
  399. return (priority, index)
  400. # Sort with original index to maintain order within each priority group
  401. # Note: This preserves the topological order from earlier
  402. sorted_items = sorted(enumerate(section_items), key=get_sort_key)
  403. # Rebuild _sections dict in new order
  404. self._sections = {key: section for _, (key, section) in sorted_items}
  405. # NOTE: Sort variables within each section by their dependencies.
  406. # This is critical for correct behavior in both display and prompts:
  407. # 1. DISPLAY: Variables are shown in logical order (dependencies before dependents)
  408. # 2. PROMPTS: Users are asked for dependency values BEFORE dependent values
  409. # Example: network_mode (bridge/host/macvlan) is prompted before
  410. # network_macvlan_ipv4_address (which needs network_mode=macvlan)
  411. # 3. VALIDATION: Ensures config/CLI overrides can be checked in correct order
  412. # Without this sorting, users would be prompted for irrelevant variables or see
  413. # confusing variable order in the UI.
  414. for section in self._sections.values():
  415. section.sort_variables(self._is_need_satisfied)
  416. def _topological_sort(self) -> List[str]:
  417. """Perform topological sort on sections based on dependencies using Kahn's algorithm."""
  418. in_degree = {key: len(section.needs) for key, section in self._sections.items()}
  419. queue = [key for key, degree in in_degree.items() if degree == 0]
  420. queue.sort(
  421. key=lambda k: list(self._sections.keys()).index(k)
  422. ) # Preserve original order
  423. result = []
  424. while queue:
  425. current = queue.pop(0)
  426. result.append(current)
  427. # Update in-degree for dependent sections
  428. for key, section in self._sections.items():
  429. if current in section.needs:
  430. in_degree[key] -= 1
  431. if in_degree[key] == 0:
  432. queue.append(key)
  433. # Fallback to original order if cycle detected
  434. if len(result) != len(self._sections):
  435. logger.warning("Topological sort incomplete - using original order")
  436. return list(self._sections.keys())
  437. return result
  438. def get_sections(self) -> Dict[str, VariableSection]:
  439. """Get all sections in the collection."""
  440. return self._sections.copy()
  441. def get_section(self, key: str) -> Optional[VariableSection]:
  442. """Get a specific section by its key."""
  443. return self._sections.get(key)
  444. def has_sections(self) -> bool:
  445. """Check if the collection has any sections."""
  446. return bool(self._sections)
  447. def get_all_values(self) -> dict[str, Any]:
  448. """Get all variable values as a dictionary."""
  449. # NOTE: Uses _variable_map for O(1) access
  450. return {
  451. name: var.convert(var.value) for name, var in self._variable_map.items()
  452. }
  453. def get_satisfied_values(self) -> dict[str, Any]:
  454. """Get variable values only from sections with satisfied dependencies.
  455. This respects both toggle states and section dependencies, ensuring that:
  456. - Variables from disabled sections (toggle=false) are excluded EXCEPT required variables
  457. - Variables from sections with unsatisfied dependencies are excluded
  458. - Required variables are always included if their section dependencies are satisfied
  459. Returns:
  460. Dictionary of variable names to values for satisfied sections only
  461. """
  462. satisfied_values = {}
  463. for section_key, section in self._sections.items():
  464. # Skip sections with unsatisfied dependencies (even required variables need satisfied deps)
  465. if not self.is_section_satisfied(section_key):
  466. logger.debug(
  467. f"Excluding variables from section '{section_key}' - dependencies not satisfied"
  468. )
  469. continue
  470. # Check if section is enabled
  471. is_enabled = section.is_enabled()
  472. if is_enabled:
  473. # Include all variables from enabled section
  474. for var_name, variable in section.variables.items():
  475. satisfied_values[var_name] = variable.convert(variable.value)
  476. else:
  477. # Section is disabled - only include required variables
  478. logger.debug(
  479. f"Section '{section_key}' is disabled - including only required variables"
  480. )
  481. for var_name, variable in section.variables.items():
  482. if variable.required:
  483. logger.debug(
  484. f"Including required variable '{var_name}' from disabled section '{section_key}'"
  485. )
  486. satisfied_values[var_name] = variable.convert(variable.value)
  487. return satisfied_values
  488. def get_sensitive_variables(self) -> Dict[str, Any]:
  489. """Get only the sensitive variables with their values."""
  490. return {
  491. name: var.value
  492. for name, var in self._variable_map.items()
  493. if var.sensitive and var.value
  494. }
  495. def apply_defaults(
  496. self, defaults: dict[str, Any], origin: str = "cli"
  497. ) -> list[str]:
  498. """Apply default values to variables, updating their origin.
  499. Args:
  500. defaults: Dictionary mapping variable names to their default values
  501. origin: Source of these defaults (e.g., 'config', 'cli')
  502. Returns:
  503. List of variable names that were successfully updated
  504. """
  505. # NOTE: This method uses the _variable_map for a significant performance gain,
  506. # as it allows direct O(1) lookup of variables instead of iterating
  507. # through all sections to find a match.
  508. successful = []
  509. errors = []
  510. for var_name, value in defaults.items():
  511. try:
  512. variable = self._variable_map.get(var_name)
  513. if not variable:
  514. logger.warning(f"Variable '{var_name}' not found in template")
  515. continue
  516. # Check if this is a toggle variable for a required section
  517. # If trying to set it to false, warn and skip
  518. for section in self._sections.values():
  519. if (
  520. section.required
  521. and section.toggle
  522. and section.toggle == var_name
  523. ):
  524. # Convert value to bool to check if it's false
  525. try:
  526. bool_value = variable.convert(value)
  527. if not bool_value:
  528. logger.warning(
  529. f"Ignoring attempt to disable toggle '{var_name}' for required section '{section.key}' via {origin}"
  530. )
  531. continue
  532. except Exception:
  533. pass # If conversion fails, let normal validation handle it
  534. # Check if variable's needs are satisfied
  535. # If not, warn that the override will have no effect
  536. if not self.is_variable_satisfied(var_name):
  537. # Build a friendly message about which needs aren't satisfied
  538. unmet_needs = []
  539. for need in variable.needs:
  540. if not self._is_need_satisfied(need):
  541. unmet_needs.append(need)
  542. needs_str = ", ".join(unmet_needs) if unmet_needs else "unknown"
  543. logger.warning(
  544. f"Setting '{var_name}' via {origin} will have no effect - needs not satisfied: {needs_str}"
  545. )
  546. # Continue anyway to store the value (it might become relevant later)
  547. # Store original value before overriding (for display purposes)
  548. # Only store if this is the first time config is being applied
  549. if origin == "config" and not hasattr(variable, "_original_stored"):
  550. variable.original_value = variable.value
  551. variable._original_stored = True
  552. # Convert and set the new value
  553. converted_value = variable.convert(value)
  554. variable.value = converted_value
  555. # Set origin to the current source (not a chain)
  556. variable.origin = origin
  557. successful.append(var_name)
  558. except ValueError as e:
  559. error_msg = f"Invalid value for '{var_name}': {value} - {e}"
  560. errors.append(error_msg)
  561. logger.error(error_msg)
  562. if errors:
  563. logger.warning(f"Some defaults failed to apply: {'; '.join(errors)}")
  564. return successful
  565. def validate_all(self) -> None:
  566. """Validate all variables in the collection.
  567. Validates:
  568. - All variables in enabled sections with satisfied dependencies
  569. - Required variables even if their section is disabled (but dependencies must be satisfied)
  570. - CLI-provided bool variables with unsatisfied dependencies
  571. """
  572. errors: list[str] = []
  573. # First, check for CLI-provided bool variables with unsatisfied dependencies
  574. for section_key, section in self._sections.items():
  575. section_satisfied = self.is_section_satisfied(section_key)
  576. is_enabled = section.is_enabled()
  577. for var_name, variable in section.variables.items():
  578. # Check CLI-provided bool variables with unsatisfied dependencies
  579. if variable.type == "bool" and variable.origin == "cli" and variable.value is not False:
  580. var_satisfied = self.is_variable_satisfied(var_name)
  581. if not section_satisfied or not is_enabled or not var_satisfied:
  582. # Build error message with unmet needs (use set to avoid duplicates)
  583. unmet_needs = set()
  584. if not section_satisfied:
  585. for need in section.needs:
  586. if not self._is_need_satisfied(need):
  587. unmet_needs.add(need)
  588. if not var_satisfied:
  589. for need in variable.needs:
  590. if not self._is_need_satisfied(need):
  591. unmet_needs.add(need)
  592. needs_str = ", ".join(sorted(unmet_needs)) if unmet_needs else "dependencies not satisfied"
  593. errors.append(
  594. f"{section.key}.{var_name} (set via CLI to {variable.value} but requires: {needs_str})"
  595. )
  596. # Then validate all other variables
  597. for section_key, section in self._sections.items():
  598. # Skip sections with unsatisfied dependencies (even for required variables)
  599. if not self.is_section_satisfied(section_key):
  600. logger.debug(
  601. f"Skipping validation for section '{section_key}' - dependencies not satisfied"
  602. )
  603. continue
  604. # Check if section is enabled
  605. is_enabled = section.is_enabled()
  606. if not is_enabled:
  607. logger.debug(
  608. f"Section '{section_key}' is disabled - validating only required variables"
  609. )
  610. # Validate variables in the section
  611. for var_name, variable in section.variables.items():
  612. # Skip all variables (including required ones) in disabled sections
  613. # Required variables are only required when their section is actually enabled
  614. if not is_enabled:
  615. continue
  616. try:
  617. # Skip autogenerated variables when empty
  618. if variable.autogenerated and not variable.value:
  619. continue
  620. # Check required fields
  621. if variable.value is None:
  622. # Optional variables can be None/empty
  623. if hasattr(variable, "optional") and variable.optional:
  624. continue
  625. if variable.is_required():
  626. errors.append(
  627. f"{section.key}.{var_name} (required - no default provided)"
  628. )
  629. continue
  630. # Validate typed value
  631. typed = variable.convert(variable.value)
  632. if variable.type not in ("bool",) and not typed:
  633. msg = f"{section.key}.{var_name}"
  634. errors.append(
  635. f"{msg} (required - cannot be empty)"
  636. if variable.is_required()
  637. else f"{msg} (empty)"
  638. )
  639. except ValueError as e:
  640. errors.append(f"{section.key}.{var_name} (invalid format: {e})")
  641. if errors:
  642. error_msg = "Variable validation failed: " + ", ".join(errors)
  643. logger.error(error_msg)
  644. raise ValueError(error_msg)
  645. def merge(
  646. self,
  647. other_spec: Union[Dict[str, Any], "VariableCollection"],
  648. origin: str = "override",
  649. ) -> "VariableCollection":
  650. """Merge another spec or VariableCollection into this one with precedence tracking.
  651. OPTIMIZED: Works directly on objects without dict conversions for better performance.
  652. The other spec/collection has higher precedence and will override values in self.
  653. Creates a new VariableCollection with merged data.
  654. Args:
  655. other_spec: Either a spec dictionary or another VariableCollection to merge
  656. origin: Origin label for variables from other_spec (e.g., 'template', 'config')
  657. Returns:
  658. New VariableCollection with merged data
  659. Example:
  660. module_vars = VariableCollection(module_spec)
  661. template_vars = module_vars.merge(template_spec, origin='template')
  662. # Variables from template_spec override module_spec
  663. # Origins tracked: 'module' or 'module -> template'
  664. """
  665. # Convert dict to VariableCollection if needed (only once)
  666. if isinstance(other_spec, dict):
  667. other = VariableCollection(other_spec)
  668. else:
  669. other = other_spec
  670. # Create new collection without calling __init__ (optimization)
  671. merged = VariableCollection.__new__(VariableCollection)
  672. merged._sections = {}
  673. merged._variable_map = {}
  674. # First pass: clone sections from self
  675. for section_key, self_section in self._sections.items():
  676. if section_key in other._sections:
  677. # Section exists in both - will merge
  678. merged._sections[section_key] = self._merge_sections(
  679. self_section, other._sections[section_key], origin
  680. )
  681. else:
  682. # Section only in self - clone it
  683. merged._sections[section_key] = self_section.clone()
  684. # Second pass: add sections that only exist in other
  685. for section_key, other_section in other._sections.items():
  686. if section_key not in merged._sections:
  687. # New section from other - clone with origin update
  688. merged._sections[section_key] = other_section.clone(
  689. origin_update=origin
  690. )
  691. # Rebuild variable map for O(1) lookups
  692. for section in merged._sections.values():
  693. for var_name, variable in section.variables.items():
  694. merged._variable_map[var_name] = variable
  695. # Validate dependencies after merge is complete
  696. merged._validate_dependencies()
  697. return merged
  698. def _merge_sections(
  699. self, self_section: VariableSection, other_section: VariableSection, origin: str
  700. ) -> VariableSection:
  701. """Merge two sections, with other_section taking precedence."""
  702. merged_section = self_section.clone()
  703. # Update section metadata from other (other takes precedence)
  704. # Explicit null/empty values clear the property (reset mechanism)
  705. for attr in ("title", "description", "toggle"):
  706. if (
  707. hasattr(other_section, "_explicit_fields")
  708. and attr in other_section._explicit_fields
  709. ):
  710. # Set to the other value even if null/empty (enables explicit reset)
  711. setattr(merged_section, attr, getattr(other_section, attr))
  712. merged_section.required = other_section.required
  713. # Respect explicit clears for dependencies (explicit null/empty clears, missing field preserves)
  714. if (
  715. hasattr(other_section, "_explicit_fields")
  716. and "needs" in other_section._explicit_fields
  717. ):
  718. merged_section.needs = (
  719. other_section.needs.copy() if other_section.needs else []
  720. )
  721. # Merge variables
  722. for var_name, other_var in other_section.variables.items():
  723. if var_name in merged_section.variables:
  724. # Variable exists in both - merge with other taking precedence
  725. self_var = merged_section.variables[var_name]
  726. # Build update dict with ONLY explicitly provided fields from other
  727. update = {"origin": origin}
  728. field_map = {
  729. "type": other_var.type,
  730. "description": other_var.description,
  731. "prompt": other_var.prompt,
  732. "options": other_var.options,
  733. "sensitive": other_var.sensitive,
  734. "extra": other_var.extra,
  735. }
  736. # Add fields that were explicitly provided, even if falsy/empty
  737. for field, value in field_map.items():
  738. if field in other_var._explicit_fields:
  739. update[field] = value
  740. # For boolean flags, only copy if explicitly provided in other
  741. # This prevents False defaults from overriding True values
  742. for bool_field in ("optional", "autogenerated", "required"):
  743. if bool_field in other_var._explicit_fields:
  744. update[bool_field] = getattr(other_var, bool_field)
  745. # Special handling for needs (allow explicit null/empty to clear)
  746. if "needs" in other_var._explicit_fields:
  747. update["needs"] = (
  748. other_var.needs.copy() if other_var.needs else []
  749. )
  750. # Special handling for value/default (allow explicit null to clear)
  751. if "value" in other_var._explicit_fields:
  752. update["value"] = other_var.value
  753. elif "default" in other_var._explicit_fields:
  754. update["value"] = other_var.value
  755. merged_section.variables[var_name] = self_var.clone(update=update)
  756. else:
  757. # New variable from other - clone with origin
  758. merged_section.variables[var_name] = other_var.clone(
  759. update={"origin": origin}
  760. )
  761. return merged_section
  762. def filter_to_used(
  763. self, used_variables: Set[str], keep_sensitive: bool = True
  764. ) -> "VariableCollection":
  765. """Filter collection to only variables that are used (or sensitive).
  766. OPTIMIZED: Works directly on objects without dict conversions for better performance.
  767. Creates a new VariableCollection containing only the variables in used_variables.
  768. Sections with no remaining variables are removed.
  769. Args:
  770. used_variables: Set of variable names that are actually used
  771. keep_sensitive: If True, also keep sensitive variables even if not in used set
  772. Returns:
  773. New VariableCollection with filtered variables
  774. Example:
  775. all_vars = VariableCollection(spec)
  776. used_vars = all_vars.filter_to_used({'var1', 'var2', 'var3'})
  777. # Only var1, var2, var3 (and any sensitive vars) remain
  778. """
  779. # Create new collection without calling __init__ (optimization)
  780. filtered = VariableCollection.__new__(VariableCollection)
  781. filtered._sections = {}
  782. filtered._variable_map = {}
  783. # Filter each section
  784. for section_key, section in self._sections.items():
  785. # Create a new section with same metadata
  786. filtered_section = VariableSection(
  787. {
  788. "key": section.key,
  789. "title": section.title,
  790. "description": section.description,
  791. "toggle": section.toggle,
  792. "required": section.required,
  793. "needs": section.needs.copy() if section.needs else None,
  794. }
  795. )
  796. # Clone only the variables that should be included
  797. for var_name, variable in section.variables.items():
  798. # Include if used OR if sensitive (and keep_sensitive is True)
  799. should_include = var_name in used_variables or (
  800. keep_sensitive and variable.sensitive
  801. )
  802. if should_include:
  803. filtered_section.variables[var_name] = variable.clone()
  804. # Only add section if it has variables
  805. if filtered_section.variables:
  806. filtered._sections[section_key] = filtered_section
  807. # Add variables to map
  808. for var_name, variable in filtered_section.variables.items():
  809. filtered._variable_map[var_name] = variable
  810. return filtered
  811. def get_all_variable_names(self) -> Set[str]:
  812. """Get set of all variable names across all sections.
  813. Returns:
  814. Set of all variable names
  815. """
  816. return set(self._variable_map.keys())