collection.py 34 KB

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