From e9b1fe199b1cccd394bd7cbe8a5ab0979a1b9081 Mon Sep 17 00:00:00 2001 From: Jim Martens Date: Wed, 18 Jul 2018 15:01:21 +0200 Subject: [PATCH] Moved validation inside argparse context Signed-off-by: Jim Martens --- src/twomartens/calendarsync/calendarsync.py | 39 ++++++++++++++++----- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/src/twomartens/calendarsync/calendarsync.py b/src/twomartens/calendarsync/calendarsync.py index e2e8e8a..f912432 100644 --- a/src/twomartens/calendarsync/calendarsync.py +++ b/src/twomartens/calendarsync/calendarsync.py @@ -32,17 +32,10 @@ def main() -> None: parser = argparse.ArgumentParser( description="Synchronizes jekyll event collection with remote calendar", ) - parser.add_argument('calendar_url', help='URL to the remote calendar ICS location') - parser.add_argument('event_collection_path', help='Path to event collection directory') + parser.add_argument('calendar_url', type=validate_url, help='URL to the remote calendar ICS location') + parser.add_argument('event_collection_path', type=validate_dir, help='Path to event collection directory') args = parser.parse_args() - # handling exceptions - parsed_url: ParseResult = urlparse(args.calendar_url) - if parsed_url.netloc == '' or parsed_url.scheme == '': - raise ValueError('calendar_url: The given calendar url is not a proper URL.') - if not isdir(args.event_collection_path): - raise ValueError('event_collection_path: The given event collection path is not a directory.') - sync(args.calendar_url, args.event_collection_path) @@ -76,3 +69,31 @@ def sync(calendar_url: str, event_collection_path: str) -> None: event_filename = begin.date().isoformat() + '-' + event.name.replace(' ', '_') + '.markdown' with open(event_collection_path + event_filename, 'w', encoding='utf-8', newline='\n') as event_file: event_file.write(event_content) + + +def validate_url(url: str) -> str: + """ + Validates a URL and returns it on success. + + :param url: URL to verify + :return: verified URL + :raises: argparse.ArgumentTypeError if URL is invalid + """ + parsed_url: ParseResult = urlparse(url) + if parsed_url.netloc == '' or parsed_url.scheme == '': + raise argparse.ArgumentTypeError(f"'{url}' is not a valid URL.") + + return url + + +def validate_dir(directory: str) -> str: + """ + Validates a directory path and returns it on success. + + :param directory: path to directory to verify + :return: verified directory path + :raises: argparse.ArgumentTypeError if directory does not exist + """ + if not isdir(directory): + raise argparse.ArgumentTypeError(f"'{directory}' is not an existing directory.") + return directory