|
12 | 12 | import miio
|
13 | 13 | import logging
|
14 | 14 | import json
|
| 15 | +import re |
15 | 16 | from typing import Union
|
16 | 17 | from functools import wraps
|
17 | 18 | from functools import partial
|
@@ -55,6 +56,43 @@ def __call__(self, *args, **kwargs):
|
55 | 56 | click.echo(click.style("Error: %s" % ex, fg='red', bold=True))
|
56 | 57 |
|
57 | 58 |
|
| 59 | +class EnumType(click.Choice): |
| 60 | + def __init__(self, enumcls, casesensitive=True): |
| 61 | + choices = enumcls.__members__ |
| 62 | + |
| 63 | + if not casesensitive: |
| 64 | + choices = (_.lower() for _ in choices) |
| 65 | + |
| 66 | + self._enumcls = enumcls |
| 67 | + self._casesensitive = casesensitive |
| 68 | + |
| 69 | + super().__init__(list(sorted(set(choices)))) |
| 70 | + |
| 71 | + def convert(self, value, param, ctx): |
| 72 | + if not self._casesensitive: |
| 73 | + value = value.lower() |
| 74 | + |
| 75 | + value = super().convert(value, param, ctx) |
| 76 | + |
| 77 | + if not self._casesensitive: |
| 78 | + return next(_ for _ in self._enumcls if _.name.lower() == value.lower()) |
| 79 | + else: |
| 80 | + return next(_ for _ in self._enumcls if _.name == value) |
| 81 | + |
| 82 | + def get_metavar(self, param): |
| 83 | + word = self._enumcls.__name__ |
| 84 | + |
| 85 | + # Stolen from jpvanhal/inflection |
| 86 | + word = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', word) |
| 87 | + word = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', word) |
| 88 | + word = word.replace("-", "_").lower().split("_") |
| 89 | + |
| 90 | + if word[-1] == "enum": |
| 91 | + word.pop() |
| 92 | + |
| 93 | + return ("_".join(word)).upper() |
| 94 | + |
| 95 | + |
58 | 96 | class GlobalContextObject:
|
59 | 97 | def __init__(self, debug: int=0, output: callable=None):
|
60 | 98 | self.debug = debug
|
@@ -221,6 +259,7 @@ def wrap(*args, **kwargs):
|
221 | 259 |
|
222 | 260 | def json_output(pretty=False):
|
223 | 261 | indent = 2 if pretty else None
|
| 262 | + |
224 | 263 | def decorator(func):
|
225 | 264 | @wraps(func)
|
226 | 265 | def wrap(*args, **kwargs):
|
|
0 commit comments