helpers.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """
  2. Helper functions for common boilerplate operations.
  3. Provides reusable utilities for scanning directories and formatting output.
  4. """
  5. from pathlib import Path
  6. from typing import List
  7. import frontmatter
  8. from .models import Boilerplate
  9. def find_boilerplates(library_path: Path, file_names: List[str]) -> List[Boilerplate]:
  10. """
  11. Find all boilerplate files in the library directory and extract metadata.
  12. Args:
  13. library_path: Path to the library directory to scan
  14. file_names: List of file names to search for (e.g., ['compose.yaml', 'docker-compose.yaml'])
  15. Returns:
  16. List of Boilerplate objects sorted by name
  17. """
  18. boilerplates = []
  19. # Recursively scan all directories
  20. for boilerplate_file in library_path.rglob("*"):
  21. if boilerplate_file.is_file() and boilerplate_file.name in file_names:
  22. try:
  23. # Parse frontmatter
  24. with open(boilerplate_file, 'r', encoding='utf-8') as f:
  25. post = frontmatter.load(f)
  26. boilerplate = Boilerplate(boilerplate_file, post.metadata, post.content)
  27. # If no name in frontmatter, use a meaningful name based on path
  28. if boilerplate.name == boilerplate_file.stem:
  29. # For nested paths like factory/runner-pool, use "Factory Runner Pool"
  30. relative_path = boilerplate_file.relative_to(library_path)
  31. path_parts = relative_path.parent.parts
  32. boilerplate.name = " ".join(part.replace("_", " ").replace("-", " ").title() for part in path_parts)
  33. boilerplates.append(boilerplate)
  34. except Exception as e:
  35. # If frontmatter parsing fails, create basic info
  36. boilerplate = Boilerplate(boilerplate_file, {}, "")
  37. relative_path = boilerplate_file.relative_to(library_path)
  38. path_parts = relative_path.parent.parts
  39. boilerplate.name = " ".join(part.replace("_", " ").replace("-", " ").title() for part in path_parts)
  40. boilerplates.append(boilerplate)
  41. return sorted(boilerplates, key=lambda x: x.name)