collection.py 30 KB

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