- Add return type annotations to __hash__ (-> int) and __eq__ (-> bool) in HistoryEntry - Add TextIO import and type annotations for file parameters - Add type ignore comment for fuzzywuzzy import - Add HistoryEntry import and list type annotations in time_analysis - Add assert statements for Optional[datetime] timestamps - Add TypedDict classes for type-safe pattern dictionaries - Add CommandPattern import and list[CommandPattern] type annotation - Add -> None return types to all test methods - Remove unused HistoryEntry import (F401)
70 lines
2.2 KiB
Python
70 lines
2.2 KiB
Python
"""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)
|