|
| 1 | +import os |
| 2 | +import json |
| 3 | +import csv |
| 4 | +import typer |
| 5 | +from rich.console import Console |
| 6 | +from rich.table import Table |
| 7 | + |
| 8 | +from cli.utils.get_translation import get_translation |
| 9 | + |
| 10 | +def export_results(results, format_type, output_file, messages): |
| 11 | + """ |
| 12 | + Export analysis results to a file in the specified format. |
| 13 | + |
| 14 | + Args: |
| 15 | + results (dict): Analysis results to export |
| 16 | + format_type (str): Format to export (json, csv, html, markdown) |
| 17 | + output_file (str): Path to output file |
| 18 | + messages (dict): Translation messages |
| 19 | + |
| 20 | + Returns: |
| 21 | + bool: True if export was successful, False otherwise |
| 22 | + """ |
| 23 | + try: |
| 24 | + # Create directory if it doesn't exist |
| 25 | + os.makedirs(os.path.dirname(os.path.abspath(output_file)), exist_ok=True) |
| 26 | + |
| 27 | + if format_type == "json": |
| 28 | + with open(output_file, "w", encoding="utf-8") as f: |
| 29 | + json.dump(results, f, indent=2) |
| 30 | + |
| 31 | + elif format_type == "csv": |
| 32 | + with open(output_file, "w", encoding="utf-8", newline="") as f: |
| 33 | + writer = csv.writer(f) |
| 34 | + # Write header |
| 35 | + writer.writerow(["Metric", "Value"]) |
| 36 | + # Write data |
| 37 | + for key, value in results.items(): |
| 38 | + if isinstance(value, (int, float, str)): |
| 39 | + writer.writerow([key, value]) |
| 40 | + elif isinstance(value, list): |
| 41 | + writer.writerow([key, json.dumps(value)]) |
| 42 | + |
| 43 | + elif format_type == "markdown": |
| 44 | + with open(output_file, "w", encoding="utf-8") as f: |
| 45 | + f.write(f"# {messages.get('analysis_results', 'Analysis Results')}\n\n") |
| 46 | + f.write(f"**{messages.get('file_name', 'File')}: {results.get('file_name', 'Unknown')}**\n\n") |
| 47 | + f.write("| Metric | Value |\n") |
| 48 | + f.write("|--------|-------|\n") |
| 49 | + for key, value in results.items(): |
| 50 | + if isinstance(value, (int, float, str)): |
| 51 | + f.write(f"| {key.replace('_', ' ').title()} | {value} |\n") |
| 52 | + elif isinstance(value, list) and key == "indentation_levels": |
| 53 | + f.write(f"| {key.replace('_', ' ').title()} | {len(value)} levels |\n") |
| 54 | + |
| 55 | + elif format_type == "html": |
| 56 | + with open(output_file, "w", encoding="utf-8") as f: |
| 57 | + f.write("<!DOCTYPE html>\n<html>\n<head>\n") |
| 58 | + f.write("<meta charset=\"utf-8\">\n") |
| 59 | + f.write("<title>SpiceCode Analysis Results</title>\n") |
| 60 | + f.write("<style>\n") |
| 61 | + f.write("body { font-family: Arial, sans-serif; margin: 20px; }\n") |
| 62 | + f.write("table { border-collapse: collapse; width: 100%; }\n") |
| 63 | + f.write("th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }\n") |
| 64 | + f.write("th { background-color: #f2f2f2; }\n") |
| 65 | + f.write("h1 { color: #333; }\n") |
| 66 | + f.write("</style>\n</head>\n<body>\n") |
| 67 | + f.write(f"<h1>{messages.get('analysis_results', 'Analysis Results')}</h1>\n") |
| 68 | + f.write(f"<p><strong>{messages.get('file_name', 'File')}: {results.get('file_name', 'Unknown')}</strong></p>\n") |
| 69 | + f.write("<table>\n<tr><th>Metric</th><th>Value</th></tr>\n") |
| 70 | + for key, value in results.items(): |
| 71 | + if isinstance(value, (int, float, str)): |
| 72 | + f.write(f"<tr><td>{key.replace('_', ' ').title()}</td><td>{value}</td></tr>\n") |
| 73 | + elif isinstance(value, list) and key == "indentation_levels": |
| 74 | + f.write(f"<tr><td>{key.replace('_', ' ').title()}</td><td>{len(value)} levels</td></tr>\n") |
| 75 | + f.write("</table>\n</body>\n</html>") |
| 76 | + |
| 77 | + else: |
| 78 | + return False |
| 79 | + |
| 80 | + return True |
| 81 | + |
| 82 | + except Exception as e: |
| 83 | + print(f"{messages.get('export_error', 'Export error')}: {str(e)}") |
| 84 | + return False |
| 85 | + |
| 86 | +def export_command(file, format_type, output, LANG_FILE): |
| 87 | + """ |
| 88 | + Export analysis results to a file. |
| 89 | + """ |
| 90 | + # Load translations |
| 91 | + messages = get_translation(LANG_FILE) |
| 92 | + console = Console() |
| 93 | + |
| 94 | + # Validate format type |
| 95 | + valid_formats = ["json", "csv", "markdown", "html"] |
| 96 | + if format_type not in valid_formats: |
| 97 | + console.print(f"[red]{messages.get('invalid_format', 'Invalid format')}[/] {format_type}") |
| 98 | + console.print(f"{messages.get('valid_formats', 'Valid formats')}: {', '.join(valid_formats)}") |
| 99 | + return |
| 100 | + |
| 101 | + try: |
| 102 | + # Analyze file |
| 103 | + from spice.analyze import analyze_file |
| 104 | + results = analyze_file(file) |
| 105 | + |
| 106 | + # Set default output file if not provided |
| 107 | + if not output: |
| 108 | + base_name = os.path.splitext(os.path.basename(file))[0] |
| 109 | + output = f"{base_name}_analysis.{format_type}" |
| 110 | + |
| 111 | + # Export results |
| 112 | + success = export_results(results, format_type, output, messages) |
| 113 | + |
| 114 | + if success: |
| 115 | + console.print(f"[green]{messages.get('export_success', 'Export successful')}[/]: {output}") |
| 116 | + else: |
| 117 | + console.print(f"[red]{messages.get('export_failed', 'Export failed')}[/]") |
| 118 | + |
| 119 | + except Exception as e: |
| 120 | + console.print(f"[red]{messages.get('error', 'Error')}[/]: {str(e)}") |
0 commit comments