From a3cf1dcb9aeee9071180d5c75bf237ecf513c8a9 Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Sat, 20 Jul 2024 00:39:07 -0500 Subject: [PATCH] Initial commit --- .gitignore | 8 +++ pyvenv.cfg | 3 + requirements.txt | 17 +++++ src/main.py | 59 ++++++++++++++++++ src/watcher.py | 159 +++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 246 insertions(+) create mode 100644 .gitignore create mode 100644 pyvenv.cfg create mode 100644 requirements.txt create mode 100644 src/main.py create mode 100644 src/watcher.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0be6c4c --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/bin +/include +/lib +/lib64 +/logs +/out +/share +__pycache__ \ No newline at end of file diff --git a/pyvenv.cfg b/pyvenv.cfg new file mode 100644 index 0000000..853404e --- /dev/null +++ b/pyvenv.cfg @@ -0,0 +1,3 @@ +home = /usr/bin +include-system-site-packages = false +version = 3.8.10 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1314e2b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,17 @@ +astroid==3.2.3 +black==24.4.2 +click==8.1.7 +dill==0.3.8 +isort==5.13.2 +mccabe==0.7.0 +mypy-extensions==1.0.0 +packaging==24.1 +pathspec==0.12.1 +platformdirs==4.2.2 +pylint==3.2.5 +pytoolconfig==1.3.1 +rope==1.13.0 +tomli==2.0.1 +tomlkit==0.13.0 +typing-extensions==4.12.2 +watchdog==4.0.1 diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..dcd1ede --- /dev/null +++ b/src/main.py @@ -0,0 +1,59 @@ +import argparse +import logging +import sys +from datetime import datetime + +import os +from .watcher import Watcher + + +def __init_dirs(dest: str): + if not os.path.exists(dest): + os.makedirs(dest) + if not os.path.exists("./logs"): + os.mkdir("./logs") + + +def main(source: str, destination: str) -> None: + """""" + __init_dirs(destination) + + logger = logging.getLogger(__name__) + logger.setLevel("DEBUG") + logging.basicConfig(filename=f"./logs/{datetime.now()}.log") + + logger.info(f"Watching directory {source}") + logger.info(f"Backing up to {destination}") + + try: + watcher = Watcher(logger, source, destination) + logger.info("Watcher started") + watcher.start() + except KeyboardInterrupt: + logger.info("Stopping watcher") + watcher.stop() + logger.info("Watcher stopped -- quitting!") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "-s", + "--source", + help="The directory to watch for changes. Changes will be watched in all subdirectories.", + required=True, + ) + parser.add_argument( + "-d", + "--destination", + help="The directory to which changed files are mirrored to.", + required=True, + ) + + try: + args = parser.parse_args() + except Exception as e: + print("Failed to start application:") + print(e) + + main(args.source, args.destination) diff --git a/src/watcher.py b/src/watcher.py new file mode 100644 index 0000000..db34825 --- /dev/null +++ b/src/watcher.py @@ -0,0 +1,159 @@ +import os +import shutil +from logging import Logger +from pathlib import Path +from time import sleep + +from watchdog.events import ( + FileCreatedEvent, + FileDeletedEvent, + FileModifiedEvent, + FileSystemEventHandler, + FileSystemMovedEvent, +) +from watchdog.observers import Observer + + +class Watcher: + def __init__(self, logger: Logger, source: str, destination: str): + self.logger = logger + self.source = Path(source).absolute() + self.dest = Path(destination).absolute() + self.observer = Observer() + self.handler = Handler(self.logger, self.source, self.dest) + self.running = False + + def start(self): + + self.observer.schedule(self.handler, self.source, recursive=True) + self.logger.info("Custom handler has been scheduled with the Observer") + + self.observer.start() + self.logger.info("The Observer has been started!") + + self.logger.info("Starting main loop @ 1s polling rate") + self.running = True + while self.running: + sleep(1) + + def stop(self): + self.running = False + self.observer.stop() + self.observer.join() + + +class Handler(FileSystemEventHandler): + def __init__(self, logger: Logger, source: Path, destination: Path): + self.logger = logger + self.source = source + self.dest = destination + + def __in_destination(self, path: Path) -> Path: + """ + Given a path in the watch directory, converts it to the destination's path instead + Arguments: + path (pathlib.Path): The path in the original directory + Returns: + (pathlib.Path): The path, but in the destination directory, as absolute + """ + # Kind of nasty, but convert to string, find & replace source with destination + as_str = str(path).replace(str(self.source), str(self.dest)) + return Path(as_str).absolute() + + def __recursively_clean_dirs_upwards(self, path: Path) -> None: + """ + Removes empty directories at and above the current one. Stops when it reaches a + non-empty directory or recursive path reaches the topmost-path in the destination + Arguments: + path (pathlib.Path): The path (a directory) at which to start the recursive cleanup + """ + # Base case: we've gone all the way back up to the root, and we'll never delete that.. + if path == self.dest: + return + # Ok, the path we're at has items -- no need to keep going up + if [x for x in path.iterdir()]: + return + # Otherwise, we have an empty directory that we should delete + shutil.rmtree(path.absolute()) + # Go up a directory and repeat! + up = path.joinpath("..").resolve().absolute() + self.__recursively_clean_dirs_upwards(up) + + def on_created(self, event: FileCreatedEvent) -> None: + """ + Called upon creation of a new file. Upon creation, will find the same subdirectory + in the destination directory, making any non-existing subdirectories recursively, + then finally copying the file + Arguments: + event (watchdog.events.FileCreatedEvent): the event fired + """ + if event.is_directory: + return + src = Path(event.src_path).absolute() + in_dest = self.__in_destination(src) + os.makedirs(in_dest.parent.absolute(), exist_ok=True) + shutil.copy2(src, self.__in_destination(src)) + + def on_modified(self, event: FileModifiedEvent) -> None: + """ + Called upon modification of a file, at which point the backed up file is + deleted and then re-copied from the source. + Arguments: + event (watchdog.events.FileModifiedEvent): the event fired + """ + if event.is_directory: + return + + src = Path(event.src_path).absolute() + in_dest = self.__in_destination(src) + + if in_dest.exists(): + in_dest.unlink() + + # Copy over the new file, making required subdirectories + os.makedirs(in_dest.parent.absolute(), exist_ok=True) + shutil.copy2(src, in_dest) + + def on_moved(self, event: FileSystemMovedEvent): + """ + Called upon renaming / relocation of a file. Upon movement, it entirely deletes the + prior location as mapped in the destination directory, then essentially does the same + thing as `on_created` for a new directory. Cleans up parent directories from the old + mapping to ensure no empty folders are just left behind + Arguments: + event (watchdog.events.FileSystemMovedEvent): the event fired + """ + if event.is_directory: + return + + src = Path(event.src_path).absolute() + dest = Path(event.dest_path).absolute() + + in_dest_before = self.__in_destination(src) + in_dest = self.__in_destination(dest) + + # Copy over the new file, making required subdirectories + os.makedirs(in_dest.parent.absolute(), exist_ok=True) + shutil.copy2(dest, in_dest) + + # Delete the old file, try to delete parent folder if it's empty + if in_dest_before.exists(): + in_dest_before.unlink() + + self.__recursively_clean_dirs_upwards(in_dest_before.parent.absolute()) + + def on_deleted(self, event: FileDeletedEvent) -> None: + """ + Called upon deletion of a file, at which point the backed up file is deleted + Arguments: + event (watchdog.events.FileDeletedEvent): the event fired + """ + if event.is_directory: + return + + in_dest = self.__in_destination(event.src_path) + + if in_dest.exists(): + in_dest.unlink() + + self.__recursively_clean_dirs_upwards(in_dest.parent.absolute())