From 635dcd38cfbe2934cb88b8a61fe4a92ae6ac39c3 Mon Sep 17 00:00:00 2001 From: Ivan Habunek Date: Tue, 21 Feb 2023 18:08:30 +0100 Subject: [PATCH] Backport argparse BooleanOptionalAction --- toot/console.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/toot/console.py b/toot/console.py index ee41a17..64674fe 100644 --- a/toot/console.py +++ b/toot/console.py @@ -15,6 +15,48 @@ VISIBILITY_CHOICES = ['public', 'unlisted', 'private', 'direct'] VISIBILITY_CHOICES_STR = ", ".join(f"'{v}'" for v in VISIBILITY_CHOICES) +class BooleanOptionalAction(Action): + """ + Backported from argparse. This action is available since Python 3.9. + https://github.com/python/cpython/blob/3.11/Lib/argparse.py + """ + def __init__(self, + option_strings, + dest, + default=None, + type=None, + choices=None, + required=False, + help=None, + metavar=None): + + _option_strings = [] + for option_string in option_strings: + _option_strings.append(option_string) + + if option_string.startswith('--'): + option_string = '--no-' + option_string[2:] + _option_strings.append(option_string) + + super().__init__( + option_strings=_option_strings, + dest=dest, + nargs=0, + default=default, + type=type, + choices=choices, + required=required, + help=help, + metavar=metavar) + + def __call__(self, parser, namespace, values, option_string=None): + if option_string in self.option_strings: + setattr(namespace, self.dest, not option_string.startswith('--no-')) + + def format_usage(self): + return ' | '.join(self.option_strings) + + def get_default_visibility(): return os.getenv("TOOT_POST_VISIBILITY", "public")