diff --git a/.termflow/commands/record.py b/.termflow/commands/record.py new file mode 100644 index 0000000..460e1bd --- /dev/null +++ b/.termflow/commands/record.py @@ -0,0 +1,89 @@ +"""Record command for CLI.""" + +import sys +from pathlib import Path +from typing import Optional + +import click +from rich.console import Console +from rich.prompt import Prompt + +from ..core.database import SessionDatabase +from ..core.recorder import InteractiveRecorder + +console = Console() + + +@click.command(name="record") +@click.argument("name", type=str, default=None) +@click.option( + "--interactive/--no-interactive", + default=True, + help="Run in interactive mode", +) +@click.option( + "--from-history", + is_flag=True, + default=False, + help="Record from shell history", +) +@click.option( + "--count", + default=50, + help="Number of history commands to record", +) +@click.option( + "--output", + "-o", + type=click.Path(path_type=Path), + help="Output file for session export", +) +@click.pass_context +def record_cmd( + ctx: click.Context, + name: Optional[str], + interactive: bool, + from_history: bool, + count: int, + output: Optional[Path], +) -> None: + """Record a terminal session.""" + db_path = ctx.obj.get("db", Path.home() / ".termflow" / "sessions.db") + db = SessionDatabase(db_path) + + if not name: + name = Prompt.ask("Enter session name", default=f"session_{len(db.get_all_sessions()) + 1}") + + if interactive: + recorder = InteractiveRecorder(db_path) + session = recorder.run_interactive(name) + + if output: + _export_session(session, output) + + console.print(f"\n[green]Session '{name}' recorded with {session.command_count} commands[/green]") + + elif from_history: + from ..core.recorder import SessionRecorder + + recorder = SessionRecorder(db_path) + session = recorder.record_from_history(name, count=count) + recorder.save_to_database(db) + + console.print(f"\n[green]Recorded {session.command_count} commands from history[/green]") + + if output: + _export_session(session, output) + + else: + console.print("[yellow]Please specify --interactive or --from-history[/yellow]") + + +def _export_session(session, output: Path) -> None: + """Export session to file.""" + import json + + with open(output, "w") as f: + json.dump(session.to_dict(), f, indent=2, default=str) + + console.print(f"[cyan]Session exported to {output}[/cyan]")