42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
"""Bash history parser."""
|
|
|
|
import os
|
|
from datetime import datetime
|
|
from typing import List, Optional
|
|
|
|
from .base import HistoryParser, ParsedCommand
|
|
|
|
|
|
class BashHistoryParser(HistoryParser):
|
|
"""Parser for Bash history files."""
|
|
|
|
SHELL_NAME = "bash"
|
|
DEFAULT_HISTORY_FILE = os.path.expanduser("~/.bash_history")
|
|
|
|
def parse_file(self, filepath: str) -> List[ParsedCommand]:
|
|
"""Parse a bash history file."""
|
|
try:
|
|
with open(filepath, 'r', encoding='utf-8', errors='replace') as f:
|
|
content = f.read()
|
|
return self.parse_content(content)
|
|
except FileNotFoundError:
|
|
return []
|
|
except Exception:
|
|
return []
|
|
|
|
def parse_content(self, content: str) -> List[ParsedCommand]:
|
|
"""Parse bash history content from a string."""
|
|
commands = []
|
|
lines = content.splitlines()
|
|
|
|
for line_num, line in enumerate(lines, start=1):
|
|
line = line.rstrip('\n\r')
|
|
if line and not line.startswith('#'):
|
|
cmd = ParsedCommand(
|
|
raw_command=line,
|
|
line_number=line_num
|
|
)
|
|
commands.append(cmd)
|
|
|
|
return commands
|