aboutsummaryrefslogtreecommitdiff
path: root/pw_rpc/py/pw_rpc/console_tools/console.py
blob: 361ed7a4daab4710449a2c3bbf53aadf0b7dce26 (plain)
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# Copyright 2021 The Pigweed Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""Utilities for creating an interactive console."""

from collections import defaultdict
import functools
from itertools import chain
import inspect
import textwrap
import types
from typing import (
    Any,
    Collection,
    Dict,
    Iterable,
    Mapping,
    NamedTuple,
    Optional,
)

import pw_status
from pw_protobuf_compiler import python_protos

import pw_rpc
from pw_rpc.descriptors import Method
from pw_rpc.console_tools import functions

_INDENT = '    '


class CommandHelper:
    """Used to implement a help command in an RPC console."""

    @classmethod
    def from_methods(
        cls,
        methods: Iterable[Method],
        variables: Mapping[str, object],
        header: str,
        footer: str = '',
    ) -> 'CommandHelper':
        return cls({m.full_name: m for m in methods}, variables, header, footer)

    def __init__(
        self,
        methods: Mapping[str, object],
        variables: Mapping[str, object],
        header: str,
        footer: str = '',
    ):
        self._methods = methods
        self._variables = variables
        self.header = header
        self.footer = footer

    def help(self, item: object = None) -> str:
        """Returns a help string with a command or all commands listed."""

        if item is None:
            all_vars = '\n'.join(sorted(self._variables_without_methods()))
            all_rpcs = '\n'.join(self._methods)
            return (
                f'{self.header}\n\n'
                f'All variables:\n\n{textwrap.indent(all_vars, _INDENT)}'
                '\n\n'
                f'All commands:\n\n{textwrap.indent(all_rpcs, _INDENT)}'
                f'\n\n{self.footer}'.strip()
            )

        # If item is a string, find commands matching that.
        if isinstance(item, str):
            matches = {n: m for n, m in self._methods.items() if item in n}
            if not matches:
                return f'No matches found for {item!r}'

            if len(matches) == 1:
                name, method = next(iter(matches.items()))
                return f'{name}\n\n{inspect.getdoc(method)}'

            return f'Multiple matches for {item!r}:\n\n' + textwrap.indent(
                '\n'.join(matches), _INDENT
            )

        return inspect.getdoc(item) or f'No documentation for {item!r}.'

    def _variables_without_methods(self) -> Mapping[str, object]:
        packages = frozenset(
            n.split('.', 1)[0] for n in self._methods if '.' in n
        )

        return {
            name: var
            for name, var in self._variables.items()
            if name not in packages
        }

    def __call__(self, item: object = None) -> None:
        """Prints the help string."""
        print(self.help(item))

    def __repr__(self) -> str:
        """Returns the help, so foo and foo() are equivalent in a console."""
        return self.help()


class ClientInfo(NamedTuple):
    """Information about an RPC client as it appears in the console."""

    # The name to use in the console to refer to this client.
    name: str

    # An object to use in the console for the client. May be a pw_rpc.Client.
    client: object

    # The pw_rpc.Client; may be the same object as client.
    rpc_client: pw_rpc.Client


def flattened_rpc_completions(
    client_info_list: Collection[ClientInfo],
) -> Dict[str, str]:
    """Create a flattened list of rpc commands for repl auto-completion.

    This gathers all rpc commands from a set of ClientInfo variables and
    produces a flattened list of valid rpc commands to run in an RPC
    console. This is useful for passing into
    prompt_toolkit.completion.WordCompleter.

    Args:
      client_info_list: List of ClientInfo variables

    Returns:
      Dict of flattened rpc commands as keys, and 'RPC' as values.
      For example: ::

        {
            'device.rpcs.pw.rpc.EchoService.Echo': 'RPC,
            'device.rpcs.pw.rpc.BatteryService.GetBatteryStatus': 'RPC',
        }
    """
    rpc_list = list(
        chain.from_iterable(
            [
                '{}.rpcs.{}'.format(c.name, a.full_name)
                for a in c.rpc_client.methods()
            ]
            for c in client_info_list
        )
    )

    # Dict should contain completion text as keys and descriptions as values.
    custom_word_completions = {
        flattened_rpc_name: 'RPC' for flattened_rpc_name in rpc_list
    }
    return custom_word_completions


class Context:
    """The Context class is used to set up an interactive RPC console.

    The Context manages a set of variables that make it easy to access RPCs and
    protobufs in a REPL.

    As an example, this class can be used to set up a console with IPython:

    .. code-block:: python

       context = console_tools.Context(
           clients, default_client, protos, help_header=WELCOME_MESSAGE)
       IPython.start_ipython(argv=[], user_ns=dict(**context.variables()))
    """

    def __init__(
        self,
        client_info: Collection[ClientInfo],
        default_client: Any,
        protos: python_protos.Library,
        *,
        help_header: str = '',
    ) -> None:
        """Creates an RPC console context.

        Protos and RPC services are accessible by their proto package and name.
        The target for these can be set with the set_target function.

        Args:
          client_info: ClientInfo objects that represent the clients this
              console uses to communicate with other devices
          default_client: default client object; must be one of the clients
          protos: protobufs to use for RPCs for all clients
          help_header: Message to display for the help command
        """
        assert client_info, 'At least one client must be provided!'

        self.client_info = client_info
        self.current_client = default_client
        self.protos = protos

        # Store objects with references to RPC services, sorted by package.
        self._services: Dict[str, types.SimpleNamespace] = defaultdict(
            types.SimpleNamespace
        )

        self._variables: Dict[str, object] = dict(
            Status=pw_status.Status,
            set_target=functions.help_as_repr(self.set_target),
            # The original built-in help function is available as 'python_help'.
            python_help=help,
        )

        # Make the RPC clients and protos available in the console.
        self._variables.update((c.name, c.client) for c in self.client_info)

        # Make the proto package hierarchy directly available in the console.
        for package in self.protos.packages:
            self._variables[
                package._package
            ] = package  # pylint: disable=protected-access

        # Monkey patch the message types to use an improved repr function.
        for message_type in self.protos.messages():
            message_type.__repr__ = python_protos.proto_repr

        # Set up the 'help' command.
        all_methods = chain.from_iterable(
            c.rpc_client.methods() for c in self.client_info
        )
        self._helper = CommandHelper.from_methods(
            all_methods,
            self._variables,
            help_header,
            'Type a command and hit Enter to see detailed help information.',
        )

        self._variables['help'] = self._helper

        # Call set_target to set up for the default target.
        self.set_target(self.current_client)

    def flattened_rpc_completions(self):
        """Create a flattened list of rpc commands for repl auto-completion."""
        return flattened_rpc_completions(self.client_info)

    def variables(self) -> Dict[str, Any]:
        """Returns a mapping of names to variables for use in an RPC console."""
        return self._variables

    def set_target(
        self, selected_client: object, channel_id: Optional[int] = None
    ) -> None:
        """Sets the default target for commands."""
        # Make sure the variable is one of the client variables.
        name = ''
        rpc_client: Any = None

        for name, client, rpc_client in self.client_info:
            if selected_client is client:
                print('CURRENT RPC TARGET:', name)
                break
        else:
            raise ValueError(
                'Supported targets :'
                + ', '.join(c.name for c in self.client_info)
            )

        # Update the RPC services to use the newly selected target.
        for service_client in rpc_client.channel(channel_id).rpcs:
            # Patch all method protos to use the improved __repr__ function too.
            for method in (m.method for m in service_client):
                method.request_type.__repr__ = python_protos.proto_repr
                method.response_type.__repr__ = python_protos.proto_repr

            service = (
                service_client._service  # pylint: disable=protected-access
            )
            setattr(
                self._services[service.package], service.name, service_client
            )

        # Add the RPC methods to their proto packages.
        for package_name, rpcs in self._services.items():
            # pylint: disable=protected-access
            self.protos.packages[package_name]._add_item(rpcs)
            # pylint: enable=protected-access

        self.current_client = selected_client


def _create_command_alias(command: Any, name: str, message: str) -> object:
    """Wraps __call__, __getattr__, and __repr__ to print a message."""

    @functools.wraps(command.__call__)
    def print_message_and_call(_, *args, **kwargs):
        print(message)
        return command(*args, **kwargs)

    def getattr_and_print_message(_, name: str) -> Any:
        attr = getattr(command, name)
        print(message)
        return attr

    return type(
        name,
        (),
        dict(
            __call__=print_message_and_call,
            __getattr__=getattr_and_print_message,
            __repr__=lambda _: message,
        ),
    )()


def _access_in_dict_or_namespace(item, name: str, create_if_missing: bool):
    """Gets name as either a key or attribute on item."""
    try:
        return item[name]
    except KeyError:
        if create_if_missing:
            try:
                item[name] = types.SimpleNamespace()
                return item[name]
            except TypeError:
                pass
    except TypeError:
        pass

    if create_if_missing and not hasattr(item, name):
        setattr(item, name, types.SimpleNamespace())

    return getattr(item, name)


def _access_names(item, names: Iterable[str], create_if_missing: bool):
    for name in names:
        item = _access_in_dict_or_namespace(item, name, create_if_missing)

    return item


def alias_deprecated_command(
    variables: Any, old_name: str, new_name: str
) -> None:
    """Adds an alias for an old command that redirects to the new command.

    The deprecated command prints a message then invokes the new command.
    """
    # Get the new command.
    item = _access_names(
        variables, new_name.split('.'), create_if_missing=False
    )

    # Create a wrapper to the new comamnd with the old name.
    wrapper = _create_command_alias(
        item,
        old_name,
        f'WARNING: {old_name} is DEPRECATED; use {new_name} instead',
    )

    # Add the wrapper to the variables with the old command's name.
    name_parts = old_name.split('.')
    item = _access_names(variables, name_parts[:-1], create_if_missing=True)
    setattr(item, name_parts[-1], wrapper)