| 68 | |
| 69 | |
| 70 | class NamespacedOptionParser: |
| 71 | |
| 72 | def __init__(self, args): |
| 73 | self.args = args |
| 74 | self.options = OrderedDict() |
| 75 | self.values = [] |
| 76 | self.passthrough = '' |
| 77 | self.namespaces = defaultdict(lambda: OrderedDict()) |
| 78 | |
| 79 | def parse(self): |
| 80 | rargs = [arg for arg in self.args if arg] |
| 81 | pos = 0 |
| 82 | while pos < len(rargs): |
| 83 | arg = rargs[pos] |
| 84 | if arg == '--': |
| 85 | self.passthrough = ' '.join(rargs[pos:]) |
| 86 | break |
| 87 | elif arg[0] == '-': |
| 88 | if arg[1] == '-': |
| 89 | self.process_long_opt(arg[2:]) |
| 90 | else: |
| 91 | value = None |
| 92 | if len(rargs) > pos + 1 and rargs[pos + 1][0] != '-': |
| 93 | value = rargs[pos + 1] |
| 94 | pos += 1 |
| 95 | self.process_short_opt(arg[1:], value) |
| 96 | else: |
| 97 | self.values.append(arg) |
| 98 | pos += 1 |
| 99 | |
| 100 | def process_long_opt(self, arg, value=None): |
| 101 | if '=' in arg: |
| 102 | arg, value = arg.split('=', 1) |
| 103 | self.add_option(arg, value, short=False) |
| 104 | |
| 105 | def process_short_opt(self, arg, value=None): |
| 106 | self.add_option(arg, value, short=True) |
| 107 | |
| 108 | def optmerge(self, ns, defaults=None): |
| 109 | if defaults is None: |
| 110 | defaults = self.options |
| 111 | return OrderedDict(defaults, **self.namespaces[ns]) |
| 112 | |
| 113 | def add_option(self, name, value, short=False, ns=None): |
| 114 | prefix = short and '-' or '--' |
| 115 | dest = self.options |
| 116 | if ':' in name: |
| 117 | name, ns = name.split(':') |
| 118 | dest = self.namespaces[ns] |
| 119 | dest[prefix + name] = value |
| 120 | |
| 121 | |
| 122 | class Node: |
no outgoing calls