소스 검색

fix all templates

xcad 4 달 전
부모
커밋
25db79f60f
4개의 변경된 파일183개의 추가작업 그리고 15개의 파일을 삭제
  1. 25 8
      cli/core/module.py
  2. 0 3
      library/compose/grafana/compose.yaml.j2
  3. 4 4
      library/compose/grafana/template.yaml
  4. 154 0
      tests/test-compose-templates.sh

+ 25 - 8
cli/core/module.py

@@ -1,6 +1,7 @@
 from __future__ import annotations
 
 import logging
+import sys
 from abc import ABC
 from pathlib import Path
 from typing import Any, Optional
@@ -17,6 +18,7 @@ from .template import Template
 
 logger = logging.getLogger(__name__)
 console = Console()
+console_err = Console(stderr=True)
 
 
 def parse_var_inputs(var_options: list[str], extra_args: list[str]) -> dict[str, Any]:
@@ -63,7 +65,10 @@ class Module(ABC):
     self.libraries = LibraryManager()
     self.display = DisplayManager()
 
-  def list(self) -> list[Template]:
+  def list(
+    self,
+    raw: bool = Option(False, "--raw", help="Output raw list format instead of rich table")
+  ) -> list[Template]:
     """List all templates."""
     logger.debug(f"Listing templates for module '{self.name}'")
     templates = []
@@ -80,11 +85,23 @@ class Module(ABC):
     filtered_templates = templates
     
     if filtered_templates:
-      self.display.display_templates_table(
-        filtered_templates,
-        self.name,
-        f"{self.name.capitalize()} templates"
-      )
+      if raw:
+        # Output raw format (tab-separated values for easy filtering with awk/sed/cut)
+        # Format: ID\tNAME\tTAGS\tVERSION\tLIBRARY
+        for template in filtered_templates:
+          name = template.metadata.name or "Unnamed Template"
+          tags_list = template.metadata.tags or []
+          tags = ",".join(tags_list) if tags_list else "-"
+          version = str(template.metadata.version) if template.metadata.version else "-"
+          library = template.metadata.library or "-"
+          print(f"{template.id}\t{name}\t{tags}\t{version}\t{library}")
+      else:
+        # Output rich table format
+        self.display.display_templates_table(
+          filtered_templates,
+          self.name,
+          f"{self.name.capitalize()} templates"
+        )
     else:
       logger.info(f"No templates found for module '{self.name}'")
 
@@ -243,7 +260,7 @@ class Module(ABC):
       
       # Safety check for render result
       if not rendered_files:
-        console.print("[red]Error: Template rendering returned no files[/red]")
+        console_err.print("[red]Error: Template rendering returned no files[/red]")
         raise Exit(code=1)
       
       logger.info(f"Successfully rendered template '{id}'")
@@ -319,7 +336,7 @@ class Module(ABC):
 
     except Exception as e:
       logger.error(f"Error rendering template '{id}': {e}")
-      console.print(f"[red]Error generating template: {e}[/red]")
+      console_err.print(f"[red]Error generating template: {e}[/red]")
       # Stop execution without letting Typer/Click print the exception again.
       raise Exit(code=1)
 

+ 0 - 3
library/compose/grafana/compose.yaml.j2

@@ -4,9 +4,6 @@ services:
     container_name: {{ container_name }}
     environment:
       - TZ={{ container_timezone }}
-      {% if container_hostname -%}
-      - GF_SERVER_DOMAIN={{ container_hostname }}
-      {% endif %}
     {% if ports_enabled %}
     ports:
       - "{{ ports_http }}:3000"

+ 4 - 4
library/compose/grafana/template.yaml

@@ -7,10 +7,10 @@ metadata:
   author: Christian Lempa
   date: '2025-09-28'
   tags:
-  - grafana
-  - monitoring
-  - observability
-  - dashboard
+    - grafana
+    - monitoring
+    - observability
+    - dashboard
 spec:
   general:
     vars:

+ 154 - 0
tests/test-compose-templates.sh

