This is a great request for a comprehensive CLI tool. I need to build:
I'll build a comprehensive CLI tool for organizing files using SHA-256 hashing with duplicate detection.
python Copy code
#!/usr/bin/env python3
"""
Content-addressable file organizer using SHA-256 hashing.
Stores files in a hierarchical structure and detects/removes duplicates.
"""
import argparse
import hashlib
import logging
import sqlite3
import json
from pathlib import Path
from typing import Dict, Optional, Tuple, List
from dataclasses import dataclass, asdict
from datetime import datetime
import shutil
from collections import defaultdict
import sys
@dataclass
class FileRecord:
"""Record of an organized file."""
original_path: str
hash_value: str
storage_path: str
file_size: int
timestamp: str
extension: str
class FileHasher:
"""Handles file hashing operations."""
CHUNK_SIZE = 8192 # 8KB chunks for memory efficiency
@staticmethod
def calculate_hash(file_path: Path) -> str:
"""
Calculate SHA-256 hash of a file.
Args:
file_path: Path to the file
Returns:
Hexadecimal hash string
"""
sha256_hash = hashlib.sha256()
try:
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(FileHasher.CHUNK_SIZE), b''):
sha256_hash.update(chunk)
return sha256_hash.hexdigest()
except (IOError, OSError) as e:
logging.error(f"Error hashing {file_path}: {e}")
raise
class FileDatabase:
"""Manages SQLite database for tracking organized files."""
def __init__(self, db_path: Path):
self.db_path = db_path
self._init_db()
def _init_db(self) -> None:
"""Initialize the database with required tables."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
original_path TEXT UNIQUE,
hash_value TEXT NOT NULL,
storage_path TEXT NOT NULL,
file_size INTEGER,
timestamp TEXT,
extension TEXT,
INDEX idx_hash (hash_value)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS duplicates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
hash_value TEXT NOT NULL,
file_count INTEGER,
first_seen TEXT,
UNIQUE(hash_value)
)
''')
conn.commit()
def add_record(self, record: FileRecord) -> bool:
"""
Add a file record to the database.
Returns:
True if added, False if hash already exists
"""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO files
(original_path, hash_value, storage_path, file_size, timestamp, extension)
VALUES (?, ?, ?, ?, ?, ?)
''', (
record.original_path,
record.hash_value,
record.storage_path,
record.file_size,
record.timestamp,
record.extension
))
conn.commit()
return True
except sqlite3.IntegrityError:
return False
def get_record_by_hash(self, hash_value: str) -> Optional[FileRecord]:
"""Retrieve a file record by hash."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
'SELECT original_path, hash_value, storage_path, file_size, timestamp, extension FROM files WHERE hash_value = ?',
(hash_value,)
)
row = cursor.fetchone()
if row:
return FileRecord(*row)
return None
def get_all_records(self) -> List[FileRecord]:
"""Get all file records."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
'SELECT original_path, hash_value, storage_path, file_size, timestamp, extension FROM files'
)
return [FileRecord(*row) for row in cursor.fetchall()]
def get_duplicate_hashes(self) -> Dict[str, List[FileRecord]]:
"""Get all hashes with multiple files."""
duplicates = defaultdict(list)
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT hash_value FROM files
GROUP BY hash_value
HAVING COUNT(*) > 1
''')
duplicate_hashes = [row[0] for row in cursor.fetchall()]
for hash_val in duplicate_hashes:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
'SELECT original_path, hash_value, storage_path, file_size, timestamp, extension FROM files WHERE hash_value = ? ORDER BY timestamp',
(hash_val,)
)
for row in cursor.fetchall():
duplicates[hash_val].append(FileRecord(*row))
return dict(duplicates)
def remove_record(self, original_path: str) -> bool:
"""Remove a file record from database."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM files WHERE original_path = ?', (original_path,))
conn.commit()
return cursor.rowcount > 0
def get_statistics(self) -> Dict:
"""Get database statistics."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM files')
total_files = cursor.fetchone()[0]
cursor.execute('SELECT SUM(file_size) FROM files')
total_size = cursor.fetchone()[0] or 0
cursor.execute('''
SELECT COUNT(*) FROM (
SELECT hash_value FROM files
GROUP BY hash_value
HAVING COUNT(*) > 1
)
''')
duplicate_groups = cursor.fetchone()[0]
cursor.execute('''
SELECT SUM(COUNT(*) - 1) FROM files
GROUP BY hash_value
''')
duplicate_count = cursor.fetchone()[0] or 0
return {
'total_files': total_files,
'total_size_bytes': total_size,
'duplicate_groups': duplicate_groups,
'duplicate_files': duplicate_count,
'unique_files': total_files - duplicate_count
}
class FileOrganizer:
"""Main file organization engine."""
def __init__(
self,
storage_dir: Path,
hash_dir_levels: int = 2,
preserve_extension: bool = True,
dry_run: bool = False,
delete_duplicates: bool = False,
verbose: bool = False
):
"""
Initialize the file organizer.
Args:
storage_dir: Directory to store organized files
hash_dir_levels: Number of directory levels from hash (1-4)
preserve_extension: Whether to keep file extensions
dry_run: Simulate operations without making changes
delete_duplicates: Delete duplicates instead of skipping
verbose: Enable verbose logging
"""
self.storage_dir = Path(storage_dir)
self.storage_dir.mkdir(parents=True, exist_ok=True)
self.hash_dir_levels = max(1, min(4, hash_dir_levels))
self.preserve_extension = preserve_extension
self.dry_run = dry_run
self.delete_duplicates = delete_duplicates
self.verbose = verbose
# Initialize database
self.db_path = self.storage_dir / '.fileorg.db'
self.database = FileDatabase(self.db_path)
# Setup logging
self._setup_logging()
def _setup_logging(self) -> None:
"""Configure logging."""
level = logging.DEBUG if self.verbose else logging.INFO
logging.basicConfig(
level=level,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler(self.storage_dir / '.organize.log')
]
)
def _get_storage_path(self, hash_value: str, extension: str = '') -> Path:
"""
Generate storage path from hash.
Example with hash_dir_levels=2:
abc123def456... -> storage/ab/c1/23def456...
"""
# Create nested directory structure from hash
dir_parts = []
remaining_hash = hash_value
for i in range(self.hash_dir_levels):
# Take 2 characters per level
dir_parts.append(remaining_hash[:2])
remaining_hash = remaining_hash[2:]
# Build path
path = self.storage_dir.joinpath(*dir_parts)
# Create filename from remaining hash + extension
if self.preserve_extension and extension:
filename = f"{remaining_hash}{extension}"
else:
filename = remaining_hash
return path / filename
def organize_file(self, source_path: Path) -> Tuple[bool, str]:
"""
Organize a single file.
Returns:
Tuple of (success, message)
"""
if not source_path.is_file():
return False, f"Not a file: {source_path}"
try:
# Calculate hash
hash_value = FileHasher.calculate_hash(source_path)
logging.debug(f"Hash for {source_path}: {hash_value}")
# Check if hash already exists (duplicate detection)
existing_record = self.database.get_record_by_hash(hash_value)
if existing_record:
if self.delete_duplicates:
if self.dry_run:
msg = f"[DRY-RUN] Would delete duplicate: {source_path} (matches {existing_record.storage_path})"
logging.info(msg)
return True, msg
else:
source_path.unlink()
self.database.remove_record(str(source_path))
msg = f"Deleted duplicate: {source_path}"
logging.info(msg)
return True, msg
else:
msg = f"Duplicate detected (skipped): {source_path} -> {existing_record.storage_path}"
logging.warning(msg)
return False, msg
# Get extension
extension = source_path.suffix
# Generate storage path
storage_path = self._get_storage_path(hash_value, extension)
# Create directories
if not self.dry_run:
storage_path.parent.mkdir(parents=True, exist_ok=True)
# Move/copy file
if self.dry_run:
msg = f"[DRY-RUN] Would move {source_path} -> {storage_path}"
logging.info(msg)
else:
shutil.move(str(source_path), str(storage_path))
logging.info(f"Moved {source_path} -> {storage_path}")
# Record in database
record = FileRecord(
original_path=str(source_path),
hash_value=hash_value,
storage_path=str(storage_path),
file_size=storage_path.stat().st_size if storage_path.exists() else 0,
timestamp=datetime.now().isoformat(),
extension=extension
)
if not self.dry_run:
self.database.add_record(record)
return True, f"Organized: {source_path}"
except Exception as e:
msg = f"Error organizing {source_path}: {e}"
logging.error(msg)
return False, msg
def organize_directory(
self,
source_dir: Path,
pattern: str = '*',
recursive: bool = True
) -> Dict[str, int]:
"""
Organize all files in a directory.
Args:
source_dir: Directory to organize
pattern: File pattern to match (e.g., '*.pdf')
recursive: Whether to scan subdirectories
Returns:
Statistics dictionary
"""
source_dir = Path(source_dir)
if not source_dir.is_dir():
logging.error(f"Not a directory: {source_dir}")
return {'processed': 0, 'successful': 0, 'failed': 0}
# Find matching files
if recursive:
files = list(source_dir.rglob(pattern))
else:
files = list(source_dir.glob(pattern))
logging.info(f"Found {len(files)} files matching '{pattern}'")
stats = {'processed': 0, 'successful': 0, 'failed': 0}
for file_path in files:
if file_path.is_file() and file_path.stat().st_size > 0:
success, msg = self.organize_file(file_path)
stats['processed'] += 1
if success:
stats['successful'] += 1
else:
stats['failed'] += 1
if self.verbose:
logging.debug(msg)
return stats
def verify_storage(self) -> Dict[str, any]:
"""Verify integrity of organized files."""
logging.info("Verifying storage integrity...")
records = self.database.get_all_records()
stats = {
'total_records': len(records),
'valid_files': 0,
'missing_files': 0,
'hash_mismatches': 0,
'errors': []
}
for record in records:
storage_path = Path(record.storage_path)
if not storage_path.exists():
stats['missing_files'] += 1
msg = f"Missing file: {storage_path}"
stats['errors'].append(msg)
logging.warning(msg)
continue
# Recalculate hash
try:
actual_hash = FileHasher.calculate_hash(storage_path)
if actual_hash == record.hash_value:
stats['valid_files'] += 1
else:
stats['hash_mismatches'] += 1
msg = f"Hash mismatch: {storage_path}"
stats['errors'].append(msg)
logging.warning(msg)
except Exception as e:
stats['errors'].append(str(e))
logging.error(f"Error verifying {storage_path}: {e}")
return stats
def get_statistics(self) -> Dict:
"""Get organization statistics."""
db_stats = self.database.get_statistics()
# Calculate actual storage size
total_size = 0
file_count = 0
for file_path in self.storage_dir.rglob('*'):
if file_path.is_file() and not file_path.name.startswith('.'):
total_size += file_path.stat().st_size
file_count += 1
return {
'database': db_stats,
'actual_storage': {
'file_count': file_count,
'total_bytes': total_size,
'storage_dir': str(self.storage_dir)
}
}
def list_duplicates(self) -> List[Dict]:
"""List all duplicate groups."""
duplicates = self.database.get_duplicate_hashes()
result = []
for hash_val, records in duplicates.items():
group = {
'hash': hash_val,
'count': len(records),
'total_size': sum(r.file_size for r in records),
'wasted_space': sum(r.file_size for r in records[1:]),
'files': [
{
'original_path': r.original_path,
'storage_path': r.storage_path,
'size': r.file_size,
'timestamp': r.timestamp
}
for r in records
]
}
result.append(group)
return result
def cleanup_duplicates(self, keep_oldest: bool = True) -> Dict[str, int]:
"""
Remove duplicate files.
Args:
keep_oldest: Keep oldest file, delete newer duplicates
Returns:
Statistics of cleanup
"""
duplicates = self.database.get_duplicate_hashes()
stats = {
'groups_processed': len(duplicates),
'files_deleted': 0,
'space_freed': 0
}
for hash_val, records in duplicates.items():
# Sort by timestamp
sorted_records = sorted(records, key=lambda r: r.timestamp)
# Choose which to keep
if keep_oldest:
keep_record = sorted_records[0]
delete_records = sorted_records[1:]
else:
keep_record = sorted_records[-1]
delete_records = sorted_records[:-1]
logging.info(f"Keeping: {keep_record.storage_path}")
for record in delete_records:
try:
storage_path = Path(record.storage_path)
if not self.dry_run:
if storage_path.exists():
space = storage_path.stat().st_size
storage_path.unlink()
self.database.remove_record(record.original_path)
stats['files_deleted'] += 1
stats['space_freed'] += space
logging.info(f"Deleted duplicate: {storage_path}")
except Exception as e:
logging.error(f"Error deleting {record.storage_path}: {e}")
return stats
def export_manifest(self, output_file: Path) -> bool:
"""Export file manifest to JSON."""
try:
records = self.database.get_all_records()
manifest = [asdict(r) for r in records]
with open(output_file, 'w') as f:
json.dump(manifest, f, indent=2)
logging.info(f"Manifest exported to {output_file}")
return True
except Exception as e:
logging.error(f"Error exporting manifest: {e}")
return False
def format_bytes(bytes_size: int) -> str:
"""Format bytes to human-readable format."""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_size < 1024.0:
return f"{bytes_size:.2f} {unit}"
bytes_size /= 1024.0
return f"{bytes_size:.2f} PB"
def main():
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
description='Content-addressable file organizer using SHA-256 hashing',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''
Examples:
# Organize all files in a directory
%(prog)s organize /source/dir -s /storage/dir
# Organize with pattern and dry-run
%(prog)s organize /source/dir -s /storage/dir -p "*.pdf" --dry-run
# List duplicates
%(prog)s duplicates -s /storage/dir
# Clean up duplicates keeping oldest
%(prog)s cleanup -s /storage/dir --keep-oldest
# Verify storage integrity
%(prog)s verify -s /storage/dir
# Show statistics
%(prog)s stats -s /storage/dir
'''
)
subparsers = parser.add_subparsers(dest='command', help='Command to execute')
# Organize command
org_parser = subparsers.add_parser('organize', help='Organize files')
org_parser.add_argument('source', type=Path, help='Source directory or file')
org_parser.add_argument('-s', '--storage', type=Path, required=True,
help='Storage directory')
org_parser.add_argument('-p', '--pattern', default='*',
help='File pattern (default: *)')
org_parser.add_argument('-l', '--levels', type=int, default=2,
help='Directory levels in hash path (1-4, default: 2)')
org_parser.add_argument('-r', '--recursive', action='store_true',
help='Recursively process subdirectories')
org_parser.add_argument('--preserve-ext', action='store_true', default=True,
help='Preserve file extensions')
org_parser.add_argument('--delete-duplicates', action='store_true',
help='Delete duplicates instead of skipping')
org_parser.add_argument('--dry-run', action='store_true',
help='Simulate operations without making changes')
org_parser.add_argument('-v', '--verbose', action='store_true',
help='Verbose output')
# Duplicates command
dup_parser = subparsers.add_parser('duplicates', help='List duplicate files')
dup_parser.add_argument('-s', '--storage', type=Path, required=True,
help='Storage directory')
dup_parser.add_argument('--export', type=Path,
help='Export to JSON file')
# Cleanup command
clean_parser = subparsers.add_parser('cleanup', help='Remove duplicate files')
clean_parser.add_argument('-s', '--storage', type=Path, required=True,
help='Storage directory')
clean_parser.add_argument('--keep-oldest', action='store_true',
help='Keep oldest file and delete newer duplicates')
clean_parser.add_argument('--dry-run', action='store_true',
help='Simulate operations')
clean_parser.add_argument('-v', '--verbose', action='store_true',
help='Verbose output')
# Verify command
ver_parser = subparsers.add_parser('verify', help='Verify storage integrity')
ver_parser.add_argument('-s', '--storage', type=Path, required=True,
help='Storage directory')
ver_parser.add_argument('-v', '--verbose', action='store_true',
help='Verbose output')
# Statistics command
stat_parser = subparsers.add_parser('stats', help='Show statistics')
stat_parser.add_argument('-s', '--storage', type=Path, required=True,
help='Storage directory')
# Export command
exp_parser = subparsers.add_parser('export', help='Export manifest')
exp_parser.add_argument('-s', '--storage', type=Path, required=True,
help='Storage directory')
exp_parser.add_argument('-o', '--output', type=Path, required=True,
help='Output JSON file')
args = parser.parse_args()
if not args.command:
parser.print_help()
return
# Create organizer
organizer = FileOrganizer(
storage_dir=args.storage,
hash_dir_levels=getattr(args, 'levels', 2),
preserve_extension=getattr(args, 'preserve_ext', True),
dry_run=getattr(args, 'dry_run', False),
delete_duplicates=getattr(args, 'delete_duplicates', False),
verbose=getattr(args, 'verbose', False)
)
# Execute command
if args.command == 'organize':
if args.source.is_file():
success, msg = organizer.organize_file(args.source)
print(msg)
else:
stats = organizer.organize_directory(
args.source,
pattern=args.pattern,
recursive=args.recursive
)
print(f"\nResults: {stats['successful']}/{stats['processed']} files organized")
if stats['failed'] > 0:
print(f"Failed: {stats['failed']}")
elif args.command == 'duplicates':
duplicates = organizer.list_duplicates()
if not duplicates:
print("No duplicates found!")
else:
print(f"\nFound {len(duplicates)} duplicate groups:\n")
for group in duplicates:
print(f"Hash: {group['hash'][:16]}...")
print(f" Files: {group['count']}")
print(f" Total size: {format_bytes(group['total_size'])}")
print(f" Wasted space: {format_bytes(group['wasted_space'])}")
for i, file in enumerate(group['files'], 1):
print(f" {i}. {file['original_path']} ({format_bytes(file['size'])})")
print()
if args.export:
import json
with open(args.export, 'w') as f:
json.dump(duplicates, f, indent=2)
print(f"Exported to {args.export}")
elif args.command == 'cleanup':
print("Removing duplicates...")
stats = organizer.cleanup_duplicates(keep_oldest=args.keep_oldest)
print(f"Deleted: {stats['files_deleted']} files")
print(f"Freed: {format_bytes(stats['space_freed'])}")
elif args.command == 'verify':
results = organizer.verify_storage()
print(f"\nVerification Results:")
print(f" Total records: {results['total_records']}")
print(f" Valid files: {results['valid_files']}")
print(f" Missing files: {results['missing_files']}")
print(f" Hash mismatches: {results['hash_mismatches']}")
if results['errors']:
print(f"\nErrors: {len(results['errors'])}")
for error in results['errors'][:5]:
print(f" - {error}")
if len(results['errors']) > 5:
print(f" ... and {len(results['errors']) - 5} more")
elif args.command == 'stats':
stats = organizer.get_statistics()
db = stats['database']
storage = stats['actual_storage']
print(f"\nStorage Statistics:")
print(f" Location: {storage['storage_dir']}")
print(f" Total files: {db['total_files']}")
print(f" Unique files: {db['unique_files']}")
print(f" Duplicate groups: {db['duplicate_groups']}")
print(f" Duplicate files: {db['duplicate_files']}")
print(f" Total size: {format_bytes(db['total_size_bytes'])}")
print(f"\n Actual storage:")
print(f" Files: {storage['file_count']}")
print(f" Size: {format_bytes(storage['total_bytes'])}")
elif args.command == 'export':
success = organizer.export_manifest(args.output)
if success:
print(f"Manifest exported to {args.output}")
if __name__ == '__main__':
main()