library.py 14 KB

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