Skip to content

Instantly share code, notes, and snippets.

@adjam
Created October 29, 2018 18:35
Show Gist options
  • Save adjam/159d452931b894398c4c8608def66c64 to your computer and use it in GitHub Desktop.
Save adjam/159d452931b894398c4c8608def66c64 to your computer and use it in GitHub Desktop.
Simple backup class
#!/usr/bin/env python3
import os
import shutil
class Backer:
"""Implements a backup strategy for a file. You might
use this when preparing to overwrite an important configuration
or log file that's not under version control."""
def __init__(self, filename):
"""Create a new instance for a given file
:param filename the full path to the file to be backed up.
Backups will be created in the same directory."""
self.base = os.path.basename(filename)
self.orig = filename
self.rpr = re.compile(f"{re.escape(self.base)}\\.?(\\d+)?")
def backup(self, retain=5):
"""Backs up the file and rotates previous backups,
retaining a specified number of previous backups.
Copies the existing file to `filename.1`, and copies
existing backups to the next higher backup number,
retaining up to `retain` backup files, including the
original.
:param retain the number of backups (filename.N) to keep.
"""
dirname = os.path.dirname(self.orig)
keepers = [os.path.join(dirname, self.orig)]
for i in range(1, retain + 1):
keepers.append(os.path.join(dirname, f"{self.base}.{i}"))
for i in range(len(keepers) - 2, -1, -1):
if os.path.exists(keepers[i]):
print(f"Copying {keepers[i]} to {keepers[i+1]}", file=sys.stderr)
shutil.copyfile(keepers[i], keepers[i + 1])
return keepers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment