File: click_common.py

package info (click to toggle)
python-miio 0.5.12-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,888 kB
  • sloc: python: 23,425; makefile: 9
file content (341 lines) | stat: -rw-r--r-- 10,580 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
"""Click commons.

This file contains common functions for cli tools.
"""
import ast
import ipaddress
import json
import logging
import re
from functools import partial, wraps
from typing import Callable, Set, Type, Union

import click

import miio

from .exceptions import DeviceError

_LOGGER = logging.getLogger(__name__)


def validate_ip(ctx, param, value):
    if value is None:
        return None
    try:
        ipaddress.ip_address(value)
        return value
    except ValueError as ex:
        raise click.BadParameter("Invalid IP: %s" % ex)


def validate_token(ctx, param, value):
    if value is None:
        return None
    token_len = len(value)
    if token_len != 32:
        raise click.BadParameter("Token length != 32 chars: %s" % token_len)
    return value


class ExceptionHandlerGroup(click.Group):
    """Add a simple group for catching the miio-related exceptions.

    This simplifies catching the exceptions from different click commands.

    Idea from https://stackoverflow.com/a/44347763
    """

    def __call__(self, *args, **kwargs):
        try:
            return self.main(*args, **kwargs)
        except miio.DeviceException as ex:
            _LOGGER.debug("Exception: %s", ex, exc_info=True)
            click.echo(click.style("Error: %s" % ex, fg="red", bold=True))


class EnumType(click.Choice):
    def __init__(self, enumcls, casesensitive=False):
        choices = enumcls.__members__

        if not casesensitive:
            choices = (_.lower() for _ in choices)

        self._enumcls = enumcls
        self._casesensitive = casesensitive

        super().__init__(list(sorted(set(choices))))

    def convert(self, value, param, ctx):
        if not self._casesensitive:
            value = value.lower()

        value = super().convert(value, param, ctx)

        if not self._casesensitive:
            return next(_ for _ in self._enumcls if _.name.lower() == value.lower())
        else:
            return next(_ for _ in self._enumcls if _.name == value)

    def get_metavar(self, param):
        word = self._enumcls.__name__

        # Stolen from jpvanhal/inflection
        word = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", word)
        word = re.sub(r"([a-z\d])([A-Z])", r"\1_\2", word)
        word = word.replace("-", "_").lower().split("_")

        if word[-1] == "enum":
            word.pop()

        return ("_".join(word)).upper()


class LiteralParamType(click.ParamType):
    name = "literal"

    def convert(self, value, param, ctx):
        try:
            return ast.literal_eval(value)
        except ValueError:
            self.fail("%s is not a valid literal" % value, param, ctx)


class GlobalContextObject:
    def __init__(self, debug: int = 0, output: Callable = None):
        self.debug = debug
        self.output = output


class DeviceGroupMeta(type):

    _device_classes: Set[Type] = set()

    def __new__(mcs, name, bases, namespace):
        commands = {}

        def _get_commands_for_namespace(namespace):
            commands = {}
            for _, val in namespace.items():
                if not callable(val):
                    continue
                device_group_command = getattr(val, "_device_group_command", None)
                if device_group_command is None:
                    continue
                commands[device_group_command.command_name] = device_group_command

            return commands

        # 1. Go through base classes for commands
        for base in bases:
            commands.update(getattr(base, "_device_group_commands", {}))

        # 2. Add commands from the current class
        commands.update(_get_commands_for_namespace(namespace))

        namespace["_device_group_commands"] = commands
        if "get_device_group" not in namespace:

            def get_device_group(dcls):
                return DeviceGroup(dcls)

            namespace["get_device_group"] = classmethod(get_device_group)

        cls = super().__new__(mcs, name, bases, namespace)
        mcs._device_classes.add(cls)
        return cls

    @property
    def supported_models(cls):
        """Return list of supported models."""
        return cls._mappings.keys() or cls._supported_models


class DeviceGroup(click.MultiCommand):
    class Command:
        def __init__(self, name, decorators, *, default_output=None, **kwargs):
            self.name = name
            self.decorators = list(decorators)
            self.decorators.reverse()
            self.default_output = default_output

            self.kwargs = kwargs

        def __call__(self, func):
            self.func = func
            func._device_group_command = self
            self.kwargs.setdefault("help", self.func.__doc__)

            def _autodetect_model_if_needed(func):
                def _wrap(self, *args, **kwargs):
                    skip_autodetect = func._device_group_command.kwargs.pop(
                        "skip_autodetect", False
                    )
                    if (
                        not skip_autodetect
                        and self._model is None
                        and self._info is None
                    ):
                        _LOGGER.debug(
                            "Unknown model, trying autodetection. %s %s"
                            % (self._model, self._info)
                        )
                        self._fetch_info()
                    return func(self, *args, **kwargs)

                # TODO HACK to make the command visible to cli
                _wrap._device_group_command = func._device_group_command
                return _wrap

            func = _autodetect_model_if_needed(func)

            return func

        @property
        def command_name(self):
            return self.name or self.func.__name__.lower()

        def wrap(self, ctx, func):
            gco = ctx.find_object(GlobalContextObject)
            if gco is not None and gco.output is not None:
                output = gco.output
            elif self.default_output:
                output = self.default_output
            else:
                output = format_output(f"Running command {self.command_name}")

            # Remove skip_autodetect before constructing the click.command
            self.kwargs.pop("skip_autodetect", None)

            func = output(func)
            for decorator in self.decorators:
                func = decorator(func)
            return click.command(self.command_name, **self.kwargs)(func)

        def call(self, owner, *args, **kwargs):
            method = getattr(owner, self.func.__name__)
            return method(*args, **kwargs)

    DEFAULT_PARAMS = [
        click.Option(["--ip"], required=True, callback=validate_ip),
        click.Option(["--token"], required=True, callback=validate_token),
        click.Option(["--model"], required=False),
    ]

    def __init__(
        self,
        device_class,
        name=None,
        invoke_without_command=False,
        no_args_is_help=None,
        subcommand_metavar=None,
        chain=False,
        result_callback=None,
        result_callback_pass_device=True,
        **attrs,
    ):

        self.commands = getattr(device_class, "_device_group_commands", None)
        if self.commands is None:
            raise RuntimeError(
                "Class {} doesn't use DeviceGroupMeta meta class."
                " It can't be used with DeviceGroup."
            )

        self.device_class = device_class
        self.device_pass = click.make_pass_decorator(device_class)

        attrs.setdefault("params", self.DEFAULT_PARAMS)
        attrs.setdefault("callback", click.pass_context(self.group_callback))
        if result_callback_pass_device and callable(result_callback):
            result_callback = self.device_pass(result_callback)

        super().__init__(
            name or device_class.__name__.lower(),
            invoke_without_command,
            no_args_is_help,
            subcommand_metavar,
            chain,
            result_callback,
            **attrs,
        )

    def group_callback(self, ctx, *args, **kwargs):
        gco = ctx.find_object(GlobalContextObject)
        if gco:
            kwargs["debug"] = gco.debug
        ctx.obj = self.device_class(*args, **kwargs)

    def command_callback(self, miio_command, miio_device, *args, **kwargs):
        return miio_command.call(miio_device, *args, **kwargs)

    def get_command(self, ctx, cmd_name):
        if cmd_name not in self.commands:
            ctx.fail("Unknown command (%s)" % cmd_name)

        cmd = self.commands[cmd_name]
        return self.commands[cmd_name].wrap(
            ctx, self.device_pass(partial(self.command_callback, cmd))
        )

    def list_commands(self, ctx):
        return sorted(self.commands.keys())


def command(*decorators, name=None, default_output=None, **kwargs):
    return DeviceGroup.Command(
        name, decorators, default_output=default_output, **kwargs
    )


def format_output(
    msg_fmt: Union[str, Callable] = "",
    result_msg_fmt: Union[str, Callable] = "{result}",
):
    def decorator(func):
        @wraps(func)
        def wrap(*args, **kwargs):
            if msg_fmt:
                if callable(msg_fmt):
                    msg = msg_fmt(**kwargs)
                else:
                    msg = msg_fmt.format(**kwargs)
                if msg:
                    click.echo(msg.strip())
            kwargs["result"] = func(*args, **kwargs)
            if result_msg_fmt:
                if callable(result_msg_fmt):
                    result_msg = result_msg_fmt(**kwargs)
                else:
                    result_msg = result_msg_fmt.format(**kwargs)
                if result_msg:
                    click.echo(result_msg.strip())

        return wrap

    return decorator


def json_output(pretty=False):
    indent = 2 if pretty else None

    def decorator(func):
        @wraps(func)
        def wrap(*args, **kwargs):
            try:
                result = func(*args, **kwargs)
            except DeviceError as ex:
                click.echo(json.dumps(ex.args[0], indent=indent))
                return

            get_json_data_func = getattr(result, "__json__", None)
            data_variable = getattr(result, "data", None)
            if get_json_data_func is not None:
                result = get_json_data_func()
            elif data_variable is not None:
                result = data_variable
            click.echo(json.dumps(result, indent=indent))

        return wrap

    return decorator