variables.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. from __future__ import annotations
  2. from collections import OrderedDict
  3. from dataclasses import dataclass, field
  4. from typing import Any, Dict, List, Optional, Set, Union
  5. from urllib.parse import urlparse
  6. import logging
  7. import re
  8. logger = logging.getLogger(__name__)
  9. TRUE_VALUES = {"true", "1", "yes", "on"}
  10. FALSE_VALUES = {"false", "0", "no", "off"}
  11. HOSTNAME_REGEX = re.compile(r"^(?=.{1,253}$)(?!-)[A-Za-z0-9_-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9_-]{1,63}(?<!-))*$")
  12. EMAIL_REGEX = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
  13. class Variable:
  14. """Represents a single templating variable with lightweight validation."""
  15. def __init__(self, data: dict[str, Any]) -> None:
  16. """Initialize Variable from a dictionary containing variable specification.
  17. Args:
  18. data: Dictionary containing variable specification with required 'name' key
  19. and optional keys: description, type, options, prompt, value, default, section, origin
  20. Raises:
  21. ValueError: If data is not a dict, missing 'name' key, or has invalid default value
  22. """
  23. # Validate input
  24. if not isinstance(data, dict):
  25. raise ValueError("Variable data must be a dictionary")
  26. if "name" not in data:
  27. raise ValueError("Variable data must contain 'name' key")
  28. # Track which fields were explicitly provided in source data
  29. self._explicit_fields: Set[str] = set(data.keys())
  30. # Initialize fields
  31. self.name: str = data["name"]
  32. self.description: Optional[str] = data.get("description") or data.get("display", "")
  33. self.type: str = data.get("type", "str")
  34. self.options: Optional[List[Any]] = data.get("options", [])
  35. self.prompt: Optional[str] = data.get("prompt")
  36. self.value: Any = data.get("value") if data.get("value") is not None else data.get("default")
  37. self.section: Optional[str] = data.get("section")
  38. self.origin: Optional[str] = data.get("origin")
  39. self.sensitive: bool = data.get("sensitive", False)
  40. # Optional extra explanation used by interactive prompts
  41. self.extra: Optional[str] = data.get("extra")
  42. # Flag indicating this variable should be auto-generated when empty
  43. self.autogenerated: bool = data.get("autogenerated", False)
  44. # Original value before config override (used for display)
  45. self.original_value: Optional[Any] = data.get("original_value")
  46. # Validate and convert the default/initial value if present
  47. if self.value is not None:
  48. try:
  49. self.value = self.convert(self.value)
  50. except ValueError as exc:
  51. raise ValueError(f"Invalid default for variable '{self.name}': {exc}")
  52. def _validate_not_empty(self, value: Any, converted_value: Any) -> None:
  53. """Validate that a value is not empty for non-boolean types."""
  54. if self.type not in ["bool"] and (converted_value is None or converted_value == ""):
  55. raise ValueError("value cannot be empty")
  56. def _validate_enum_option(self, value: str) -> None:
  57. """Validate that a value is in the allowed enum options."""
  58. if self.options and value not in self.options:
  59. raise ValueError(f"value must be one of: {', '.join(self.options)}")
  60. def _validate_regex_pattern(self, value: str, pattern: re.Pattern, error_msg: str) -> None:
  61. """Validate that a value matches a regex pattern."""
  62. if not pattern.fullmatch(value):
  63. raise ValueError(error_msg)
  64. def _validate_url_structure(self, parsed_url) -> None:
  65. """Validate that a parsed URL has required components."""
  66. if not (parsed_url.scheme and parsed_url.netloc):
  67. raise ValueError("value must be a valid URL (include scheme and host)")
  68. def convert(self, value: Any) -> Any:
  69. """Validate and convert a raw value based on the variable type."""
  70. if value is None:
  71. return None
  72. # Treat empty strings as None to avoid storing "" for missing values.
  73. if isinstance(value, str) and value.strip() == "":
  74. return None
  75. # Type conversion mapping for cleaner code
  76. converters = {
  77. "bool": self._convert_bool,
  78. "int": self._convert_int,
  79. "float": self._convert_float,
  80. "enum": self._convert_enum,
  81. "hostname": self._convert_hostname,
  82. "url": self._convert_url,
  83. "email": self._convert_email,
  84. }
  85. converter = converters.get(self.type)
  86. if converter:
  87. return converter(value)
  88. # Default to string conversion
  89. return str(value)
  90. def _convert_bool(self, value: Any) -> bool:
  91. """Convert value to boolean."""
  92. if isinstance(value, bool):
  93. return value
  94. if isinstance(value, str):
  95. lowered = value.strip().lower()
  96. if lowered in TRUE_VALUES:
  97. return True
  98. if lowered in FALSE_VALUES:
  99. return False
  100. raise ValueError("value must be a boolean (true/false)")
  101. def _convert_int(self, value: Any) -> Optional[int]:
  102. """Convert value to integer."""
  103. if isinstance(value, int):
  104. return value
  105. if isinstance(value, str) and value.strip() == "":
  106. return None
  107. try:
  108. return int(value)
  109. except (TypeError, ValueError) as exc:
  110. raise ValueError("value must be an integer") from exc
  111. def _convert_float(self, value: Any) -> Optional[float]:
  112. """Convert value to float."""
  113. if isinstance(value, float):
  114. return value
  115. if isinstance(value, str) and value.strip() == "":
  116. return None
  117. try:
  118. return float(value)
  119. except (TypeError, ValueError) as exc:
  120. raise ValueError("value must be a float") from exc
  121. def _convert_enum(self, value: Any) -> Optional[str]:
  122. """Convert value to enum option."""
  123. if value == "":
  124. return None
  125. val = str(value)
  126. self._validate_enum_option(val)
  127. return val
  128. def _convert_hostname(self, value: Any) -> str:
  129. """Convert and validate hostname."""
  130. val = str(value).strip()
  131. if not val:
  132. return None
  133. if val.lower() != "localhost":
  134. self._validate_regex_pattern(val, HOSTNAME_REGEX, "value must be a valid hostname")
  135. return val
  136. def _convert_url(self, value: Any) -> str:
  137. """Convert and validate URL."""
  138. val = str(value).strip()
  139. if not val:
  140. return None
  141. parsed = urlparse(val)
  142. self._validate_url_structure(parsed)
  143. return val
  144. def _convert_email(self, value: Any) -> str:
  145. """Convert and validate email."""
  146. val = str(value).strip()
  147. if not val:
  148. return None
  149. self._validate_regex_pattern(val, EMAIL_REGEX, "value must be a valid email address")
  150. return val
  151. def get_typed_value(self) -> Any:
  152. """Return the stored value converted to the appropriate Python type."""
  153. return self.convert(self.value)
  154. def to_dict(self) -> Dict[str, Any]:
  155. """Serialize Variable to a dictionary for storage.
  156. Returns:
  157. Dictionary representation of the variable with only relevant fields.
  158. """
  159. var_dict = {}
  160. if self.type:
  161. var_dict["type"] = self.type
  162. if self.value is not None:
  163. var_dict["default"] = self.value
  164. if self.description:
  165. var_dict["description"] = self.description
  166. if self.prompt:
  167. var_dict["prompt"] = self.prompt
  168. if self.sensitive:
  169. var_dict["sensitive"] = self.sensitive
  170. if self.extra:
  171. var_dict["extra"] = self.extra
  172. if self.autogenerated:
  173. var_dict["autogenerated"] = self.autogenerated
  174. if self.options:
  175. var_dict["options"] = self.options
  176. if self.origin:
  177. var_dict["origin"] = self.origin
  178. return var_dict
  179. def get_display_value(self, mask_sensitive: bool = True, max_length: int = 30) -> str:
  180. """Get formatted display value with optional masking and truncation.
  181. Args:
  182. mask_sensitive: If True, mask sensitive values with asterisks
  183. max_length: Maximum length before truncation (0 = no limit)
  184. Returns:
  185. Formatted string representation of the value
  186. """
  187. if self.value is None:
  188. return ""
  189. # Mask sensitive values
  190. if self.sensitive and mask_sensitive:
  191. return "********"
  192. # Convert to string
  193. display = str(self.value)
  194. # Truncate if needed
  195. if max_length > 0 and len(display) > max_length:
  196. return display[:max_length - 3] + "..."
  197. return display
  198. def get_normalized_default(self) -> Any:
  199. """Get normalized default value suitable for prompts and display.
  200. Handles type conversion and provides sensible defaults for different types.
  201. Especially useful for enum, bool, and int types in interactive prompts.
  202. Returns:
  203. Normalized default value appropriate for the variable type
  204. """
  205. try:
  206. typed = self.get_typed_value()
  207. except Exception:
  208. typed = self.value
  209. # Enum: ensure default is valid option
  210. if self.type == "enum":
  211. if not self.options:
  212. return typed
  213. # If typed is invalid or missing, use first option
  214. if typed is None or str(typed) not in self.options:
  215. return self.options[0]
  216. return str(typed)
  217. # Boolean: return as bool type
  218. if self.type == "bool":
  219. if isinstance(typed, bool):
  220. return typed
  221. return None if typed is None else bool(typed)
  222. # Integer: return as int type
  223. if self.type == "int":
  224. try:
  225. return int(typed) if typed is not None and typed != "" else None
  226. except Exception:
  227. return None
  228. # Default: return string or None
  229. return None if typed is None else str(typed)
  230. def get_prompt_text(self) -> str:
  231. """Get formatted prompt text for interactive input.
  232. Returns:
  233. Prompt text with optional type hints and descriptions
  234. """
  235. prompt_text = self.prompt or self.description or self.name
  236. # Add type hint for semantic types if there's a default
  237. if self.value is not None and self.type in ["hostname", "email", "url"]:
  238. prompt_text += f" ({self.type})"
  239. return prompt_text
  240. def get_validation_hint(self) -> Optional[str]:
  241. """Get validation hint for prompts (e.g., enum options).
  242. Returns:
  243. Formatted hint string or None if no hint needed
  244. """
  245. hints = []
  246. # Add enum options
  247. if self.type == "enum" and self.options:
  248. hints.append(f"Options: {', '.join(self.options)}")
  249. # Add extra help text
  250. if self.extra:
  251. hints.append(self.extra)
  252. return " — ".join(hints) if hints else None
  253. def is_required(self) -> bool:
  254. """Check if this variable requires a value (cannot be empty/None).
  255. A variable is considered required if:
  256. - It doesn't have a default value (value is None)
  257. - It's not marked as autogenerated (which can be empty and generated later)
  258. - It's not a boolean type (booleans default to False if not set)
  259. Returns:
  260. True if the variable must have a non-empty value, False otherwise
  261. """
  262. # Autogenerated variables can be empty (will be generated later)
  263. if self.autogenerated:
  264. return False
  265. # Boolean variables always have a value (True or False)
  266. if self.type == "bool":
  267. return False
  268. # Variables with a default value are not required
  269. if self.value is not None:
  270. return False
  271. # No default value and not autogenerated = required
  272. return True
  273. def clone(self, update: Optional[Dict[str, Any]] = None) -> 'Variable':
  274. """Create a deep copy of the variable with optional field updates.
  275. This is more efficient than converting to dict and back when copying variables.
  276. Args:
  277. update: Optional dictionary of field updates to apply to the clone
  278. Returns:
  279. New Variable instance with copied data
  280. Example:
  281. var2 = var1.clone(update={'origin': 'template'})
  282. """
  283. data = {
  284. 'name': self.name,
  285. 'type': self.type,
  286. 'value': self.value,
  287. 'description': self.description,
  288. 'prompt': self.prompt,
  289. 'options': self.options.copy() if self.options else None,
  290. 'section': self.section,
  291. 'origin': self.origin,
  292. 'sensitive': self.sensitive,
  293. 'extra': self.extra,
  294. 'autogenerated': self.autogenerated,
  295. 'original_value': self.original_value,
  296. }
  297. # Apply updates if provided
  298. if update:
  299. data.update(update)
  300. # Create new variable
  301. cloned = Variable(data)
  302. # Preserve explicit fields from original, and add any update keys
  303. cloned._explicit_fields = self._explicit_fields.copy()
  304. if update:
  305. cloned._explicit_fields.update(update.keys())
  306. return cloned
  307. class VariableSection:
  308. """Groups variables together with shared metadata for presentation."""
  309. def __init__(self, data: dict[str, Any]) -> None:
  310. """Initialize VariableSection from a dictionary.
  311. Args:
  312. data: Dictionary containing section specification with required 'key' and 'title' keys
  313. """
  314. if not isinstance(data, dict):
  315. raise ValueError("VariableSection data must be a dictionary")
  316. if "key" not in data:
  317. raise ValueError("VariableSection data must contain 'key'")
  318. if "title" not in data:
  319. raise ValueError("VariableSection data must contain 'title'")
  320. self.key: str = data["key"]
  321. self.title: str = data["title"]
  322. self.variables: OrderedDict[str, Variable] = OrderedDict()
  323. self.description: Optional[str] = data.get("description")
  324. self.toggle: Optional[str] = data.get("toggle")
  325. # Default "general" section to required=True, all others to required=False
  326. self.required: bool = data.get("required", data["key"] == "general")
  327. # Section dependencies - can be string or list of strings
  328. needs_value = data.get("needs")
  329. if needs_value:
  330. if isinstance(needs_value, str):
  331. self.needs: List[str] = [needs_value]
  332. elif isinstance(needs_value, list):
  333. self.needs: List[str] = needs_value
  334. else:
  335. raise ValueError(f"Section '{self.key}' has invalid 'needs' value: must be string or list")
  336. else:
  337. self.needs: List[str] = []
  338. def variable_names(self) -> list[str]:
  339. return list(self.variables.keys())
  340. def to_dict(self) -> Dict[str, Any]:
  341. """Serialize VariableSection to a dictionary for storage.
  342. Returns:
  343. Dictionary representation of the section with all metadata and variables.
  344. """
  345. section_dict = {}
  346. if self.title:
  347. section_dict["title"] = self.title
  348. if self.description:
  349. section_dict["description"] = self.description
  350. if self.toggle:
  351. section_dict["toggle"] = self.toggle
  352. # Always store required flag
  353. section_dict["required"] = self.required
  354. # Store dependencies if any
  355. if self.needs:
  356. section_dict["needs"] = self.needs if len(self.needs) > 1 else self.needs[0]
  357. # Serialize all variables using their own to_dict method
  358. section_dict["vars"] = {}
  359. for var_name, variable in self.variables.items():
  360. section_dict["vars"][var_name] = variable.to_dict()
  361. return section_dict
  362. def is_enabled(self) -> bool:
  363. """Check if section is currently enabled based on toggle variable.
  364. Returns:
  365. True if section is enabled (no toggle or toggle is True), False otherwise
  366. """
  367. if not self.toggle:
  368. return True
  369. toggle_var = self.variables.get(self.toggle)
  370. if not toggle_var:
  371. return True
  372. try:
  373. return bool(toggle_var.get_typed_value())
  374. except Exception:
  375. return False
  376. def get_toggle_value(self) -> Optional[bool]:
  377. """Get the current value of the toggle variable.
  378. Returns:
  379. Boolean value of toggle variable, or None if no toggle exists
  380. """
  381. if not self.toggle:
  382. return None
  383. toggle_var = self.variables.get(self.toggle)
  384. if not toggle_var:
  385. return None
  386. try:
  387. return bool(toggle_var.get_typed_value())
  388. except Exception:
  389. return None
  390. def clone(self, origin_update: Optional[str] = None) -> 'VariableSection':
  391. """Create a deep copy of the section with all variables.
  392. This is more efficient than converting to dict and back when copying sections.
  393. Args:
  394. origin_update: Optional origin string to apply to all cloned variables
  395. Returns:
  396. New VariableSection instance with deep-copied variables
  397. Example:
  398. section2 = section1.clone(origin_update='template')
  399. """
  400. # Create new section with same metadata
  401. cloned = VariableSection({
  402. 'key': self.key,
  403. 'title': self.title,
  404. 'description': self.description,
  405. 'toggle': self.toggle,
  406. 'required': self.required,
  407. 'needs': self.needs.copy() if self.needs else None,
  408. })
  409. # Deep copy all variables
  410. for var_name, variable in self.variables.items():
  411. if origin_update:
  412. cloned.variables[var_name] = variable.clone(update={'origin': origin_update})
  413. else:
  414. cloned.variables[var_name] = variable.clone()
  415. return cloned
  416. class VariableCollection:
  417. """Manages variables grouped by sections and builds Jinja context."""
  418. def __init__(self, spec: dict[str, Any]) -> None:
  419. """Initialize VariableCollection from a specification dictionary.
  420. Args:
  421. spec: Dictionary containing the complete variable specification structure
  422. Expected format (as used in compose.py):
  423. {
  424. "section_key": {
  425. "title": "Section Title",
  426. "prompt": "Optional prompt text",
  427. "toggle": "optional_toggle_var_name",
  428. "description": "Optional description",
  429. "vars": {
  430. "var_name": {
  431. "description": "Variable description",
  432. "type": "str",
  433. "default": "default_value",
  434. ...
  435. }
  436. }
  437. }
  438. }
  439. """
  440. if not isinstance(spec, dict):
  441. raise ValueError("Spec must be a dictionary")
  442. self._sections: Dict[str, VariableSection] = {}
  443. # NOTE: The _variable_map provides a flat, O(1) lookup for any variable by its name,
  444. # avoiding the need to iterate through sections. It stores references to the same
  445. # Variable objects contained in the _set structure.
  446. self._variable_map: Dict[str, Variable] = {}
  447. self._initialize_sections(spec)
  448. # Validate dependencies after all sections are loaded
  449. self._validate_dependencies()
  450. def _initialize_sections(self, spec: dict[str, Any]) -> None:
  451. """Initialize sections from the spec."""
  452. for section_key, section_data in spec.items():
  453. if not isinstance(section_data, dict):
  454. continue
  455. section = self._create_section(section_key, section_data)
  456. # Guard against None from empty YAML sections (vars: with no content)
  457. vars_data = section_data.get("vars") or {}
  458. self._initialize_variables(section, vars_data)
  459. self._sections[section_key] = section
  460. def _create_section(self, key: str, data: dict[str, Any]) -> VariableSection:
  461. """Create a VariableSection from data."""
  462. section_init_data = {
  463. "key": key,
  464. "title": data.get("title", key.replace("_", " ").title()),
  465. "description": data.get("description"),
  466. "toggle": data.get("toggle"),
  467. "required": data.get("required", key == "general"),
  468. "needs": data.get("needs")
  469. }
  470. return VariableSection(section_init_data)
  471. def _initialize_variables(self, section: VariableSection, vars_data: dict[str, Any]) -> None:
  472. """Initialize variables for a section."""
  473. # Guard against None from empty YAML sections
  474. if vars_data is None:
  475. vars_data = {}
  476. for var_name, var_data in vars_data.items():
  477. var_init_data = {"name": var_name, **var_data}
  478. variable = Variable(var_init_data)
  479. section.variables[var_name] = variable
  480. # NOTE: Populate the direct lookup map for efficient access.
  481. self._variable_map[var_name] = variable
  482. # Validate toggle variable after all variables are added
  483. self._validate_section_toggle(section)
  484. # FIXME: Add more section-level validation here as needed:
  485. # - Validate that variable names don't conflict across sections (currently allowed but could be confusing)
  486. # - Validate that required sections have at least one non-toggle variable
  487. # - Validate that enum variables have non-empty options lists
  488. # - Validate that variable names follow naming conventions (e.g., lowercase_with_underscores)
  489. # - Validate that default values are compatible with their type definitions
  490. def _validate_section_toggle(self, section: VariableSection) -> None:
  491. """Validate that toggle variable is of type bool if it exists.
  492. If the toggle variable doesn't exist (e.g., filtered out), removes the toggle.
  493. Args:
  494. section: The section to validate
  495. Raises:
  496. ValueError: If toggle variable exists but is not boolean type
  497. """
  498. if not section.toggle:
  499. return
  500. toggle_var = section.variables.get(section.toggle)
  501. if not toggle_var:
  502. # Toggle variable doesn't exist (e.g., was filtered out) - remove toggle metadata
  503. section.toggle = None
  504. return
  505. if toggle_var.type != "bool":
  506. raise ValueError(
  507. f"Section '{section.key}' toggle variable '{section.toggle}' must be type 'bool', "
  508. f"but is type '{toggle_var.type}'"
  509. )
  510. def _validate_dependencies(self) -> None:
  511. """Validate section dependencies for cycles and missing references.
  512. Raises:
  513. ValueError: If circular dependencies or missing section references are found
  514. """
  515. # Check for missing dependencies
  516. for section_key, section in self._sections.items():
  517. for dep in section.needs:
  518. if dep not in self._sections:
  519. raise ValueError(
  520. f"Section '{section_key}' depends on '{dep}', but '{dep}' does not exist"
  521. )
  522. # Check for circular dependencies using depth-first search
  523. visited = set()
  524. rec_stack = set()
  525. def has_cycle(section_key: str) -> bool:
  526. visited.add(section_key)
  527. rec_stack.add(section_key)
  528. section = self._sections[section_key]
  529. for dep in section.needs:
  530. if dep not in visited:
  531. if has_cycle(dep):
  532. return True
  533. elif dep in rec_stack:
  534. raise ValueError(
  535. f"Circular dependency detected: '{section_key}' depends on '{dep}', "
  536. f"which creates a cycle"
  537. )
  538. rec_stack.remove(section_key)
  539. return False
  540. for section_key in self._sections:
  541. if section_key not in visited:
  542. has_cycle(section_key)
  543. def is_section_satisfied(self, section_key: str) -> bool:
  544. """Check if all dependencies for a section are satisfied.
  545. A dependency is satisfied if:
  546. 1. The dependency section exists
  547. 2. The dependency section is enabled (if it has a toggle)
  548. Args:
  549. section_key: The key of the section to check
  550. Returns:
  551. True if all dependencies are satisfied, False otherwise
  552. """
  553. section = self._sections.get(section_key)
  554. if not section:
  555. return False
  556. # No dependencies = always satisfied
  557. if not section.needs:
  558. return True
  559. # Check each dependency
  560. for dep_key in section.needs:
  561. dep_section = self._sections.get(dep_key)
  562. if not dep_section:
  563. logger.warning(f"Section '{section_key}' depends on missing section '{dep_key}'")
  564. return False
  565. # Check if dependency is enabled
  566. if not dep_section.is_enabled():
  567. logger.debug(f"Section '{section_key}' dependency '{dep_key}' is disabled")
  568. return False
  569. return True
  570. def sort_sections(self) -> None:
  571. """Sort sections with the following priority:
  572. 1. Dependencies come before dependents (topological sort)
  573. 2. Required sections first (in their original order)
  574. 3. Enabled sections with satisfied dependencies next (in their original order)
  575. 4. Disabled sections or sections with unsatisfied dependencies last (in their original order)
  576. This maintains the original ordering within each group while organizing
  577. sections logically for display and user interaction, and ensures that
  578. sections are prompted in the correct dependency order.
  579. """
  580. # First, perform topological sort to respect dependencies
  581. sorted_keys = self._topological_sort()
  582. # Then apply priority sorting within dependency groups
  583. section_items = [(key, self._sections[key]) for key in sorted_keys]
  584. # Define sort key: (priority, original_index)
  585. # Priority: 0 = required, 1 = enabled with satisfied dependencies, 2 = disabled or unsatisfied dependencies
  586. def get_sort_key(item_with_index):
  587. index, (key, section) = item_with_index
  588. if section.required:
  589. priority = 0
  590. elif section.is_enabled() and self.is_section_satisfied(key):
  591. priority = 1
  592. else:
  593. priority = 2
  594. return (priority, index)
  595. # Sort with original index to maintain order within each priority group
  596. # Note: This preserves the topological order from earlier
  597. sorted_items = sorted(
  598. enumerate(section_items),
  599. key=get_sort_key
  600. )
  601. # Rebuild _sections dict in new order
  602. self._sections = {key: section for _, (key, section) in sorted_items}
  603. def _topological_sort(self) -> List[str]:
  604. """Perform topological sort on sections based on dependencies.
  605. Uses Kahn's algorithm to ensure dependencies come before dependents.
  606. Preserves original order when no dependencies exist.
  607. Returns:
  608. List of section keys in topologically sorted order
  609. """
  610. # Calculate in-degree (number of dependencies) for each section
  611. in_degree = {key: len(section.needs) for key, section in self._sections.items()}
  612. # Find all sections with no dependencies
  613. queue = [key for key, degree in in_degree.items() if degree == 0]
  614. result = []
  615. # Process sections in order
  616. while queue:
  617. # Sort queue to preserve original order when possible
  618. queue.sort(key=lambda k: list(self._sections.keys()).index(k))
  619. current = queue.pop(0)
  620. result.append(current)
  621. # Find sections that depend on current
  622. for key, section in self._sections.items():
  623. if current in section.needs:
  624. in_degree[key] -= 1
  625. if in_degree[key] == 0:
  626. queue.append(key)
  627. # If not all sections processed, there's a cycle (shouldn't happen due to validation)
  628. if len(result) != len(self._sections):
  629. logger.warning("Topological sort incomplete - possible dependency cycle")
  630. return list(self._sections.keys())
  631. return result
  632. def get_sections(self) -> Dict[str, VariableSection]:
  633. """Get all sections in the collection."""
  634. return self._sections.copy()
  635. def get_section(self, key: str) -> Optional[VariableSection]:
  636. """Get a specific section by its key."""
  637. return self._sections.get(key)
  638. def has_sections(self) -> bool:
  639. """Check if the collection has any sections."""
  640. return bool(self._sections)
  641. def get_all_values(self) -> dict[str, Any]:
  642. """Get all variable values as a dictionary."""
  643. # NOTE: This method is optimized to use the _variable_map for direct O(1) access
  644. # to each variable, which is much faster than iterating through sections.
  645. all_values = {}
  646. for var_name, variable in self._variable_map.items():
  647. all_values[var_name] = variable.get_typed_value()
  648. return all_values
  649. def get_satisfied_values(self) -> dict[str, Any]:
  650. """Get variable values only from sections with satisfied dependencies.
  651. This respects both toggle states and section dependencies, ensuring that:
  652. - Variables from disabled sections (toggle=false) are excluded
  653. - Variables from sections with unsatisfied dependencies are excluded
  654. Returns:
  655. Dictionary of variable names to values for satisfied sections only
  656. """
  657. satisfied_values = {}
  658. for section_key, section in self._sections.items():
  659. # Skip sections with unsatisfied dependencies
  660. if not self.is_section_satisfied(section_key):
  661. logger.debug(f"Excluding variables from section '{section_key}' - dependencies not satisfied")
  662. continue
  663. # Skip disabled sections (toggle check)
  664. if not section.is_enabled():
  665. logger.debug(f"Excluding variables from section '{section_key}' - section is disabled")
  666. continue
  667. # Include all variables from this satisfied section
  668. for var_name, variable in section.variables.items():
  669. satisfied_values[var_name] = variable.get_typed_value()
  670. return satisfied_values
  671. def get_sensitive_variables(self) -> Dict[str, Any]:
  672. """Get only the sensitive variables with their values."""
  673. return {name: var.value for name, var in self._variable_map.items() if var.sensitive and var.value}
  674. def apply_defaults(self, defaults: dict[str, Any], origin: str = "cli") -> list[str]:
  675. """Apply default values to variables, updating their origin.
  676. Args:
  677. defaults: Dictionary mapping variable names to their default values
  678. origin: Source of these defaults (e.g., 'config', 'cli')
  679. Returns:
  680. List of variable names that were successfully updated
  681. """
  682. # NOTE: This method uses the _variable_map for a significant performance gain,
  683. # as it allows direct O(1) lookup of variables instead of iterating
  684. # through all sections to find a match.
  685. successful = []
  686. errors = []
  687. for var_name, value in defaults.items():
  688. try:
  689. variable = self._variable_map.get(var_name)
  690. if not variable:
  691. logger.warning(f"Variable '{var_name}' not found in template")
  692. continue
  693. # Store original value before overriding (for display purposes)
  694. # Only store if this is the first time config is being applied
  695. if origin == "config" and not hasattr(variable, '_original_stored'):
  696. variable.original_value = variable.value
  697. variable._original_stored = True
  698. # Convert and set the new value
  699. converted_value = variable.convert(value)
  700. variable.value = converted_value
  701. # Set origin to the current source (not a chain)
  702. variable.origin = origin
  703. successful.append(var_name)
  704. except ValueError as e:
  705. error_msg = f"Invalid value for '{var_name}': {value} - {e}"
  706. errors.append(error_msg)
  707. logger.error(error_msg)
  708. if errors:
  709. logger.warning(f"Some defaults failed to apply: {'; '.join(errors)}")
  710. return successful
  711. def validate_all(self) -> None:
  712. """Validate all variables in the collection, skipping disabled and unsatisfied sections."""
  713. errors: list[str] = []
  714. for section_key, section in self._sections.items():
  715. # Skip sections with unsatisfied dependencies
  716. if not self.is_section_satisfied(section_key):
  717. logger.debug(f"Skipping validation for section '{section_key}' - dependencies not satisfied")
  718. continue
  719. # Check if the section is disabled by a toggle
  720. if section.toggle:
  721. toggle_var = section.variables.get(section.toggle)
  722. if toggle_var and not toggle_var.get_typed_value():
  723. logger.debug(f"Skipping validation for disabled section: '{section.key}'")
  724. continue # Skip this entire section
  725. # Validate each variable in the section
  726. for var_name, variable in section.variables.items():
  727. try:
  728. # Skip validation for autogenerated variables when empty/None
  729. if variable.autogenerated and (variable.value is None or variable.value == ""):
  730. logger.debug(f"Skipping validation for autogenerated variable: '{section.key}.{var_name}'")
  731. continue
  732. # If value is None and the variable is required, report as missing
  733. if variable.value is None:
  734. if variable.is_required():
  735. errors.append(f"{section.key}.{var_name} (required - no default provided)")
  736. continue
  737. # Attempt to convert/validate typed value
  738. typed = variable.get_typed_value()
  739. # For non-boolean types, treat None or empty string as invalid
  740. if variable.type not in ("bool",) and (typed is None or typed == ""):
  741. if variable.is_required():
  742. errors.append(f"{section.key}.{var_name} (required - cannot be empty)")
  743. else:
  744. errors.append(f"{section.key}.{var_name} (empty)")
  745. except ValueError as e:
  746. errors.append(f"{section.key}.{var_name} (invalid format: {e})")
  747. if errors:
  748. error_msg = "Variable validation failed: " + ", ".join(errors)
  749. logger.error(error_msg)
  750. raise ValueError(error_msg)
  751. def merge(self, other_spec: Union[Dict[str, Any], 'VariableCollection'], origin: str = "override") -> 'VariableCollection':
  752. """Merge another spec or VariableCollection into this one with precedence tracking.
  753. OPTIMIZED: Works directly on objects without dict conversions for better performance.
  754. The other spec/collection has higher precedence and will override values in self.
  755. Creates a new VariableCollection with merged data.
  756. Args:
  757. other_spec: Either a spec dictionary or another VariableCollection to merge
  758. origin: Origin label for variables from other_spec (e.g., 'template', 'config')
  759. Returns:
  760. New VariableCollection with merged data
  761. Example:
  762. module_vars = VariableCollection(module_spec)
  763. template_vars = module_vars.merge(template_spec, origin='template')
  764. # Variables from template_spec override module_spec
  765. # Origins tracked: 'module' or 'module -> template'
  766. """
  767. # Convert dict to VariableCollection if needed (only once)
  768. if isinstance(other_spec, dict):
  769. other = VariableCollection(other_spec)
  770. else:
  771. other = other_spec
  772. # Create new collection without calling __init__ (optimization)
  773. merged = VariableCollection.__new__(VariableCollection)
  774. merged._sections = {}
  775. merged._variable_map = {}
  776. # First pass: clone sections from self
  777. for section_key, self_section in self._sections.items():
  778. if section_key in other._sections:
  779. # Section exists in both - will merge
  780. merged._sections[section_key] = self._merge_sections(
  781. self_section,
  782. other._sections[section_key],
  783. origin
  784. )
  785. else:
  786. # Section only in self - clone it
  787. merged._sections[section_key] = self_section.clone()
  788. # Second pass: add sections that only exist in other
  789. for section_key, other_section in other._sections.items():
  790. if section_key not in merged._sections:
  791. # New section from other - clone with origin update
  792. merged._sections[section_key] = other_section.clone(origin_update=origin)
  793. # Rebuild variable map for O(1) lookups
  794. for section in merged._sections.values():
  795. for var_name, variable in section.variables.items():
  796. merged._variable_map[var_name] = variable
  797. return merged
  798. def _infer_origin_from_context(self) -> str:
  799. """Infer origin from existing variables (fallback)."""
  800. for section in self._sections.values():
  801. for variable in section.variables.values():
  802. if variable.origin:
  803. return variable.origin
  804. return "template"
  805. def _merge_sections(self, self_section: VariableSection, other_section: VariableSection, origin: str) -> VariableSection:
  806. """Merge two sections, with other_section taking precedence.
  807. Args:
  808. self_section: Base section
  809. other_section: Section to merge in (takes precedence)
  810. origin: Origin label for merged variables
  811. Returns:
  812. New merged VariableSection
  813. """
  814. # Start with a clone of self_section
  815. merged_section = self_section.clone()
  816. # Update section metadata from other (other takes precedence)
  817. if other_section.title:
  818. merged_section.title = other_section.title
  819. if other_section.description:
  820. merged_section.description = other_section.description
  821. if other_section.toggle:
  822. merged_section.toggle = other_section.toggle
  823. # Required flag always updated
  824. merged_section.required = other_section.required
  825. # Needs/dependencies always updated
  826. if other_section.needs:
  827. merged_section.needs = other_section.needs.copy()
  828. # Merge variables
  829. for var_name, other_var in other_section.variables.items():
  830. if var_name in merged_section.variables:
  831. # Variable exists in both - merge with other taking precedence
  832. self_var = merged_section.variables[var_name]
  833. # Build update dict with ONLY explicitly provided fields from other
  834. update = {}
  835. if 'type' in other_var._explicit_fields and other_var.type:
  836. update['type'] = other_var.type
  837. if ('value' in other_var._explicit_fields or 'default' in other_var._explicit_fields) and other_var.value is not None:
  838. update['value'] = other_var.value
  839. if 'description' in other_var._explicit_fields and other_var.description:
  840. update['description'] = other_var.description
  841. if 'prompt' in other_var._explicit_fields and other_var.prompt:
  842. update['prompt'] = other_var.prompt
  843. if 'options' in other_var._explicit_fields and other_var.options:
  844. update['options'] = other_var.options
  845. if 'sensitive' in other_var._explicit_fields and other_var.sensitive:
  846. update['sensitive'] = other_var.sensitive
  847. if 'extra' in other_var._explicit_fields and other_var.extra:
  848. update['extra'] = other_var.extra
  849. # Update origin tracking (only keep the current source, not the chain)
  850. update['origin'] = origin
  851. # Clone with updates
  852. merged_section.variables[var_name] = self_var.clone(update=update)
  853. else:
  854. # New variable from other - clone with origin
  855. merged_section.variables[var_name] = other_var.clone(update={'origin': origin})
  856. return merged_section
  857. def filter_to_used(self, used_variables: Set[str], keep_sensitive: bool = True) -> 'VariableCollection':
  858. """Filter collection to only variables that are used (or sensitive).
  859. OPTIMIZED: Works directly on objects without dict conversions for better performance.
  860. Creates a new VariableCollection containing only the variables in used_variables.
  861. Sections with no remaining variables are removed.
  862. Args:
  863. used_variables: Set of variable names that are actually used
  864. keep_sensitive: If True, also keep sensitive variables even if not in used set
  865. Returns:
  866. New VariableCollection with filtered variables
  867. Example:
  868. all_vars = VariableCollection(spec)
  869. used_vars = all_vars.filter_to_used({'var1', 'var2', 'var3'})
  870. # Only var1, var2, var3 (and any sensitive vars) remain
  871. """
  872. # Create new collection without calling __init__ (optimization)
  873. filtered = VariableCollection.__new__(VariableCollection)
  874. filtered._sections = {}
  875. filtered._variable_map = {}
  876. # Filter each section
  877. for section_key, section in self._sections.items():
  878. # Create a new section with same metadata
  879. filtered_section = VariableSection({
  880. 'key': section.key,
  881. 'title': section.title,
  882. 'description': section.description,
  883. 'toggle': section.toggle,
  884. 'required': section.required,
  885. 'needs': section.needs.copy() if section.needs else None,
  886. })
  887. # Clone only the variables that should be included
  888. for var_name, variable in section.variables.items():
  889. # Include if used OR if sensitive (and keep_sensitive is True)
  890. should_include = (
  891. var_name in used_variables or
  892. (keep_sensitive and variable.sensitive)
  893. )
  894. if should_include:
  895. filtered_section.variables[var_name] = variable.clone()
  896. # Only add section if it has variables
  897. if filtered_section.variables:
  898. filtered._sections[section_key] = filtered_section
  899. # Add variables to map
  900. for var_name, variable in filtered_section.variables.items():
  901. filtered._variable_map[var_name] = variable
  902. return filtered
  903. def get_all_variable_names(self) -> Set[str]:
  904. """Get set of all variable names across all sections.
  905. Returns:
  906. Set of all variable names
  907. """
  908. return set(self._variable_map.keys())