104 lines
2.6 KiB
Python
104 lines
2.6 KiB
Python
"""Export command for CLI."""
|
|
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
import click
|
|
from rich.console import Console
|
|
|
|
from ..core.database import SessionDatabase
|
|
from ..exporters.ascii_generator import ASCIIGenerator
|
|
from ..exporters.mermaid_generator import MermaidGenerator
|
|
|
|
console = Console()
|
|
|
|
|
|
@click.command(name="export")
|
|
@click.argument("source", type=str)
|
|
@click.option(
|
|
"--session-id",
|
|
"-s",
|
|
type=int,
|
|
help="Session ID to export",
|
|
)
|
|
@click.option(
|
|
"--format",
|
|
"-f",
|
|
type=click.Choice(["json", "ascii", "mermaid"]),
|
|
default="json",
|
|
help="Export format",
|
|
)
|
|
@click.option(
|
|
"--output",
|
|
"-o",
|
|
type=click.Path(path_type=Path),
|
|
required=True,
|
|
help="Output file",
|
|
)
|
|
@click.pass_context
|
|
def export_cmd(
|
|
ctx: click.Context,
|
|
source: str,
|
|
session_id: Optional[int],
|
|
format: str,
|
|
output: Path,
|
|
) -> None:
|
|
"""Export a session to file."""
|
|
db_path = ctx.obj.get("db")
|
|
db = SessionDatabase(db_path)
|
|
|
|
if session_id is None:
|
|
sessions = db.get_all_sessions()
|
|
if sessions:
|
|
session_id = sessions[0]["id"]
|
|
else:
|
|
console.print("[yellow]No sessions found[/yellow]")
|
|
return
|
|
|
|
if source == "session":
|
|
_export_session(db, session_id, format, output)
|
|
else:
|
|
console.print("[red]Unknown export source[/red]")
|
|
|
|
|
|
def _export_session(db: SessionDatabase, session_id: int, format: str, output: Path) -> None:
|
|
"""Export session to file."""
|
|
session = db.get_session(session_id)
|
|
if not session:
|
|
console.print(f"[red]Session {session_id} not found[/red]")
|
|
return
|
|
|
|
commands = db.get_session_commands(session_id)
|
|
command_list = [cmd.get("command", "") for cmd in commands]
|
|
|
|
if format == "json":
|
|
import json
|
|
|
|
data = {
|
|
"session": session,
|
|
"commands": commands,
|
|
}
|
|
with open(output, "w") as f:
|
|
json.dump(data, f, indent=2, default=str)
|
|
|
|
elif format == "ascii":
|
|
ascii_gen = ASCIIGenerator(style="detailed")
|
|
metadata = {
|
|
"title": f"Session: {session.get('name', 'Unknown')}",
|
|
"command_count": len(command_list),
|
|
}
|
|
result = ascii_gen.generate_from_commands(command_list, metadata)
|
|
with open(output, "w") as f:
|
|
f.write(result)
|
|
|
|
elif format == "mermaid":
|
|
mermaid_gen = MermaidGenerator()
|
|
result = mermaid_gen.generate_flowchart(
|
|
command_list,
|
|
title=f"Session: {session.get('name', 'Unknown')}",
|
|
)
|
|
with open(output, "w") as f:
|
|
f.write(result)
|
|
|
|
console.print(f"[green]Exported to {output}[/green]")
|