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