Add backup scrupt. Add .env config
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
.env
|
||||
backup/
|
||||
source/
|
||||
include/
|
||||
bin/
|
||||
lib/
|
||||
pyvenv.cfg
|
||||
@@ -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()
|
||||
@@ -0,0 +1 @@
|
||||
python-dotenv==1.2.2
|
||||
Reference in New Issue
Block a user