Skip to content

Commit

Permalink
style: add type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
YisusChrist committed Sep 17, 2024
1 parent 1844e48 commit e5db568
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 25 deletions.
47 changes: 26 additions & 21 deletions pybacker/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

import sys
import time
from argparse import Namespace
from pathlib import Path
from shutil import copytree, rmtree
from tkinter import Tk, filedialog
from typing import NoReturn

from core_helpers.updates import check_updates
from rich import print
Expand Down Expand Up @@ -35,7 +37,7 @@ def check_dir_list(dirs: list) -> bool:

def create_backup_dir(output: str, base_path: str) -> Path:
if output:
backup_dir = Path(output).resolve()
backup_dir: Path = Path(output).resolve()
elif base_path:
if not Path(base_path).exists():
print(f" [red]ERROR[/]: Base path '{base_path}' does not exist")
Expand All @@ -60,15 +62,15 @@ def create_backup_dir(output: str, base_path: str) -> Path:
return backup_dir


def check_directories(backup_dir, files):
def check_directories(backup_dir: Path, files: list[str]) -> None:
if not check_dir_list(files):
print(" [red]ERROR[/]: Some directories do not exist")
cleanup_and_exit(EXIT_FAILURE, backup_dir)

print(" All directories exist")


def create_empty(backup_dir: Path, files: list) -> None:
def create_empty(backup_dir: Path, files: list[str]) -> None:
"""
Create empty containers for the files to be backed up
Expand All @@ -81,6 +83,7 @@ def create_empty(backup_dir: Path, files: list) -> None:
so that the files can be copied to the backup directory
without having to create the directories and files manually
"""
file_path: Path
for file in files:
try:
file_path = Path(*Path(file).parent.parts[1:])
Expand All @@ -95,29 +98,29 @@ def create_empty(backup_dir: Path, files: list) -> None:
file_path.mkdir(parents=True, exist_ok=True)


def get_file_list(backup_dir: Path) -> list:
def get_file_list(backup_dir: Path) -> list[str]:
"""
Get the list of files to be backed up from a file
Returns:
list: List of files to be backed up
list[str]: List of files to be backed up
"""
print(" Select the file with the list to be backed up")
# Create a Tk root window
root = Tk()
# Hide the main window
root.withdraw()
# Ask the user to select a file
file_path = filedialog.askopenfilename()
file_path: str = filedialog.askopenfilename()
if not file_path:
print(" No file selected.")
cleanup_and_exit(EXIT_FAILURE, backup_dir)

file_name = Path(file_path).name
file_name: str = Path(file_path).name
print(f" Reading file '{file_name}'...")

with open(file_path, "r", encoding="utf-8") as f:
files = [
files: list[str] = [
line.strip()
for line in f.readlines()
if not line.startswith("#") and line.strip()
Expand All @@ -126,11 +129,11 @@ def get_file_list(backup_dir: Path) -> list:
return files


def copy_files(backup_dir: Path, files: list) -> None:
def copy_files(backup_dir: Path, files: list[str]) -> None:
count = 0
for i, file in enumerate(files):
source_path = Path(file)
dest_path = backup_dir.joinpath(Path(*Path(file).parts[1:]))
dest_path: Path = backup_dir.joinpath(Path(*Path(file).parts[1:]))

try:
copytree(source_path, dest_path, dirs_exist_ok=True)
Expand All @@ -143,9 +146,11 @@ def copy_files(backup_dir: Path, files: list) -> None:
print(f" {count}/{len(files)} files backed up")


def check_backup_directory(backup_dir, files):
source_files = [Path(file) for file in files]
bak_files = [backup_dir.joinpath(Path(*file.parts[1:])) for file in source_files]
def check_backup_directory(backup_dir: Path, files: list[str]) -> None:
source_files: list[Path] = [Path(file) for file in files]
bak_files: list[Path] = [
backup_dir.joinpath(Path(*file.parts[1:])) for file in source_files
]

# Check if source folders exist in backup directory
if not check_dir_list([str(bak_file) for bak_file in bak_files]):
Expand All @@ -154,15 +159,15 @@ def check_backup_directory(backup_dir, files):

# Check if the number of files in the source directory matches the backup directory
for source_file, bak_file in zip(source_files, bak_files):
source_file_count = sum(1 for _ in source_file.rglob("*") if _.is_file())
bak_file_count = sum(1 for _ in bak_file.rglob("*") if _.is_file())
source_file_count: int = sum(1 for _ in source_file.rglob("*") if _.is_file())
bak_file_count: int = sum(1 for _ in bak_file.rglob("*") if _.is_file())

if source_file_count != bak_file_count:
print(f" [red]ERROR[/]: File count mismatch for '{source_file}'.")
cleanup_and_exit(EXIT_FAILURE, backup_dir)

source_dir_count = sum(1 for _ in source_file.rglob("*") if _.is_dir())
bak_dir_count = sum(1 for _ in bak_file.rglob("*") if _.is_dir())
source_dir_count: int = sum(1 for _ in source_file.rglob("*") if _.is_dir())
bak_dir_count: int = sum(1 for _ in bak_file.rglob("*") if _.is_dir())

if source_dir_count != bak_dir_count:
print(f" [red]ERROR[/]: Folder count mismatch for '{source_file}'.")
Expand All @@ -184,15 +189,15 @@ def cleanup_and_exit(exit_code: int, backup_dir: Path) -> None:
sys.exit(exit_code)


def main():
args = get_parsed_args()
def main() -> NoReturn:
args: Namespace = get_parsed_args()
check_updates(GITHUB, VERSION)

print("1. Creating backup directory...")
backup_dir = create_backup_dir(output=args.output, base_path=args.path)
backup_dir: Path = create_backup_dir(output=args.output, base_path=args.path)

print("2. Getting list of files to be backed up...")
files = get_file_list(backup_dir)
files: list[str] = get_file_list(backup_dir)

print("3. Checking directories...")
check_directories(backup_dir, files)
Expand Down
10 changes: 6 additions & 4 deletions pybacker/consts.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
"""Constants for the project."""

from typing import Any

try:
from importlib import metadata
except ImportError: # for Python < 3.8
import importlib_metadata as metadata # type: ignore

__version__ = metadata.version(__package__ or __name__)
__desc__ = metadata.metadata(__package__ or __name__)["Summary"]
PACKAGE = metadata.metadata(__package__ or __name__)["Name"]
GITHUB = metadata.metadata(__package__ or __name__)["Home-page"]
__version__: str | Any = metadata.version(__package__ or __name__)
__desc__: str | Any = metadata.metadata(__package__ or __name__)["Summary"]
PACKAGE: str | Any = metadata.metadata(__package__ or __name__)["Name"]
GITHUB: str | Any = metadata.metadata(__package__ or __name__)["Home-page"]

MAX_TIMEOUT = 5

Expand Down

0 comments on commit e5db568

Please sign in to comment.