@@ -0,0 +1,154 @@
+#!/usr/bin/env bash
+# Test script for validating all compose templates with dry-run
+# This script iterates through all templates and runs a non-interactive dry-run
+# Output is GitHub Actions friendly and easy to parse
+
+set -euo pipefail
+
+# Colors for output (only if terminal supports it)
+if [[ -t 1 ]]; then
+    RED='\033[0;31m'
+    GREEN='\033[0;32m'
+    YELLOW='\033[1;33m'
+    BLUE='\033[0;34m'
+    NC='\033[0m'
+else
+    RED=''
+    GREEN=''
+    YELLOW=''
+    BLUE=''
+    NC=''
+fi
+
+# Counters
+TOTAL=0
+PASSED=0
+FAILED=0
+FAILED_TEMPLATES=()
+
+# Get script directory and project root
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
+
+# Function to print status (GitHub Actions annotations format)
+print_status() {
+    local status=$1
+    local message=$2
+    case $status in
+        "INFO")
+            echo "[INFO] ${message}"
+            ;;
+        "SUCCESS")
+            echo "[PASS] ${message}"
+            ;;
+        "ERROR")
+            echo "[FAIL] ${message}"
+            # GitHub Actions error annotation
+            if [[ -n "${GITHUB_ACTIONS:-}" ]]; then
+                echo "::error::${message}"
+            fi
+            ;;
+        "WARNING")
+            echo "[WARN] ${message}"
+            if [[ -n "${GITHUB_ACTIONS:-}" ]]; then
+                echo "::warning::${message}"
+            fi
+            ;;
+    esac
+}
+
+# Function to test a single template
+test_template() {
+    local template_id=$1
+    local template_name=$2
+    
+    TOTAL=$((TOTAL + 1))
+    
+    print_status "INFO" "Testing: ${template_id}"
+    
+    # Run the generate command with dry-run and no-interactive
+    # Capture stderr for error reporting
+    local temp_stderr=$(mktemp)
+    if python3 -m cli compose generate "${template_id}" \
+        --dry-run \
+        --no-interactive \
+        > /dev/null 2>"${temp_stderr}"; then
+        print_status "SUCCESS" "${template_id}"
+        PASSED=$((PASSED + 1))
+        rm -f "${temp_stderr}"
+        return 0
+    else
+        print_status "ERROR" "${template_id}"
+        FAILED=$((FAILED + 1))
+        FAILED_TEMPLATES+=("${template_id}")
+        
+        # Show error message from stderr
+        if [[ -s "${temp_stderr}" ]]; then
+            local error_msg=$(cat "${temp_stderr}" | tr '\n' ' ')
+            if [[ -n "${error_msg}" ]]; then
+                echo "  └─ ${error_msg}"
+            fi
+        fi
+        rm -f "${temp_stderr}"
+        return 1
+    fi
+}
+
+# Main execution
+main() {
+    cd "${PROJECT_ROOT}"
+    
+    echo "=========================================="
+    echo "Compose Template Dry-Run Tests"
+    echo "=========================================="
+    print_status "INFO" "Working directory: ${PROJECT_ROOT}"
+    echo ""
+    
+    # Get list of all compose templates
+    local templates
+    if ! templates=$(python3 -m cli compose list --raw 2>&1); then
+        print_status "ERROR" "Failed to retrieve template list"
+        echo "${templates}"
+        exit 1
+    fi
+    
+    # Count total templates
+    local template_count
+    template_count=$(echo "${templates}" | wc -l | tr -d ' ')
+    
+    print_status "INFO" "Found ${template_count} templates to test"
+    echo ""
+    
+    # Iterate through each template
+    while IFS=$'\t' read -r template_id template_name tags version library; do
+        # Continue even if test fails (don't let set -e stop us)
+        test_template "${template_id}" "${template_name}" || true
+    done <<< "${templates}"
+    
+    # Print summary
+    echo ""
+    echo "=========================================="
+    echo "Test Summary"
+    echo "=========================================="
+    echo "Total:    ${TOTAL}"
+    echo "Passed:   ${PASSED}"
+    echo "Failed:   ${FAILED}"
+    
+    # List failed templates if any
+    if [ "${FAILED}" -gt 0 ]; then
+        echo ""
+        echo "Failed templates:"
+        for template in "${FAILED_TEMPLATES[@]}"; do
+            echo "  - ${template}"
+        done
+        echo ""
+        print_status "ERROR" "${FAILED} template(s) failed validation"
+        exit 1
+    else
+        echo ""
+        print_status "SUCCESS" "All templates passed validation!"
+    fi
+}
+
+# Run main function
+main "$@"