collection.py 28 KB

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