101 lines
3.1 KiB
Python
101 lines
3.1 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Snippet Summarizer - Generates formatted code snippet reports
|
|
Usage: python snippet-summarizer.py <directory> [--output <file>]
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import json
|
|
from pathlib import Path
|
|
from datetime import datetime
|
|
from typing import List, Dict, Any
|
|
|
|
def get_snippet_info(filepath: Path) -> Dict[str, Any]:
|
|
"""Extract snippet metadata from a source file."""
|
|
try:
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
content = f.read()
|
|
|
|
lines = content.split('\n')
|
|
return {
|
|
'path': str(filepath),
|
|
'filename': filepath.name,
|
|
'extension': filepath.suffix,
|
|
'lines': len(lines),
|
|
'characters': len(content),
|
|
'size_kb': len(content.encode('utf-8')) / 1024,
|
|
'first_line': lines[0] if lines else '',
|
|
'hash': ''
|
|
}
|
|
except Exception as e:
|
|
return {
|
|
'path': str(filepath),
|
|
'error': str(e)
|
|
}
|
|
|
|
def generate_report(directory: str, output_file: str = None) -> Dict[str, Any]:
|
|
"""Generate a code snippet summary report."""
|
|
dir_path = Path(directory)
|
|
|
|
if not dir_path.exists():
|
|
raise ValueError(f"Directory does not exist: {directory}")
|
|
|
|
# Find all Python source files
|
|
snippets = []
|
|
for py_file in dir_path.rglob('*.py'):
|
|
if not py_file.name.startswith('__'):
|
|
snippets.append(get_snippet_info(py_file))
|
|
|
|
report = {
|
|
'generated_at': datetime.now().isoformat(),
|
|
'directory': str(dir_path.absolute()),
|
|
'total_snippets': len(snippets),
|
|
'total_lines': sum(s.get('lines', 0) for s in snippets),
|
|
'total_size_kb': sum(s.get('size_kb', 0) for s in snippets),
|
|
'snippets': snippets,
|
|
'summary': {
|
|
'by_extension': {},
|
|
'avg_lines': sum(s.get('lines', 0) for s in snippets) / len(snippets) if snippets else 0
|
|
}
|
|
}
|
|
|
|
# Group by extension
|
|
for s in snippets:
|
|
ext = s.get('extension', 'unknown')
|
|
report['summary']['by_extension'][ext] = report['summary']['by_extension'].get(ext, 0) + 1
|
|
|
|
# Write output
|
|
output = json.dumps(report, indent=2)
|
|
|
|
if output_file:
|
|
with open(output_file, 'w', encoding='utf-8') as f:
|
|
f.write(output)
|
|
print(f"Report written to: {output_file}")
|
|
|
|
return report
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python snippet-summarizer.py <directory> [--output <file>]")
|
|
sys.exit(1)
|
|
|
|
directory = sys.argv[1]
|
|
output_file = None
|
|
|
|
if '--output' in sys.argv:
|
|
idx = sys.argv.index('--output')
|
|
if idx + 1 < len(sys.argv):
|
|
output_file = sys.argv[idx + 1]
|
|
|
|
try:
|
|
report = generate_report(directory, output_file)
|
|
print(f"Processed {report['total_snippets']} snippets")
|
|
print(f"Total lines: {report['total_lines']}")
|
|
print(f"Total size: {report['total_size_kb']:.2f} KB")
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
sys.exit(1)
|
|
|
|
if __name__ == '__main__':
|
|
main() |