From 4ea7a16d3015ec64135e676318076a31dbf130ce Mon Sep 17 00:00:00 2001 From: Rafael Moraes <50295204+glomatico@users.noreply.github.com> Date: Fri, 4 Jul 2025 18:24:01 -0300 Subject: [PATCH] Refactor prompt_path to improve path validation --- votify/cli.py | 4 ++-- votify/utils.py | 33 ++++++++++++++++++++++++--------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/votify/cli.py b/votify/cli.py index f21aa0e..723626a 100644 --- a/votify/cli.py +++ b/votify/cli.py @@ -400,7 +400,7 @@ def main( stream_handler = logging.StreamHandler() stream_handler.setFormatter(CustomLoggerFormatter()) logger.addHandler(stream_handler) - cookies_path = prompt_path("Cookies file", cookies_path) + cookies_path = prompt_path(True, cookies_path, "Cookies file") logger.info("Starting Votify") spotify_api = SpotifyApi.from_cookies_file(cookies_path) if spotify_api.session_info["isAnonymous"]: @@ -489,7 +489,7 @@ def main( X_NOT_FOUND_STRING.format("mp4decrypt", mp4decrypt_path) ) return - wvd_path = prompt_path(".wvd file", wvd_path) + wvd_path = prompt_path(False, wvd_path, ".wvd file") downloader.set_cdm() if download_mode == DownloadMode.ARIA2C and not downloader.aria2c_path_full: logger.critical(X_NOT_FOUND_STRING.format("aria2c", aria2c_path)) diff --git a/votify/utils.py b/votify/utils.py index 1c1abbe..5b5055b 100644 --- a/votify/utils.py +++ b/votify/utils.py @@ -22,15 +22,30 @@ def _raise_response_exception(response: requests.Response): ) -def prompt_path(path_description: str, path_obj: Path) -> Path: - while not path_obj.exists(): - path_obj_str = click.prompt( - X_NOT_FOUND_STRING.format(path_description, path_obj.absolute()) - + ". Move it to that location or drag and drop it here. Then, press enter to continue", - default=str(path_obj), - show_default=False, - ) - path_obj = Path(path_obj_str.strip('"')) +def prompt_path(is_file: bool, initial_path: Path, description: str) -> Path: + path_validator = click.Path( + exists=True, + file_okay=is_file, + dir_okay=not is_file, + path_type=Path, + ) + while True: + try: + path_obj = path_validator.convert(initial_path, None, None) + break + except click.BadParameter as e: + path_str = click.prompt( + ( + f"{X_NOT_FOUND_STRING.format(description, initial_path.absolute())} or " + "the specified path is not valid. " + "Move it to that location, type the path or drag and drop it here. " + "Then, press enter to continue" + ), + default=str(initial_path), + show_default=False, + ) + path_str = path_str.strip('"') + initial_path = Path(path_str) return path_obj