module.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. from __future__ import annotations
  2. import logging
  3. import sys
  4. from abc import ABC
  5. from pathlib import Path
  6. from typing import Any, Optional, List, Dict, Tuple
  7. from rich.console import Console
  8. from rich.panel import Panel
  9. from rich.prompt import Confirm
  10. from typer import Argument, Context, Option, Typer, Exit
  11. from .display import DisplayManager
  12. from .exceptions import (
  13. TemplateRenderError,
  14. TemplateSyntaxError,
  15. TemplateValidationError
  16. )
  17. from .library import LibraryManager
  18. from .prompt import PromptHandler
  19. from .template import Template
  20. logger = logging.getLogger(__name__)
  21. console = Console()
  22. console_err = Console(stderr=True)
  23. def parse_var_inputs(var_options: List[str], extra_args: List[str]) -> Dict[str, Any]:
  24. """Parse variable inputs from --var options and extra args.
  25. Supports formats:
  26. --var KEY=VALUE
  27. --var KEY VALUE
  28. Args:
  29. var_options: List of variable options from CLI
  30. extra_args: Additional arguments that may contain values
  31. Returns:
  32. Dictionary of parsed variables
  33. """
  34. variables = {}
  35. # Parse --var KEY=VALUE format
  36. for var_option in var_options:
  37. if '=' in var_option:
  38. key, value = var_option.split('=', 1)
  39. variables[key] = value
  40. else:
  41. # --var KEY VALUE format - value should be in extra_args
  42. if extra_args:
  43. variables[var_option] = extra_args.pop(0)
  44. else:
  45. logger.warning(f"No value provided for variable '{var_option}'")
  46. return variables
  47. class Module(ABC):
  48. """Streamlined base module that auto-detects variables from templates."""
  49. def __init__(self) -> None:
  50. if not all([self.name, self.description]):
  51. raise ValueError(
  52. f"Module {self.__class__.__name__} must define name and description"
  53. )
  54. logger.info(f"Initializing module '{self.name}'")
  55. logger.debug(f"Module '{self.name}' configuration: description='{self.description}'")
  56. self.libraries = LibraryManager()
  57. self.display = DisplayManager()
  58. def list(
  59. self,
  60. raw: bool = Option(False, "--raw", help="Output raw list format instead of rich table")
  61. ) -> list[Template]:
  62. """List all templates."""
  63. logger.debug(f"Listing templates for module '{self.name}'")
  64. templates = []
  65. entries = self.libraries.find(self.name, sort_results=True)
  66. for entry in entries:
  67. # Unpack entry - now returns (path, library_name, needs_qualification)
  68. template_dir = entry[0]
  69. library_name = entry[1]
  70. needs_qualification = entry[2] if len(entry) > 2 else False
  71. try:
  72. # Get library object to determine type
  73. library = next((lib for lib in self.libraries.libraries if lib.name == library_name), None)
  74. library_type = library.library_type if library else "git"
  75. template = Template(template_dir, library_name=library_name, library_type=library_type)
  76. # If template ID needs qualification, set qualified ID
  77. if needs_qualification:
  78. template.set_qualified_id()
  79. templates.append(template)
  80. except Exception as exc:
  81. logger.error(f"Failed to load template from {template_dir}: {exc}")
  82. continue
  83. filtered_templates = templates
  84. if filtered_templates:
  85. if raw:
  86. # Output raw format (tab-separated values for easy filtering with awk/sed/cut)
  87. # Format: ID\tNAME\tTAGS\tVERSION\tLIBRARY
  88. for template in filtered_templates:
  89. name = template.metadata.name or "Unnamed Template"
  90. tags_list = template.metadata.tags or []
  91. tags = ",".join(tags_list) if tags_list else "-"
  92. version = str(template.metadata.version) if template.metadata.version else "-"
  93. library = template.metadata.library or "-"
  94. print(f"{template.id}\t{name}\t{tags}\t{version}\t{library}")
  95. else:
  96. # Output rich table format
  97. self.display.display_templates_table(
  98. filtered_templates,
  99. self.name,
  100. f"{self.name.capitalize()} templates"
  101. )
  102. else:
  103. logger.info(f"No templates found for module '{self.name}'")
  104. return filtered_templates
  105. def search(
  106. self,
  107. query: str = Argument(..., help="Search string to filter templates by ID")
  108. ) -> list[Template]:
  109. """Search for templates by ID containing the search string."""
  110. logger.debug(f"Searching templates for module '{self.name}' with query='{query}'")
  111. templates = []
  112. entries = self.libraries.find(self.name, sort_results=True)
  113. for entry in entries:
  114. # Unpack entry - now returns (path, library_name, needs_qualification)
  115. template_dir = entry[0]
  116. library_name = entry[1]
  117. needs_qualification = entry[2] if len(entry) > 2 else False
  118. try:
  119. # Get library object to determine type
  120. library = next((lib for lib in self.libraries.libraries if lib.name == library_name), None)
  121. library_type = library.library_type if library else "git"
  122. template = Template(template_dir, library_name=library_name, library_type=library_type)
  123. # If template ID needs qualification, set qualified ID
  124. if needs_qualification:
  125. template.set_qualified_id()
  126. templates.append(template)
  127. except Exception as exc:
  128. logger.error(f"Failed to load template from {template_dir}: {exc}")
  129. continue
  130. # Apply search filtering
  131. filtered_templates = [t for t in templates if query.lower() in t.id.lower()]
  132. if filtered_templates:
  133. logger.info(f"Found {len(filtered_templates)} templates matching '{query}' for module '{self.name}'")
  134. self.display.display_templates_table(
  135. filtered_templates,
  136. self.name,
  137. f"{self.name.capitalize()} templates matching '{query}'"
  138. )
  139. else:
  140. logger.info(f"No templates found matching '{query}' for module '{self.name}'")
  141. self.display.display_warning(f"No templates found matching '{query}'", context=f"module '{self.name}'")
  142. return filtered_templates
  143. def show(
  144. self,
  145. id: str,
  146. ) -> None:
  147. """Show template details."""
  148. logger.debug(f"Showing template '{id}' from module '{self.name}'")
  149. template = self._load_template_by_id(id)
  150. if not template:
  151. self.display.display_error(f"Template '{id}' not found", context=f"module '{self.name}'")
  152. return
  153. # Apply config defaults (same as in generate)
  154. # This ensures the display shows the actual defaults that will be used
  155. if template.variables:
  156. from .config import ConfigManager
  157. config = ConfigManager()
  158. config_defaults = config.get_defaults(self.name)
  159. if config_defaults:
  160. logger.debug(f"Loading config defaults for module '{self.name}'")
  161. # Apply config defaults (this respects the variable types and validation)
  162. successful = template.variables.apply_defaults(config_defaults, "config")
  163. if successful:
  164. logger.debug(f"Applied config defaults for: {', '.join(successful)}")
  165. # Re-sort sections after applying config (toggle values may have changed)
  166. template.variables.sort_sections()
  167. self._display_template_details(template, id)
  168. def _apply_variable_defaults(self, template: Template) -> None:
  169. """Apply config defaults and CLI overrides to template variables.
  170. Args:
  171. template: Template instance with variables to configure
  172. """
  173. if not template.variables:
  174. return
  175. from .config import ConfigManager
  176. config = ConfigManager()
  177. config_defaults = config.get_defaults(self.name)
  178. if config_defaults:
  179. logger.info(f"Loading config defaults for module '{self.name}'")
  180. successful = template.variables.apply_defaults(config_defaults, "config")
  181. if successful:
  182. logger.debug(f"Applied config defaults for: {', '.join(successful)}")
  183. def _apply_cli_overrides(self, template: Template, var: Optional[List[str]], ctx=None) -> None:
  184. """Apply CLI variable overrides to template.
  185. Args:
  186. template: Template instance to apply overrides to
  187. var: List of variable override strings from --var flags
  188. ctx: Context object containing extra args (optional, will get current context if None)
  189. """
  190. if not template.variables:
  191. return
  192. # Get context if not provided (compatible with all Typer versions)
  193. if ctx is None:
  194. import click
  195. try:
  196. ctx = click.get_current_context()
  197. except RuntimeError:
  198. ctx = None
  199. extra_args = list(ctx.args) if ctx and hasattr(ctx, "args") else []
  200. cli_overrides = parse_var_inputs(var or [], extra_args)
  201. if cli_overrides:
  202. logger.info(f"Received {len(cli_overrides)} variable overrides from CLI")
  203. successful_overrides = template.variables.apply_defaults(cli_overrides, "cli")
  204. if successful_overrides:
  205. logger.debug(f"Applied CLI overrides for: {', '.join(successful_overrides)}")
  206. def _collect_variable_values(self, template: Template, interactive: bool) -> Dict[str, Any]:
  207. """Collect variable values from user prompts and template defaults.
  208. Args:
  209. template: Template instance with variables
  210. interactive: Whether to prompt user for values interactively
  211. Returns:
  212. Dictionary of variable names to values
  213. """
  214. variable_values = {}
  215. # Collect values interactively if enabled
  216. if interactive and template.variables:
  217. prompt_handler = PromptHandler()
  218. collected_values = prompt_handler.collect_variables(template.variables)
  219. if collected_values:
  220. variable_values.update(collected_values)
  221. logger.info(f"Collected {len(collected_values)} variable values from user input")
  222. # Add satisfied variable values (respects dependencies and toggles)
  223. if template.variables:
  224. variable_values.update(template.variables.get_satisfied_values())
  225. return variable_values
  226. def _check_output_directory(self, output_dir: Path, rendered_files: Dict[str, str],
  227. interactive: bool) -> Optional[List[Path]]:
  228. """Check output directory for conflicts and get user confirmation if needed.
  229. Args:
  230. output_dir: Directory where files will be written
  231. rendered_files: Dictionary of file paths to rendered content
  232. interactive: Whether to prompt user for confirmation
  233. Returns:
  234. List of existing files that will be overwritten, or None to cancel
  235. """
  236. dir_exists = output_dir.exists()
  237. dir_not_empty = dir_exists and any(output_dir.iterdir())
  238. # Check which files already exist
  239. existing_files = []
  240. if dir_exists:
  241. for file_path in rendered_files.keys():
  242. full_path = output_dir / file_path
  243. if full_path.exists():
  244. existing_files.append(full_path)
  245. # Warn if directory is not empty
  246. if dir_not_empty:
  247. if interactive:
  248. details = []
  249. if existing_files:
  250. details.append(f"{len(existing_files)} file(s) will be overwritten.")
  251. if not self.display.display_warning_with_confirmation(
  252. f"Directory '{output_dir}' is not empty.",
  253. details if details else None,
  254. default=False
  255. ):
  256. self.display.display_info("Generation cancelled")
  257. return None
  258. else:
  259. # Non-interactive mode: show warning but continue
  260. logger.warning(f"Directory '{output_dir}' is not empty")
  261. if existing_files:
  262. logger.warning(f"{len(existing_files)} file(s) will be overwritten")
  263. return existing_files
  264. def _get_generation_confirmation(self, output_dir: Path, rendered_files: Dict[str, str],
  265. existing_files: Optional[List[Path]], dir_not_empty: bool,
  266. dry_run: bool, interactive: bool) -> bool:
  267. """Display file generation confirmation and get user approval.
  268. Args:
  269. output_dir: Output directory path
  270. rendered_files: Dictionary of file paths to content
  271. existing_files: List of existing files that will be overwritten
  272. dir_not_empty: Whether output directory already contains files
  273. dry_run: Whether this is a dry run
  274. interactive: Whether to prompt for confirmation
  275. Returns:
  276. True if user confirms generation, False to cancel
  277. """
  278. if not interactive:
  279. return True
  280. self.display.display_file_generation_confirmation(
  281. output_dir,
  282. rendered_files,
  283. existing_files if existing_files else None
  284. )
  285. # Final confirmation (only if we didn't already ask about overwriting)
  286. if not dir_not_empty and not dry_run:
  287. if not Confirm.ask("Generate these files?", default=True):
  288. self.display.display_info("Generation cancelled")
  289. return False
  290. return True
  291. def _execute_dry_run(self, id: str, output_dir: Path, rendered_files: Dict[str, str], show_files: bool) -> None:
  292. """Execute dry run mode with comprehensive simulation.
  293. Simulates all filesystem operations that would occur during actual generation,
  294. including directory creation, file writing, and permission checks.
  295. Args:
  296. id: Template ID
  297. output_dir: Directory where files would be written
  298. rendered_files: Dictionary of file paths to rendered content
  299. show_files: Whether to display file contents
  300. """
  301. import os
  302. console.print()
  303. console.print("[bold cyan]Dry Run Mode - Simulating File Generation[/bold cyan]")
  304. console.print()
  305. # Simulate directory creation
  306. self.display.display_heading("Directory Operations", icon_type="folder")
  307. # Check if output directory exists
  308. if output_dir.exists():
  309. self.display.display_success(f"Output directory exists: [cyan]{output_dir}[/cyan]")
  310. # Check if we have write permissions
  311. if os.access(output_dir, os.W_OK):
  312. self.display.display_success("Write permission verified")
  313. else:
  314. self.display.display_warning("Write permission may be denied")
  315. else:
  316. console.print(f" [dim]→[/dim] Would create output directory: [cyan]{output_dir}[/cyan]")
  317. # Check if parent directory exists and is writable
  318. parent = output_dir.parent
  319. if parent.exists() and os.access(parent, os.W_OK):
  320. self.display.display_success("Parent directory writable")
  321. else:
  322. self.display.display_warning("Parent directory may not be writable")
  323. # Collect unique subdirectories that would be created
  324. subdirs = set()
  325. for file_path in rendered_files.keys():
  326. parts = Path(file_path).parts
  327. for i in range(1, len(parts)):
  328. subdirs.add(Path(*parts[:i]))
  329. if subdirs:
  330. console.print(f" [dim]→[/dim] Would create {len(subdirs)} subdirectory(ies)")
  331. for subdir in sorted(subdirs):
  332. console.print(f" [dim]📁[/dim] {subdir}/")
  333. console.print()
  334. # Display file operations in a table
  335. self.display.display_heading("File Operations", icon_type="file")
  336. total_size = 0
  337. new_files = 0
  338. overwrite_files = 0
  339. file_operations = []
  340. for file_path, content in sorted(rendered_files.items()):
  341. full_path = output_dir / file_path
  342. file_size = len(content.encode('utf-8'))
  343. total_size += file_size
  344. # Determine status
  345. if full_path.exists():
  346. status = "Overwrite"
  347. overwrite_files += 1
  348. else:
  349. status = "Create"
  350. new_files += 1
  351. file_operations.append((file_path, file_size, status))
  352. self.display.display_file_operation_table(file_operations)
  353. console.print()
  354. # Summary statistics
  355. if total_size < 1024:
  356. size_str = f"{total_size}B"
  357. elif total_size < 1024 * 1024:
  358. size_str = f"{total_size / 1024:.1f}KB"
  359. else:
  360. size_str = f"{total_size / (1024 * 1024):.1f}MB"
  361. summary_items = {
  362. "Total files:": str(len(rendered_files)),
  363. "New files:": str(new_files),
  364. "Files to overwrite:": str(overwrite_files),
  365. "Total size:": size_str
  366. }
  367. self.display.display_summary_table("Summary", summary_items)
  368. console.print()
  369. # Show file contents if requested
  370. if show_files:
  371. console.print("[bold cyan]Generated File Contents:[/bold cyan]")
  372. console.print()
  373. for file_path, content in sorted(rendered_files.items()):
  374. console.print(f"[cyan]File:[/cyan] {file_path}")
  375. print(f"{'─'*80}")
  376. print(content)
  377. print() # Add blank line after content
  378. console.print()
  379. self.display.display_success("Dry run complete - no files were written")
  380. console.print(f"[dim]Files would have been generated in '{output_dir}'[/dim]")
  381. logger.info(f"Dry run completed for template '{id}' - {len(rendered_files)} files, {total_size} bytes")
  382. def _write_generated_files(self, output_dir: Path, rendered_files: Dict[str, str], quiet: bool = False) -> None:
  383. """Write rendered files to the output directory.
  384. Args:
  385. output_dir: Directory to write files to
  386. rendered_files: Dictionary of file paths to rendered content
  387. quiet: Suppress output messages
  388. """
  389. output_dir.mkdir(parents=True, exist_ok=True)
  390. for file_path, content in rendered_files.items():
  391. full_path = output_dir / file_path
  392. full_path.parent.mkdir(parents=True, exist_ok=True)
  393. with open(full_path, 'w', encoding='utf-8') as f:
  394. f.write(content)
  395. if not quiet:
  396. console.print(f"[green]Generated file: {file_path}[/green]") # Keep simple per-file output
  397. if not quiet:
  398. self.display.display_success(f"Template generated successfully in '{output_dir}'")
  399. logger.info(f"Template written to directory: {output_dir}")
  400. def generate(
  401. self,
  402. id: str = Argument(..., help="Template ID"),
  403. directory: Optional[str] = Argument(None, help="Output directory (defaults to template ID)"),
  404. interactive: bool = Option(True, "--interactive/--no-interactive", "-i/-n", help="Enable interactive prompting for variables"),
  405. var: Optional[list[str]] = Option(None, "--var", "-v", help="Variable override (repeatable). Supports: KEY=VALUE or KEY VALUE"),
  406. dry_run: bool = Option(False, "--dry-run", help="Preview template generation without writing files"),
  407. show_files: bool = Option(False, "--show-files", help="Display generated file contents in plain text (use with --dry-run)"),
  408. quiet: bool = Option(False, "--quiet", "-q", help="Suppress all non-error output"),
  409. ) -> None:
  410. """Generate from template.
  411. Variable precedence chain (lowest to highest):
  412. 1. Module spec (defined in cli/modules/*.py)
  413. 2. Template spec (from template.yaml)
  414. 3. Config defaults (from ~/.config/boilerplates/config.yaml)
  415. 4. CLI overrides (--var flags)
  416. Examples:
  417. # Generate to directory named after template
  418. cli compose generate traefik
  419. # Generate to custom directory
  420. cli compose generate traefik my-proxy
  421. # Generate with variables
  422. cli compose generate traefik --var traefik_enabled=false
  423. # Preview without writing files (dry run)
  424. cli compose generate traefik --dry-run
  425. # Preview and show generated file contents
  426. cli compose generate traefik --dry-run --show-files
  427. """
  428. logger.info(f"Starting generation for template '{id}' from module '{self.name}'")
  429. # Create a display manager with quiet mode if needed
  430. display = DisplayManager(quiet=quiet) if quiet else self.display
  431. template = self._load_template_by_id(id)
  432. # Apply defaults and overrides
  433. self._apply_variable_defaults(template)
  434. self._apply_cli_overrides(template, var)
  435. # Re-sort sections after all overrides (toggle values may have changed)
  436. if template.variables:
  437. template.variables.sort_sections()
  438. if not quiet:
  439. self._display_template_details(template, id)
  440. console.print()
  441. # Collect variable values
  442. variable_values = self._collect_variable_values(template, interactive)
  443. try:
  444. # Validate and render template
  445. if template.variables:
  446. template.variables.validate_all()
  447. # Check if we're in debug mode (logger level is DEBUG)
  448. debug_mode = logger.isEnabledFor(logging.DEBUG)
  449. rendered_files, variable_values = template.render(template.variables, debug=debug_mode)
  450. if not rendered_files:
  451. display.display_error("Template rendering returned no files", context="template generation")
  452. raise Exit(code=1)
  453. logger.info(f"Successfully rendered template '{id}'")
  454. # Determine output directory
  455. if directory:
  456. output_dir = Path(directory)
  457. # Check if path looks like an absolute path but is missing the leading slash
  458. # This handles cases like "Users/username/path" which should be "/Users/username/path"
  459. if not output_dir.is_absolute() and str(output_dir).startswith(("Users/", "home/", "usr/", "opt/", "var/", "tmp/")):
  460. output_dir = Path("/") / output_dir
  461. logger.debug(f"Normalized relative-looking absolute path to: {output_dir}")
  462. else:
  463. output_dir = Path(id)
  464. # Check for conflicts and get confirmation (skip in quiet mode)
  465. if not quiet:
  466. existing_files = self._check_output_directory(output_dir, rendered_files, interactive)
  467. if existing_files is None:
  468. return # User cancelled
  469. # Get final confirmation for generation
  470. dir_not_empty = output_dir.exists() and any(output_dir.iterdir())
  471. if not self._get_generation_confirmation(output_dir, rendered_files, existing_files,
  472. dir_not_empty, dry_run, interactive):
  473. return # User cancelled
  474. else:
  475. # In quiet mode, just check for existing files without prompts
  476. existing_files = []
  477. # Execute generation (dry run or actual)
  478. if dry_run:
  479. if not quiet:
  480. self._execute_dry_run(id, output_dir, rendered_files, show_files)
  481. else:
  482. self._write_generated_files(output_dir, rendered_files, quiet=quiet)
  483. # Display next steps (not in quiet mode)
  484. if template.metadata.next_steps and not quiet:
  485. display.display_next_steps(template.metadata.next_steps, variable_values)
  486. except TemplateRenderError as e:
  487. # Display enhanced error information for template rendering errors (always show errors)
  488. display.display_template_render_error(e, context=f"template '{id}'")
  489. raise Exit(code=1)
  490. except Exception as e:
  491. display.display_error(str(e), context=f"generating template '{id}'")
  492. raise Exit(code=1)
  493. def config_get(
  494. self,
  495. var_name: Optional[str] = Argument(None, help="Variable name to get (omit to show all defaults)"),
  496. ) -> None:
  497. """Get default value(s) for this module.
  498. Examples:
  499. # Get all defaults for module
  500. cli compose defaults get
  501. # Get specific variable default
  502. cli compose defaults get service_name
  503. """
  504. from .config import ConfigManager
  505. config = ConfigManager()
  506. if var_name:
  507. # Get specific variable default
  508. value = config.get_default_value(self.name, var_name)
  509. if value is not None:
  510. console.print(f"[green]{var_name}[/green] = [yellow]{value}[/yellow]")
  511. else:
  512. self.display.display_warning(f"No default set for variable '{var_name}'", context=f"module '{self.name}'")
  513. else:
  514. # Show all defaults (flat list)
  515. defaults = config.get_defaults(self.name)
  516. if defaults:
  517. console.print(f"[bold]Config defaults for module '{self.name}':[/bold]\n")
  518. for var_name, var_value in defaults.items():
  519. console.print(f" [green]{var_name}[/green] = [yellow]{var_value}[/yellow]")
  520. else:
  521. console.print(f"[yellow]No defaults configured for module '{self.name}'[/yellow]")
  522. def config_set(
  523. self,
  524. var_name: str = Argument(..., help="Variable name or var=value format"),
  525. value: Optional[str] = Argument(None, help="Default value (not needed if using var=value format)"),
  526. ) -> None:
  527. """Set a default value for a variable.
  528. This only sets the DEFAULT VALUE, not the variable spec.
  529. The variable must be defined in the module or template spec.
  530. Supports both formats:
  531. - var_name value
  532. - var_name=value
  533. Examples:
  534. # Set default value (format 1)
  535. cli compose defaults set service_name my-awesome-app
  536. # Set default value (format 2)
  537. cli compose defaults set service_name=my-awesome-app
  538. # Set author for all compose templates
  539. cli compose defaults set author "Christian Lempa"
  540. """
  541. from .config import ConfigManager
  542. config = ConfigManager()
  543. # Parse var_name and value - support both "var value" and "var=value" formats
  544. if '=' in var_name and value is None:
  545. # Format: var_name=value
  546. parts = var_name.split('=', 1)
  547. actual_var_name = parts[0]
  548. actual_value = parts[1]
  549. elif value is not None:
  550. # Format: var_name value
  551. actual_var_name = var_name
  552. actual_value = value
  553. else:
  554. self.display.display_error(f"Missing value for variable '{var_name}'", context="config set")
  555. console.print(f"[dim]Usage: defaults set VAR_NAME VALUE or defaults set VAR_NAME=VALUE[/dim]")
  556. raise Exit(code=1)
  557. # Set the default value
  558. config.set_default_value(self.name, actual_var_name, actual_value)
  559. self.display.display_success(f"Set default: [cyan]{actual_var_name}[/cyan] = [yellow]{actual_value}[/yellow]")
  560. console.print(f"\n[dim]This will be used as the default value when generating templates with this module.[/dim]")
  561. def config_remove(
  562. self,
  563. var_name: str = Argument(..., help="Variable name to remove"),
  564. ) -> None:
  565. """Remove a specific default variable value.
  566. Examples:
  567. # Remove a default value
  568. cli compose defaults rm service_name
  569. """
  570. from .config import ConfigManager
  571. config = ConfigManager()
  572. defaults = config.get_defaults(self.name)
  573. if not defaults:
  574. console.print(f"[yellow]No defaults configured for module '{self.name}'[/yellow]")
  575. return
  576. if var_name in defaults:
  577. del defaults[var_name]
  578. config.set_defaults(self.name, defaults)
  579. self.display.display_success(f"Removed default for '{var_name}'")
  580. else:
  581. self.display.display_error(f"No default found for variable '{var_name}'")
  582. def config_clear(
  583. self,
  584. var_name: Optional[str] = Argument(None, help="Variable name to clear (omit to clear all defaults)"),
  585. force: bool = Option(False, "--force", "-f", help="Skip confirmation prompt"),
  586. ) -> None:
  587. """Clear default value(s) for this module.
  588. Examples:
  589. # Clear specific variable default
  590. cli compose defaults clear service_name
  591. # Clear all defaults for module
  592. cli compose defaults clear --force
  593. """
  594. from .config import ConfigManager
  595. config = ConfigManager()
  596. defaults = config.get_defaults(self.name)
  597. if not defaults:
  598. console.print(f"[yellow]No defaults configured for module '{self.name}'[/yellow]")
  599. return
  600. if var_name:
  601. # Clear specific variable
  602. if var_name in defaults:
  603. del defaults[var_name]
  604. config.set_defaults(self.name, defaults)
  605. self.display.display_success(f"Cleared default for '{var_name}'")
  606. else:
  607. self.display.display_error(f"No default found for variable '{var_name}'")
  608. else:
  609. # Clear all defaults
  610. if not force:
  611. detail_lines = [f"This will clear ALL defaults for module '{self.name}':", ""]
  612. for var_name, var_value in defaults.items():
  613. detail_lines.append(f" [green]{var_name}[/green] = [yellow]{var_value}[/yellow]")
  614. self.display.display_warning("Warning: This will clear ALL defaults")
  615. console.print()
  616. for line in detail_lines:
  617. console.print(line)
  618. console.print()
  619. if not Confirm.ask(f"[bold red]Are you sure?[/bold red]", default=False):
  620. console.print("[green]Operation cancelled.[/green]")
  621. return
  622. config.clear_defaults(self.name)
  623. self.display.display_success(f"Cleared all defaults for module '{self.name}'")
  624. def config_list(self) -> None:
  625. """Display the defaults for this specific module in YAML format.
  626. Examples:
  627. # Show the defaults for the current module
  628. cli compose defaults list
  629. """
  630. from .config import ConfigManager
  631. import yaml
  632. config = ConfigManager()
  633. # Get only the defaults for this module
  634. defaults = config.get_defaults(self.name)
  635. if not defaults:
  636. console.print(f"[yellow]No configuration found for module '{self.name}'[/yellow]")
  637. console.print(f"\n[dim]Config file location: {config.get_config_path()}[/dim]")
  638. return
  639. # Create a minimal config structure with only this module's defaults
  640. module_config = {
  641. "defaults": {
  642. self.name: defaults
  643. }
  644. }
  645. # Convert config to YAML string
  646. yaml_output = yaml.dump(module_config, default_flow_style=False, sort_keys=False)
  647. console.print(f"[bold]Configuration for module:[/bold] [cyan]{self.name}[/cyan]")
  648. console.print(f"[dim]Config file: {config.get_config_path()}[/dim]\n")
  649. console.print(Panel(yaml_output, title=f"{self.name.capitalize()} Config", border_style="blue"))
  650. def validate(
  651. self,
  652. template_id: str = Argument(None, help="Template ID to validate (if omitted, validates all templates)"),
  653. path: Optional[str] = Option(None, "--path", "-p", help="Validate a template from a specific directory path"),
  654. verbose: bool = Option(False, "--verbose", "-v", help="Show detailed validation information"),
  655. semantic: bool = Option(True, "--semantic/--no-semantic", help="Enable semantic validation (Docker Compose schema, etc.)")
  656. ) -> None:
  657. """Validate templates for Jinja2 syntax, undefined variables, and semantic correctness.
  658. Validation includes:
  659. - Jinja2 syntax checking
  660. - Variable definition checking
  661. - Semantic validation (when --semantic is enabled):
  662. - Docker Compose file structure
  663. - YAML syntax
  664. - Configuration best practices
  665. Examples:
  666. # Validate all templates in this module
  667. cli compose validate
  668. # Validate a specific template
  669. cli compose validate gitlab
  670. # Validate a template from a specific path
  671. cli compose validate --path /path/to/template
  672. # Validate with verbose output
  673. cli compose validate --verbose
  674. # Skip semantic validation (only Jinja2)
  675. cli compose validate --no-semantic
  676. """
  677. from rich.table import Table
  678. from .validators import get_validator_registry
  679. # Validate from path takes precedence
  680. if path:
  681. try:
  682. template_path = Path(path).resolve()
  683. if not template_path.exists():
  684. self.display.display_error(f"Path does not exist: {path}")
  685. raise Exit(code=1)
  686. if not template_path.is_dir():
  687. self.display.display_error(f"Path is not a directory: {path}")
  688. raise Exit(code=1)
  689. console.print(f"[bold]Validating template from path:[/bold] [cyan]{template_path}[/cyan]\n")
  690. template = Template(template_path, library_name="local")
  691. template_id = template.id
  692. except Exception as e:
  693. self.display.display_error(f"Failed to load template from path '{path}': {e}")
  694. raise Exit(code=1)
  695. elif template_id:
  696. # Validate a specific template by ID
  697. try:
  698. template = self._load_template_by_id(template_id)
  699. console.print(f"[bold]Validating template:[/bold] [cyan]{template_id}[/cyan]\n")
  700. except Exception as e:
  701. self.display.display_error(f"Failed to load template '{template_id}': {e}")
  702. raise Exit(code=1)
  703. else:
  704. # Validate all templates - handled separately below
  705. template = None
  706. # Single template validation
  707. if template:
  708. try:
  709. # Trigger validation by accessing used_variables
  710. _ = template.used_variables
  711. # Trigger variable definition validation by accessing variables
  712. _ = template.variables
  713. self.display.display_success("Jinja2 validation passed")
  714. # Semantic validation
  715. if semantic:
  716. console.print(f"\n[bold cyan]Running semantic validation...[/bold cyan]")
  717. registry = get_validator_registry()
  718. has_semantic_errors = False
  719. # Render template with default values for validation
  720. debug_mode = logger.isEnabledFor(logging.DEBUG)
  721. rendered_files, _ = template.render(template.variables, debug=debug_mode)
  722. for file_path, content in rendered_files.items():
  723. result = registry.validate_file(content, file_path)
  724. if result.errors or result.warnings or (verbose and result.info):
  725. console.print(f"\n[cyan]File:[/cyan] {file_path}")
  726. result.display(f"{file_path}")
  727. if result.errors:
  728. has_semantic_errors = True
  729. if not has_semantic_errors:
  730. self.display.display_success("Semantic validation passed")
  731. else:
  732. self.display.display_error("Semantic validation found errors")
  733. raise Exit(code=1)
  734. if verbose:
  735. console.print(f"\n[dim]Template path: {template.template_dir}[/dim]")
  736. console.print(f"[dim]Found {len(template.used_variables)} variables[/dim]")
  737. if semantic:
  738. console.print(f"[dim]Generated {len(rendered_files)} files[/dim]")
  739. except TemplateRenderError as e:
  740. # Display enhanced error information for template rendering errors
  741. self.display.display_template_render_error(e, context=f"template '{template_id}'")
  742. raise Exit(code=1)
  743. except (TemplateSyntaxError, TemplateValidationError, ValueError) as e:
  744. self.display.display_error(f"Validation failed for '{template_id}':")
  745. console.print(f"\n{e}")
  746. raise Exit(code=1)
  747. except Exception as e:
  748. self.display.display_error(f"Unexpected error validating '{template_id}': {e}")
  749. raise Exit(code=1)
  750. return
  751. else:
  752. # Validate all templates
  753. console.print(f"[bold]Validating all {self.name} templates...[/bold]\n")
  754. entries = self.libraries.find(self.name, sort_results=True)
  755. total = len(entries)
  756. valid_count = 0
  757. invalid_count = 0
  758. errors = []
  759. for template_dir, library_name in entries:
  760. template_id = template_dir.name
  761. try:
  762. template = Template(template_dir, library_name=library_name)
  763. # Trigger validation
  764. _ = template.used_variables
  765. _ = template.variables
  766. valid_count += 1
  767. if verbose:
  768. self.display.display_success(template_id)
  769. except ValueError as e:
  770. invalid_count += 1
  771. errors.append((template_id, str(e)))
  772. if verbose:
  773. self.display.display_error(template_id)
  774. except Exception as e:
  775. invalid_count += 1
  776. errors.append((template_id, f"Load error: {e}"))
  777. if verbose:
  778. self.display.display_warning(template_id)
  779. # Summary
  780. summary_items = {
  781. "Total templates:": str(total),
  782. "[green]Valid:[/green]": str(valid_count),
  783. "[red]Invalid:[/red]": str(invalid_count)
  784. }
  785. self.display.display_summary_table("Validation Summary", summary_items)
  786. # Show errors if any
  787. if errors:
  788. console.print(f"\n[bold red]Validation Errors:[/bold red]")
  789. for template_id, error_msg in errors:
  790. console.print(f"\n[yellow]Template:[/yellow] [cyan]{template_id}[/cyan]")
  791. console.print(f"[dim]{error_msg}[/dim]")
  792. raise Exit(code=1)
  793. else:
  794. self.display.display_success("All templates are valid!")
  795. @classmethod
  796. def register_cli(cls, app: Typer) -> None:
  797. """Register module commands with the main app."""
  798. logger.debug(f"Registering CLI commands for module '{cls.name}'")
  799. module_instance = cls()
  800. module_app = Typer(help=cls.description)
  801. module_app.command("list")(module_instance.list)
  802. module_app.command("search")(module_instance.search)
  803. module_app.command("show")(module_instance.show)
  804. module_app.command("validate")(module_instance.validate)
  805. module_app.command(
  806. "generate",
  807. context_settings={"allow_extra_args": True, "ignore_unknown_options": True}
  808. )(module_instance.generate)
  809. # Add defaults commands (simplified - only manage default values)
  810. defaults_app = Typer(help="Manage default values for template variables")
  811. defaults_app.command("get", help="Get default value(s)")(module_instance.config_get)
  812. defaults_app.command("set", help="Set a default value")(module_instance.config_set)
  813. defaults_app.command("rm", help="Remove a specific default value")(module_instance.config_remove)
  814. defaults_app.command("clear", help="Clear default value(s)")(module_instance.config_clear)
  815. defaults_app.command("list", help="Display the config for this module in YAML format")(module_instance.config_list)
  816. module_app.add_typer(defaults_app, name="defaults")
  817. app.add_typer(module_app, name=cls.name, help=cls.description)
  818. logger.info(f"Module '{cls.name}' CLI commands registered")
  819. def _load_template_by_id(self, id: str) -> Template:
  820. """Load a template by its ID, supporting qualified IDs.
  821. Supports both formats:
  822. - Simple: "alloy" (uses priority system)
  823. - Qualified: "alloy.default" (loads from specific library)
  824. Args:
  825. id: Template ID (simple or qualified)
  826. Returns:
  827. Template instance
  828. Raises:
  829. FileNotFoundError: If template is not found
  830. """
  831. logger.debug(f"Loading template with ID '{id}' from module '{self.name}'")
  832. # find_by_id now handles both simple and qualified IDs
  833. result = self.libraries.find_by_id(self.name, id)
  834. if not result:
  835. raise FileNotFoundError(f"Template '{id}' not found in module '{self.name}'")
  836. template_dir, library_name = result
  837. # Get library type
  838. library = next((lib for lib in self.libraries.libraries if lib.name == library_name), None)
  839. library_type = library.library_type if library else "git"
  840. try:
  841. template = Template(template_dir, library_name=library_name, library_type=library_type)
  842. # If the original ID was qualified, preserve it
  843. if '.' in id:
  844. template.id = id
  845. return template
  846. except Exception as exc:
  847. logger.error(f"Failed to load template '{id}': {exc}")
  848. raise FileNotFoundError(f"Template '{id}' could not be loaded: {exc}") from exc
  849. def _display_template_details(self, template: Template, id: str) -> None:
  850. """Display template information panel and variables table."""
  851. self.display.display_template_details(template, id)