From 960b18a461a69c6cc9864030a9ee39f0c89ebb04 Mon Sep 17 00:00:00 2001 From: Tobias Diekershoff Date: Sat, 14 Jan 2023 12:37:04 +0100 Subject: [PATCH] improved CSV output and error handling --- .../brewserverblocklist.py | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/brewserverblocklist/brewserverblocklist.py b/src/brewserverblocklist/brewserverblocklist.py index b6ffa62..9db2e2c 100644 --- a/src/brewserverblocklist/brewserverblocklist.py +++ b/src/brewserverblocklist/brewserverblocklist.py @@ -8,11 +8,26 @@ of any number of other Friendica instances. See https://git.friendi.ca/tobias/brewserverblocklist """ +import argparse import configparser import sys from os.path import exists import requests -from bargparse.bargparse import MyParser + +class BParser(argparse.ArgumentParser): + """ + This expansion of the ArgParser class will display the --help results by + default if an error occurs (e.g. no arguments are passed to the script). + + It is based on an StackOverflow answer from 2010 by unutbu who refered to + a reply from Steven Bethard as source of the code. + + https://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu/4042861#4042861 + """ + def error(self, message): + sys.stderr.write('error: %s\n' % message) + self.print_help() + sys.exit(2) class BrewBlocklist(): """ @@ -36,7 +51,6 @@ class BrewBlocklist(): config = configparser.RawConfigParser() config.read(configfile) for section in config.sections(): - print(section) section_values = dict(config.items(section)) if (section.find('http://') > -1) or (section.find('https://') > -1): print('The section name in the config file must not contain the protocol ({})'.format(section)) @@ -139,6 +153,12 @@ class BrewBlocklist(): orig_stdout = sys.stdout sys.stdout = out_file for key, value in self.blocklist.items(): + try: + if ("," in self.reasons[key] or " " in self.reasons[key]) and not self.reasons[key].startswith('"'): + self.reasons[key] = '"{}"'.format(self.reasons[key]) + except TypeError: + self.reasons[key] = '"no reason given"' + self.error.append("for {} no blocking reason was provided".format(key)) print('{}, {}, {}'.format(key, self.reasons[key], value)) if self.outputfile: sys.stdout = orig_stdout @@ -157,7 +177,7 @@ def main(): * collect the ingredient * serve the result """ - parser = MyParser() + parser = BParser() parser.add_argument('-c', '--config', dest='configfile', required=True,