variables.py 39 KB

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