|
| 1 | +from argparse import ArgumentError, ArgumentParser |
| 2 | +from collections import Counter |
| 3 | +from re import finditer |
| 4 | + |
| 5 | +from benedict.serializers.abstract import AbstractSerializer |
| 6 | +from benedict.utils import type_util |
| 7 | + |
| 8 | + |
| 9 | +class CLISerializer(AbstractSerializer): |
| 10 | + """ |
| 11 | + This class describes a CLI serializer. |
| 12 | + """ |
| 13 | + |
| 14 | + regex_keys_with_values = r"-+\w+(?=\s[^\s-])" |
| 15 | + """ |
| 16 | + Regex string. |
| 17 | + Used to search for keys (e.g. -STRING or --STRING) |
| 18 | + that *aren't* followed by another key |
| 19 | +
|
| 20 | + Example input: script.py --username example --verbose -d -e [email protected] |
| 21 | + - Matches: --username, -e |
| 22 | + - Doesn't match: script.py, example, --verbose, -d, [email protected] |
| 23 | + """ |
| 24 | + |
| 25 | + regex_all_keys = r"-+\w+" |
| 26 | + """ |
| 27 | + Regex string. |
| 28 | + Used to search for keys (e.g. -STRING or --STRING) |
| 29 | + no matter if they are followed by another key |
| 30 | +
|
| 31 | + Example input: script.py --username example --verbose -d -e [email protected] |
| 32 | + - Matches: --username, --verbose, -d, -e |
| 33 | + - Doesn't match: script.py, example, [email protected] |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__(self): |
| 37 | + super().__init__( |
| 38 | + extensions=["cli"], |
| 39 | + ) |
| 40 | + |
| 41 | + @staticmethod |
| 42 | + def parse_keys(regex, string): |
| 43 | + # For some reason findall didn't work |
| 44 | + results = [match.group(0) for match in finditer(regex, string)] |
| 45 | + return results |
| 46 | + |
| 47 | + """Helper method, returns a list of --keys based on the regex used""" |
| 48 | + |
| 49 | + @staticmethod |
| 50 | + def _get_parser(options): |
| 51 | + parser = ArgumentParser(**options) |
| 52 | + return parser |
| 53 | + |
| 54 | + def decode(self, s=None, **kwargs): |
| 55 | + parser = self._get_parser(options=kwargs) |
| 56 | + |
| 57 | + keys_with_values = set(self.parse_keys(self.regex_keys_with_values, s)) |
| 58 | + all_keys = Counter(self.parse_keys(self.regex_all_keys, s)) |
| 59 | + for key in all_keys: |
| 60 | + count = all_keys[key] |
| 61 | + |
| 62 | + try: |
| 63 | + # If the key has a value... |
| 64 | + if key in keys_with_values: |
| 65 | + # and is defined once, collect the values |
| 66 | + if count == 1: |
| 67 | + parser.add_argument( |
| 68 | + key, |
| 69 | + nargs="*", |
| 70 | + # This puts multiple values in a list |
| 71 | + # even though this won't always be wanted |
| 72 | + # This is adressed after the dict is generated |
| 73 | + required=False, |
| 74 | + ) |
| 75 | + # and is defined multiple times, collect the values |
| 76 | + else: |
| 77 | + parser.add_argument(key, action="append", required=False) |
| 78 | + |
| 79 | + # If the key doesn't have a value... |
| 80 | + else: |
| 81 | + # and is defined once, store as bool |
| 82 | + if count <= 1: |
| 83 | + parser.add_argument(key, action="store_true", required=False) |
| 84 | + # and is defined multiple times, count how many times |
| 85 | + else: |
| 86 | + parser.add_argument(key, action="count", required=False) |
| 87 | + |
| 88 | + except ArgumentError as error: |
| 89 | + raise ValueError from error |
| 90 | + |
| 91 | + try: |
| 92 | + args = parser.parse_args(s.split()) |
| 93 | + except BaseException as error: |
| 94 | + raise ValueError from error |
| 95 | + |
| 96 | + dict = vars(args) |
| 97 | + for key in dict: |
| 98 | + value = dict[key] |
| 99 | + # If only one value was written, |
| 100 | + # return that value instead of a list |
| 101 | + if type_util.is_list(value) and len(value) == 1: |
| 102 | + dict[key] = value[0] |
| 103 | + |
| 104 | + return dict |
0 commit comments