From 2c4070d24bbd625f4dc15b371673eb7def1f4b4c Mon Sep 17 00:00:00 2001 From: Lara Jensen Date: Sun, 3 May 2026 01:20:34 +0200 Subject: [PATCH] Add backup scrupt. Add .env config --- .gitignore | 7 +++++ main.py | 72 ++++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 1 + 3 files changed, 80 insertions(+) create mode 100644 .gitignore create mode 100644 main.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6f83880 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.env +backup/ +source/ +include/ +bin/ +lib/ +pyvenv.cfg \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..395885b --- /dev/null +++ b/main.py @@ -0,0 +1,72 @@ +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() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c7c1b09 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +python-dotenv==1.2.2