72 lines
1.6 KiB
Python
72 lines
1.6 KiB
Python
import os
|
|
import shutil
|
|
from datetime import datetime
|
|
from typing import List
|
|
import dotenv
|
|
|
|
"""
|
|
Load config
|
|
"""
|
|
dotenv.load_dotenv()
|
|
CONFIG = {
|
|
"source_dir": os.getenv("SOURCE_DIR"),
|
|
"backup_dir": os.getenv("BACKUP_DIR"),
|
|
"max_backups": int(f"{os.getenv("MAX_BACKUPS")}")
|
|
}
|
|
|
|
|
|
def copy_to_backup() -> None:
|
|
"""
|
|
Copies the source dir to the backup dir.
|
|
"""
|
|
timestamp = datetime.now()
|
|
|
|
src_dir = f"{CONFIG['source_dir']}"
|
|
dst_dir = f"{CONFIG['backup_dir']}/{timestamp.isoformat()}"
|
|
print(f"Copying from: {src_dir} to: {dst_dir}")
|
|
shutil.copytree(src_dir, dst_dir)
|
|
|
|
|
|
def find_backups() -> List[str]:
|
|
"""
|
|
List the current backups located in the backup dir.
|
|
"""
|
|
path = f"{CONFIG["backup_dir"]}"
|
|
return os.listdir(path)
|
|
|
|
|
|
def sort_by_oldest(path: List[str]) -> List[str]:
|
|
"""
|
|
Sort the directories by age. from oldest to newest.
|
|
"""
|
|
copy = path.copy()
|
|
copy.sort()
|
|
copy.reverse()
|
|
return copy
|
|
|
|
|
|
def delete_backups_over_max(paths: List[str]) -> None:
|
|
"""
|
|
Delete the oldest backups if the max backups has been reached.
|
|
"""
|
|
max = CONFIG["max_backups"]
|
|
paths_sorted = sort_by_oldest(paths)
|
|
overshoot = len(paths_sorted) - max
|
|
|
|
for i in range(0, overshoot):
|
|
backup = paths_sorted[len(paths_sorted) - 1 - i]
|
|
path = f"{CONFIG['backup_dir']}/{backup}"
|
|
shutil.rmtree(path)
|
|
|
|
|
|
def main() -> None:
|
|
copy_to_backup()
|
|
backup_dirs = find_backups()
|
|
if len(backup_dirs) > CONFIG["max_backups"]:
|
|
delete_backups_over_max(backup_dirs)
|
|
|
|
print("Done copying to destination.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |