python
#!/usr/bin/env python3
"""
Automated Backup Script with Version Control
This script creates timestamped backups of a source directory or file to a backup directory.
Supports compression (ZIP) and automatic pruning of old backups to keep only the specified number.
Usage:
python backup.py /path/to/source /path/to/backup_dir [options]
Examples:
python backup.py ~/Documents ~/Backups --keep 5
python backup.py ~/Documents ~/Backups --compress --name my_special_backup
"""
import os
import shutil
import datetime
import argparse
import zipfile
import sys
def parse_arguments():
parser = argparse.ArgumentParser(description='Automate backups with version control')
parser.add_argument('source', help='Source directory or file to backup')
parser.add_argument('backup_dir', help='Backup destination directory')
parser.add_argument('--name', help='Custom backup name (default: backup_YYYYMMDD_HHMMSS)')
parser.add_argument('--keep', type=int, default=10, help='Number of latest backups to keep (default: 10)')
parser.add_argument('--compress', action='store_true', help='Compress backup as ZIP file')
parser.add_argument('--dry-run', action='store_true', help='Dry run: show what would be done without changes')
return parser.parse_args()
def generate_backup_name(args):
if args.name:
return args.name
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
return f"backup_{timestamp}"
def create_backup(args, backup_path):
source = os.path.abspath(args.source)
if not os.path.exists(source):
raise FileNotFoundError(f"Source not found: {source}")
print(f"Creating backup of '{source}'...")
if args.compress:
backup_file = backup_path + '.zip'
if args.dry_run:
print(f"Would create ZIP: {backup_file}")
return backup_file
with zipfile.ZipFile(backup_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(source):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, source)
zipf.write(file_path, arcname)
print(f"Compressed backup created: {backup_file}")
return backup_file
else:
# Ensure backup directory exists
os.makedirs(backup_path, exist_ok=True)
if args.dry_run:
print(f"Would copy to directory: {backup_path}")
return backup_path
if os.path.isdir(source):
shutil.copytree(source, backup_path, dirs_exist_ok=True)
elif os.path.isfile(source):
dst_file = os.path.join(backup_path, os.path.basename(source))
shutil.copy2(source, dst_file)
else:
raise ValueError(f"Source is neither a file nor directory: {source}")
print(f"Backup directory created: {backup_path}")
return backup_path
def prune_old_backups(args, backup_dir):
if args.keep <= 0:
print("Pruning disabled (keep <= 0)")
return
backups = []
full_path = os.path.join(backup_dir, '') # Ensure absolute
for item in os.listdir(backup_dir):
item_path = os.path.join(backup_dir, item)
if item.startswith('backup_') and (
item.endswith('.zip') or os.path.isdir(item_path)
):
backups.append(item)
if not backups:
print("No backups found to prune")
return
# Sort by name descending (newest first, since timestamp format sorts chronologically)
backups.sort(reverse=True)
to_delete = backups[args.keep:]
print(f"Pruning {len(to_delete)} old backups (keeping latest {args.keep})...")
for old_backup in to_delete:
old_path = os.path.join(backup_dir, old_backup)
if args.dry_run:
print(f"Would delete: {old_path}")
else:
try:
if old_backup.endswith('.zip'):
os.remove(old_path)
else:
shutil.rmtree(old_path)
print(f"Deleted: {old_path}")
except Exception as e:
print(f"Error deleting {old_path}: {e}", file=sys.stderr)
def main():
args = parse_arguments()
# Ensure backup dir exists
os.makedirs(args.backup_dir, exist_ok=True)
backup_name = generate_backup_name(args)
backup_path = os.path.join(args.backup_dir, backup_name)
created_backup = create_backup(args, backup_path)
print(f"Backup completed: {created_backup}")
prune_old_backups(args, args.backup_dir)
print("Backup process finished.")
if __name__ == '__main__':
main()
This provides simple, effective version control via dated snapshots with cleanup!