library.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. from __future__ import annotations
  2. import logging
  3. from pathlib import Path
  4. import yaml
  5. from .config import ConfigManager
  6. from .exceptions import DuplicateTemplateError, LibraryError, TemplateNotFoundError
  7. logger = logging.getLogger(__name__)
  8. # Qualified ID format: "template_id.library_name"
  9. QUALIFIED_ID_PARTS = 2
  10. class Library:
  11. """Represents a single library with a specific path."""
  12. def __init__(self, name: str, path: Path, priority: int = 0, library_type: str = "git") -> None:
  13. """Initialize a library instance.
  14. Args:
  15. name: Display name for the library
  16. path: Path to the library directory
  17. priority: Priority for library lookup (higher = checked first)
  18. library_type: Type of library ("git" or "static")
  19. """
  20. if library_type not in ("git", "static"):
  21. raise ValueError(f"Invalid library type: {library_type}. Must be 'git' or 'static'.")
  22. self.name = name
  23. self.path = path
  24. self.priority = priority # Higher priority = checked first
  25. self.library_type = library_type
  26. def _is_template_draft(self, template_path: Path) -> bool:
  27. """Check if a template is marked as draft."""
  28. # Find the template file
  29. for filename in ("template.yaml", "template.yml"):
  30. template_file = template_path / filename
  31. if template_file.exists():
  32. break
  33. else:
  34. return False
  35. try:
  36. with template_file.open(encoding="utf-8") as f:
  37. docs = [doc for doc in yaml.safe_load_all(f) if doc]
  38. return docs[0].get("metadata", {}).get("draft", False) if docs else False
  39. except (yaml.YAMLError, OSError) as e:
  40. logger.warning(f"Error checking draft status for {template_path}: {e}")
  41. return False
  42. def find_by_id(self, module_name: str, template_id: str) -> tuple[Path, str]:
  43. """Find a template by its ID in this library for generation/show operations.
  44. Note: Draft templates are intentionally excluded from this method.
  45. They are visible in list/search commands (via find()) but cannot be
  46. used for generation as they are work-in-progress.
  47. Args:
  48. module_name: The module name (e.g., 'compose', 'terraform')
  49. template_id: The template ID to find
  50. Returns:
  51. Path to the template directory if found and not draft
  52. Raises:
  53. TemplateNotFoundError: If the template ID is not found in this library or is marked as draft
  54. """
  55. logger.debug(f"Looking for template '{template_id}' in module '{module_name}' in library '{self.name}'")
  56. # Build the path to the specific template directory
  57. template_path = self.path / module_name / template_id
  58. # Check if template directory exists with a template file
  59. has_template = template_path.is_dir() and any(
  60. (template_path / f).exists() for f in ("template.yaml", "template.yml")
  61. )
  62. # Draft templates are not available for generation/show operations
  63. if not has_template or self._is_template_draft(template_path):
  64. raise TemplateNotFoundError(template_id, module_name)
  65. logger.debug(f"Found template '{template_id}' at: {template_path}")
  66. return template_path, self.name
  67. def find(self, module_name: str, sort_results: bool = False) -> list[tuple[Path, str]]:
  68. """Find templates in this library for a specific module.
  69. Includes all templates (both published and draft).
  70. Args:
  71. module_name: The module name (e.g., 'compose', 'terraform')
  72. sort_results: Whether to return results sorted alphabetically
  73. Returns:
  74. List of Path objects representing template directories (including drafts)
  75. Raises:
  76. FileNotFoundError: If the module directory is not found in this library
  77. """
  78. logger.debug(f"Looking for templates in module '{module_name}' in library '{self.name}'")
  79. # Build the path to the module directory
  80. module_path = self.path / module_name
  81. # Check if the module directory exists
  82. if not module_path.is_dir():
  83. raise LibraryError(f"Module '{module_name}' not found in library '{self.name}'")
  84. # Track seen IDs to detect duplicates within this library
  85. seen_ids = {}
  86. template_dirs = []
  87. try:
  88. for item in module_path.iterdir():
  89. has_template = item.is_dir() and any((item / f).exists() for f in ("template.yaml", "template.yml"))
  90. if has_template:
  91. template_id = item.name
  92. # Check for duplicate within same library
  93. if template_id in seen_ids:
  94. raise DuplicateTemplateError(template_id, self.name)
  95. seen_ids[template_id] = True
  96. template_dirs.append((item, self.name))
  97. except PermissionError as e:
  98. raise LibraryError(
  99. f"Permission denied accessing module '{module_name}' in library '{self.name}': {e}"
  100. ) from e
  101. # Sort if requested
  102. if sort_results:
  103. template_dirs.sort(key=lambda x: x[0].name.lower())
  104. logger.debug(f"Found {len(template_dirs)} templates in module '{module_name}'")
  105. return template_dirs
  106. class LibraryManager:
  107. """Manages multiple libraries and provides methods to find templates."""
  108. def __init__(self) -> None:
  109. """Initialize LibraryManager with git-based libraries from config."""
  110. self.config = ConfigManager()
  111. self.libraries = self._load_libraries_from_config()
  112. def _resolve_git_library_path(self, name: str, lib_config: dict, libraries_path: Path) -> Path:
  113. """Resolve path for a git-based library."""
  114. directory = lib_config.get("directory", ".")
  115. library_base = libraries_path / name
  116. if directory and directory != ".":
  117. return library_base / directory
  118. return library_base
  119. def _resolve_static_library_path(self, name: str, lib_config: dict) -> Path | None:
  120. """Resolve path for a static library."""
  121. path_str = lib_config.get("path")
  122. if not path_str:
  123. logger.warning(f"Static library '{name}' has no path configured")
  124. return None
  125. library_path = Path(path_str).expanduser()
  126. if not library_path.is_absolute():
  127. library_path = (self.config.config_path.parent / library_path).resolve()
  128. return library_path
  129. def _warn_missing_library(self, name: str, library_path: Path, lib_type: str) -> None:
  130. """Log warning about missing library."""
  131. if lib_type == "git":
  132. logger.warning(
  133. f"Library '{name}' not found at {library_path}. Run 'boilerplates repo update' to sync libraries."
  134. )
  135. else:
  136. logger.warning(f"Static library '{name}' not found at {library_path}")
  137. def _load_libraries_from_config(self) -> list[Library]:
  138. """Load libraries from configuration.
  139. Returns:
  140. List of Library instances
  141. """
  142. libraries = []
  143. libraries_path = self.config.get_libraries_path()
  144. library_configs = self.config.get_libraries()
  145. for i, lib_config in enumerate(library_configs):
  146. # Skip disabled libraries
  147. if not lib_config.get("enabled", True):
  148. logger.debug(f"Skipping disabled library: {lib_config.get('name')}")
  149. continue
  150. name = lib_config.get("name")
  151. lib_type = lib_config.get("type", "git")
  152. # Resolve library path based on type
  153. if lib_type == "git":
  154. library_path = self._resolve_git_library_path(name, lib_config, libraries_path)
  155. elif lib_type == "static":
  156. library_path = self._resolve_static_library_path(name, lib_config)
  157. if not library_path:
  158. continue
  159. else:
  160. logger.warning(f"Unknown library type '{lib_type}' for library '{name}'")
  161. continue
  162. # Check if library path exists
  163. if not library_path.exists():
  164. self._warn_missing_library(name, library_path, lib_type)
  165. continue
  166. # Create Library instance with priority based on order
  167. priority = len(library_configs) - i
  168. libraries.append(
  169. Library(
  170. name=name,
  171. path=library_path,
  172. priority=priority,
  173. library_type=lib_type,
  174. )
  175. )
  176. logger.debug(f"Loaded {lib_type} library '{name}' from {library_path} with priority {priority}")
  177. if not libraries:
  178. logger.warning("No libraries loaded. Run 'boilerplates repo update' to sync libraries.")
  179. return libraries
  180. def find_by_id(self, module_name: str, template_id: str) -> tuple[Path, str] | None:
  181. """Find a template by its ID across all libraries.
  182. Supports both simple IDs and qualified IDs (template.library format).
  183. Args:
  184. module_name: The module name (e.g., 'compose', 'terraform')
  185. template_id: The template ID to find (simple or qualified)
  186. Returns:
  187. Tuple of (template_path, library_name) if found, None otherwise
  188. """
  189. logger.debug(f"Searching for template '{template_id}' in module '{module_name}' across all libraries")
  190. # Check if this is a qualified ID (contains '.')
  191. if "." in template_id:
  192. parts = template_id.rsplit(".", 1)
  193. if len(parts) == QUALIFIED_ID_PARTS:
  194. base_id, requested_lib = parts
  195. logger.debug(f"Parsing qualified ID: base='{base_id}', library='{requested_lib}'")
  196. # Try to find in the specific library
  197. for library in self.libraries:
  198. if library.name == requested_lib:
  199. try:
  200. template_path, lib_name = library.find_by_id(module_name, base_id)
  201. logger.debug(f"Found template '{base_id}' in library '{requested_lib}'")
  202. return template_path, lib_name
  203. except TemplateNotFoundError:
  204. logger.debug(f"Template '{base_id}' not found in library '{requested_lib}'")
  205. return None
  206. logger.debug(f"Library '{requested_lib}' not found")
  207. return None
  208. # Simple ID - search by priority
  209. for library in sorted(self.libraries, key=lambda x: x.priority, reverse=True):
  210. try:
  211. template_path, lib_name = library.find_by_id(module_name, template_id)
  212. logger.debug(f"Found template '{template_id}' in library '{library.name}'")
  213. return template_path, lib_name
  214. except TemplateNotFoundError:
  215. # Continue searching in next library
  216. continue
  217. logger.debug(f"Template '{template_id}' not found in any library")
  218. return None
  219. def find(self, module_name: str, sort_results: bool = False) -> list[tuple[Path, str, bool]]:
  220. """Find templates across all libraries for a specific module.
  221. Handles duplicates by qualifying IDs with library names when needed.
  222. Args:
  223. module_name: The module name (e.g., 'compose', 'terraform')
  224. sort_results: Whether to return results sorted alphabetically
  225. Returns:
  226. List of tuples (template_path, library_name, needs_qualification)
  227. where needs_qualification is True if the template ID appears in multiple libraries
  228. """
  229. logger.debug(f"Searching for templates in module '{module_name}' across all libraries")
  230. all_templates = []
  231. # Collect templates from all libraries
  232. for library in sorted(self.libraries, key=lambda x: x.priority, reverse=True):
  233. try:
  234. templates = library.find(module_name, sort_results=False)
  235. all_templates.extend(templates)
  236. logger.debug(f"Found {len(templates)} templates in library '{library.name}'")
  237. except (LibraryError, DuplicateTemplateError) as e:
  238. # DuplicateTemplateError from library.find() should propagate up
  239. if isinstance(e, DuplicateTemplateError):
  240. raise
  241. logger.debug(f"Module '{module_name}' not found in library '{library.name}'")
  242. continue
  243. # Track template IDs and their libraries to detect cross-library duplicates
  244. id_to_occurrences = {}
  245. for template_path, library_name in all_templates:
  246. template_id = template_path.name
  247. if template_id not in id_to_occurrences:
  248. id_to_occurrences[template_id] = []
  249. id_to_occurrences[template_id].append((template_path, library_name))
  250. # Build result with qualification markers for duplicates
  251. result = []
  252. for template_id, occurrences in id_to_occurrences.items():
  253. if len(occurrences) > 1:
  254. # Duplicate across libraries - mark for qualified IDs
  255. lib_names = ", ".join(lib for _, lib in occurrences)
  256. logger.info(f"Template '{template_id}' found in multiple libraries: {lib_names}. Using qualified IDs.")
  257. for template_path, library_name in occurrences:
  258. # Mark that this ID needs qualification
  259. result.append((template_path, library_name, True))
  260. else:
  261. # Unique template - no qualification needed
  262. template_path, library_name = occurrences[0]
  263. result.append((template_path, library_name, False))
  264. # Sort if requested
  265. if sort_results:
  266. result.sort(key=lambda x: x[0].name.lower())
  267. logger.debug(f"Found {len(result)} templates total")
  268. return result