"""Export functionality for detected patterns.""" from datetime import datetime from pathlib import Path from typing import Optional from shellhist.core import HistoryStore from shellhist.core.patterns import CommandPattern def generate_script( patterns: list[CommandPattern], script_name: str = "shellhist_script", output_dir: Optional[str] = None, dry_run: bool = False, ) -> str: """Generate a shell script from detected patterns. Args: patterns: List of CommandPattern objects to export. script_name: Name for the output script (without extension). output_dir: Optional output directory. If not provided, uses current directory. dry_run: If True, return script content without writing to file. Returns: Path to the generated script or script content if dry_run. """ script_content = _build_script_content(patterns, script_name) if dry_run: return script_content output_path = Path(output_dir) if output_dir else Path.cwd() output_path.mkdir(parents=True, exist_ok=True) script_file = output_path / f"{script_name}.sh" script_file.write_text(script_content, encoding="utf-8") return str(script_file) def _build_script_content(patterns: list[CommandPattern], script_name: str) -> str: """Build the content of the generated shell script.""" lines = [ f"#!/bin/bash", f"# Generated by Shell History Automation Tool", f"# Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", "", f"# {script_name} - Automated shell script from detected patterns", "", ] for i, pattern in enumerate(patterns, 1): if len(pattern.commands) == 1: cmd = pattern.commands[0] lines.append(f"# Pattern {i}: Command run {pattern.frequency} times") lines.append(f"{cmd}") else: cmds = " && ".join(pattern.commands) lines.append(f"# Pattern {i}: Sequence run {pattern.frequency} times") lines.append(f"{cmds}") lines.append("") lines.extend([ "# End of generated script", "echo 'Script execution completed.'", ]) return "\n".join(lines)