module.py 36 KB

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