Smaller Updates + Build Script!
This commit is contained in:
parent
8d64ae6d0a
commit
5eda941a07
6 changed files with 163 additions and 76 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -1,9 +1,12 @@
|
||||||
__pycache__
|
__pycache__
|
||||||
/bin
|
/bin
|
||||||
|
/build
|
||||||
|
/dist
|
||||||
/include
|
/include
|
||||||
/lib
|
/lib
|
||||||
/lib64
|
/lib64
|
||||||
/logs
|
/logs
|
||||||
|
/main.spec
|
||||||
/out
|
/out
|
||||||
/Scripts
|
/Scripts
|
||||||
/share
|
/share
|
||||||
1
build.bat
Normal file
1
build.bat
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
pyinstaller.exe -F --paths=Lib\site-packages .\src\main.py
|
||||||
|
|
@ -1,3 +1,3 @@
|
||||||
home = /usr/bin
|
home = C:\Users\Jose\AppData\Local\Programs\Python\Python310
|
||||||
include-system-site-packages = false
|
include-system-site-packages = false
|
||||||
version = 3.8.10
|
version = 3.10.4
|
||||||
|
|
|
||||||
0
src/__init__.py
Normal file
0
src/__init__.py
Normal file
82
src/main.py
82
src/main.py
|
|
@ -1,13 +1,24 @@
|
||||||
import argparse
|
import argparse
|
||||||
import logging
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import sys
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from .watcher import Watcher
|
from src.watcher import Watcher
|
||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
|
class LogLevel(Enum):
|
||||||
|
debug = "DEBUG"
|
||||||
|
info = "INFO"
|
||||||
|
warning = "WARNING"
|
||||||
|
error = "ERROR"
|
||||||
|
critical = "CRITICAL"
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.value
|
||||||
|
|
||||||
|
|
||||||
def __init_dirs(dest: str):
|
def __init_dirs(dest: str):
|
||||||
|
|
@ -16,51 +27,74 @@ def __init_dirs(dest: str):
|
||||||
if not os.path.exists("./logs"):
|
if not os.path.exists("./logs"):
|
||||||
os.mkdir("./logs")
|
os.mkdir("./logs")
|
||||||
|
|
||||||
|
|
||||||
def __get_log_version(today: date) -> int:
|
def __get_log_version(today: date) -> int:
|
||||||
existing = list(filter(lambda x: x.startswith(str(today)), os.listdir("./logs")))
|
existing = list(filter(lambda x: x.startswith(str(today)), os.listdir("./logs")))
|
||||||
return len(existing) + 1
|
return len(existing) + 1
|
||||||
|
|
||||||
|
|
||||||
def main(source: str, destination: str) -> None:
|
def main(
|
||||||
""""""
|
source: Path, destination: Path, ignore_pattern: str, log_level: LogLevel
|
||||||
__init_dirs(destination)
|
) -> None:
|
||||||
|
"""
|
||||||
|
Main method for this entire program
|
||||||
|
Arguments:
|
||||||
|
source (pathlib.Path): The path to watch
|
||||||
|
destination (pathlib.Path): The path to copy directory changes to
|
||||||
|
ignore_pattern (str): A regex pattern used to ignore backing up certain directories
|
||||||
|
log_level (LogLevel): The verbosity at which logs should be written. Defaults to ERROR from argparse
|
||||||
|
"""
|
||||||
|
__init_dirs(str(destination))
|
||||||
|
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
logger.setLevel("DEBUG")
|
logger.setLevel(str(log_level))
|
||||||
logging.basicConfig(filename=f"./logs/{now.date()}-{__get_log_version(now.date())}.log")
|
logging.basicConfig(
|
||||||
|
filename=f"./logs/{now.date()}-{__get_log_version(now.date())}.log"
|
||||||
|
)
|
||||||
|
|
||||||
logger.info(f"Watching directory {source}")
|
logger.info(f"Watching directory {source}")
|
||||||
logger.info(f"Backing up to {destination}")
|
logger.info(f"Backing up to {destination}")
|
||||||
|
|
||||||
|
# Spin up a different thread for each subdirectory to keep up with performance
|
||||||
|
subdirs = sorted(
|
||||||
|
list(
|
||||||
|
filter(
|
||||||
|
lambda x: source.joinpath(x).resolve().is_dir(),
|
||||||
|
os.listdir(source),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
threads = [
|
threads = [
|
||||||
Thread(
|
Thread(
|
||||||
|
daemon=True,
|
||||||
target=worker,
|
target=worker,
|
||||||
args=(
|
args=(
|
||||||
logger,
|
logger,
|
||||||
Path(source).absolute().joinpath(dir),
|
source.joinpath(subdir).resolve().absolute(),
|
||||||
Path(destination).absolute().joinpath(dir),
|
destination.joinpath(subdir).resolve().absolute(),
|
||||||
|
ignore_pattern
|
||||||
),
|
),
|
||||||
daemon=True,
|
|
||||||
)
|
|
||||||
for dir in filter(
|
|
||||||
lambda x: os.path.isdir(Path(source).absolute().joinpath(x)),
|
|
||||||
os.listdir(source),
|
|
||||||
)
|
)
|
||||||
|
for subdir in subdirs
|
||||||
]
|
]
|
||||||
|
|
||||||
|
logger.info(f"Starting up {len(threads)} watcher threads")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
[x.start() for x in threads]
|
[x.start() for x in threads]
|
||||||
|
logger.info(f"{len(threads)} Threads started!")
|
||||||
[x.join() for x in threads]
|
[x.join() for x in threads]
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("Waiting for threads to die...")
|
print("Waiting for threads to die...")
|
||||||
|
logger.info("Waiting for threads to die...")
|
||||||
pass # keyboard interrupt should be caught by each thread
|
pass # keyboard interrupt should be caught by each thread
|
||||||
|
|
||||||
|
|
||||||
def worker(logger, source: str, destination: str) -> None:
|
def worker(logger, source: Path, destination: Path, ignore_pattern: str) -> None:
|
||||||
try:
|
try:
|
||||||
watcher = Watcher(logger, source, destination)
|
watcher = Watcher(logger, source, destination, ignore_pattern)
|
||||||
watcher.start()
|
watcher.start()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
watcher.stop()
|
watcher.stop()
|
||||||
|
|
@ -80,6 +114,20 @@ if __name__ == "__main__":
|
||||||
help="The directory to which changed files are mirrored to.",
|
help="The directory to which changed files are mirrored to.",
|
||||||
required=True,
|
required=True,
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-i",
|
||||||
|
"--ignore-pattern",
|
||||||
|
help="A list of directories to ignore when backing up, comma-delimited",
|
||||||
|
default="",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-l",
|
||||||
|
"--log-level",
|
||||||
|
help="Changes logging level to show all debug messages",
|
||||||
|
default=LogLevel.error,
|
||||||
|
type=LogLevel,
|
||||||
|
choices=list(LogLevel),
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
@ -87,4 +135,4 @@ if __name__ == "__main__":
|
||||||
print("Failed to start application:")
|
print("Failed to start application:")
|
||||||
print(e)
|
print(e)
|
||||||
|
|
||||||
main(args.source, args.destination)
|
main(Path(args.source), Path(args.destination), args.ignore_pattern, args.log_level)
|
||||||
|
|
|
||||||
|
|
@ -14,15 +14,18 @@ from watchdog.events import (
|
||||||
)
|
)
|
||||||
from watchdog.observers import Observer
|
from watchdog.observers import Observer
|
||||||
from threading import current_thread
|
from threading import current_thread
|
||||||
|
import re
|
||||||
|
|
||||||
|
|
||||||
class Watcher:
|
class Watcher:
|
||||||
def __init__(self, logger: Logger, source: str, destination: str):
|
def __init__(
|
||||||
|
self, logger: Logger, source: Path, destination: Path, ignore_pattern: str = ""
|
||||||
|
):
|
||||||
self.logger = logger
|
self.logger = logger
|
||||||
self.source = Path(source).absolute()
|
self.source = source.absolute()
|
||||||
self.dest = Path(destination).absolute()
|
self.dest = destination.absolute()
|
||||||
self.observer = Observer()
|
self.observer = Observer()
|
||||||
self.handler = Handler(self.logger, self.source, self.dest)
|
self.handler = Handler(self.logger, self.source, self.dest, ignore_pattern)
|
||||||
self.running = False
|
self.running = False
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
|
|
@ -54,10 +57,13 @@ class Watcher:
|
||||||
|
|
||||||
|
|
||||||
class Handler(FileSystemEventHandler):
|
class Handler(FileSystemEventHandler):
|
||||||
def __init__(self, logger: Logger, source: Path, destination: Path):
|
def __init__(
|
||||||
|
self, logger: Logger, source: Path, destination: Path, ignore_pattern: str
|
||||||
|
):
|
||||||
self.logger = logger
|
self.logger = logger
|
||||||
self.source = source
|
self.source = source
|
||||||
self.dest = destination
|
self.dest = destination
|
||||||
|
self.ignore_pattern = ignore_pattern
|
||||||
|
|
||||||
def __log_event(self, event: FileSystemEvent) -> None:
|
def __log_event(self, event: FileSystemEvent) -> None:
|
||||||
"""
|
"""
|
||||||
|
|
@ -66,8 +72,8 @@ class Handler(FileSystemEventHandler):
|
||||||
event (watchdog.events.FileSystemEvent): the event fired
|
event (watchdog.events.FileSystemEvent): the event fired
|
||||||
"""
|
"""
|
||||||
dest_str = f", dest: {event.dest_path}" if event.dest_path else ""
|
dest_str = f", dest: {event.dest_path}" if event.dest_path else ""
|
||||||
self.logger.info(
|
self.logger.debug(
|
||||||
f"[{current_thread().native_id}] type: {event.event_type}, src: {event.src_path}{dest_str}"
|
f"[{current_thread().native_id}]: type: {event.event_type}, src: {event.src_path}{dest_str}"
|
||||||
)
|
)
|
||||||
|
|
||||||
def __in_destination(self, path: Path) -> Path:
|
def __in_destination(self, path: Path) -> Path:
|
||||||
|
|
@ -112,17 +118,22 @@ class Handler(FileSystemEventHandler):
|
||||||
Arguments:
|
Arguments:
|
||||||
event (watchdog.events.FileCreatedEvent): the event fired
|
event (watchdog.events.FileCreatedEvent): the event fired
|
||||||
"""
|
"""
|
||||||
|
try:
|
||||||
if event.is_directory:
|
if event.is_directory:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if self.ignore_pattern and re.search(self.ignore_pattern, event.src_path):
|
||||||
|
return
|
||||||
|
|
||||||
self.__log_event(event)
|
self.__log_event(event)
|
||||||
src = Path(event.src_path).absolute()
|
src = Path(event.src_path).absolute()
|
||||||
in_dest = self.__in_destination(src)
|
in_dest = self.__in_destination(src)
|
||||||
os.makedirs(in_dest.parent.absolute(), exist_ok=True)
|
os.makedirs(in_dest.parent.absolute(), exist_ok=True)
|
||||||
try:
|
|
||||||
shutil.copy2(src, self.__in_destination(src))
|
shutil.copy2(src, self.__in_destination(src))
|
||||||
except FileNotFoundError:
|
except Exception as exc:
|
||||||
pass # Sometimes files are removed by an external app before we finish processing
|
self.logger.warn(
|
||||||
|
f"[{current_thread().native_id}]: Exception thrown in Handler#on_created:\n\t{exc}"
|
||||||
|
)
|
||||||
|
|
||||||
def on_modified(self, event: FileModifiedEvent) -> None:
|
def on_modified(self, event: FileModifiedEvent) -> None:
|
||||||
"""
|
"""
|
||||||
|
|
@ -131,9 +142,13 @@ class Handler(FileSystemEventHandler):
|
||||||
Arguments:
|
Arguments:
|
||||||
event (watchdog.events.FileModifiedEvent): the event fired
|
event (watchdog.events.FileModifiedEvent): the event fired
|
||||||
"""
|
"""
|
||||||
|
try:
|
||||||
if event.is_directory:
|
if event.is_directory:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if self.ignore_pattern and re.search(self.ignore_pattern, event.src_path):
|
||||||
|
return
|
||||||
|
|
||||||
self.__log_event(event)
|
self.__log_event(event)
|
||||||
|
|
||||||
src = Path(event.src_path).absolute()
|
src = Path(event.src_path).absolute()
|
||||||
|
|
@ -144,10 +159,11 @@ class Handler(FileSystemEventHandler):
|
||||||
|
|
||||||
# Copy over the new file, making required subdirectories
|
# Copy over the new file, making required subdirectories
|
||||||
os.makedirs(in_dest.parent.absolute(), exist_ok=True)
|
os.makedirs(in_dest.parent.absolute(), exist_ok=True)
|
||||||
try:
|
|
||||||
shutil.copy2(src, in_dest)
|
shutil.copy2(src, in_dest)
|
||||||
except FileNotFoundError:
|
except Exception as exc:
|
||||||
pass # Sometimes files are removed by an external app before we finish processing
|
self.logger.warn(
|
||||||
|
f"[{current_thread().native_id}]: Exception thrown in Handler#on_modified:\n\t{exc}"
|
||||||
|
)
|
||||||
|
|
||||||
def on_moved(self, event: FileSystemMovedEvent):
|
def on_moved(self, event: FileSystemMovedEvent):
|
||||||
"""
|
"""
|
||||||
|
|
@ -158,9 +174,16 @@ class Handler(FileSystemEventHandler):
|
||||||
Arguments:
|
Arguments:
|
||||||
event (watchdog.events.FileSystemMovedEvent): the event fired
|
event (watchdog.events.FileSystemMovedEvent): the event fired
|
||||||
"""
|
"""
|
||||||
|
try:
|
||||||
if event.is_directory:
|
if event.is_directory:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if self.ignore_pattern and re.search(self.ignore_pattern, event.src_path):
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.ignore_pattern and re.search(self.ignore_pattern, event.dest_path):
|
||||||
|
return
|
||||||
|
|
||||||
self.__log_event(event)
|
self.__log_event(event)
|
||||||
|
|
||||||
src = Path(event.src_path).absolute()
|
src = Path(event.src_path).absolute()
|
||||||
|
|
@ -181,6 +204,10 @@ class Handler(FileSystemEventHandler):
|
||||||
in_dest_before.unlink()
|
in_dest_before.unlink()
|
||||||
|
|
||||||
self.__recursively_clean_dirs_upwards(in_dest_before.parent.absolute())
|
self.__recursively_clean_dirs_upwards(in_dest_before.parent.absolute())
|
||||||
|
except Exception as exc:
|
||||||
|
self.logger.warn(
|
||||||
|
f"[{current_thread().native_id}]: Exception thrown in Handler#on_moved:\n\t{exc}"
|
||||||
|
)
|
||||||
|
|
||||||
def on_deleted(self, event: FileDeletedEvent) -> None:
|
def on_deleted(self, event: FileDeletedEvent) -> None:
|
||||||
"""
|
"""
|
||||||
|
|
@ -188,9 +215,13 @@ class Handler(FileSystemEventHandler):
|
||||||
Arguments:
|
Arguments:
|
||||||
event (watchdog.events.FileDeletedEvent): the event fired
|
event (watchdog.events.FileDeletedEvent): the event fired
|
||||||
"""
|
"""
|
||||||
|
try:
|
||||||
if event.is_directory:
|
if event.is_directory:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if self.ignore_pattern and re.search(self.ignore_pattern, event.src_path):
|
||||||
|
return
|
||||||
|
|
||||||
self.__log_event(event)
|
self.__log_event(event)
|
||||||
|
|
||||||
in_dest = self.__in_destination(event.src_path)
|
in_dest = self.__in_destination(event.src_path)
|
||||||
|
|
@ -199,3 +230,7 @@ class Handler(FileSystemEventHandler):
|
||||||
in_dest.unlink()
|
in_dest.unlink()
|
||||||
|
|
||||||
self.__recursively_clean_dirs_upwards(in_dest.parent.absolute())
|
self.__recursively_clean_dirs_upwards(in_dest.parent.absolute())
|
||||||
|
except Exception as exc:
|
||||||
|
self.logger.warn(
|
||||||
|
f"[{current_thread().native_id}]: Exception thrown in Handler#on_deleted:\n\t{exc}"
|
||||||
|
)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue