click_cli.py 9.13 KB
Newer Older
Mark Hewitt's avatar
Mark Hewitt committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#  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
#
#      http://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.

"""Entry or launch point for CLI.

Handles creating and launching a CLI to handle a user command."""

import collections
import functools
import json
import logging
from os import path

import click
24
25
from click.core import Context
from click.formatting import HelpFormatter
Mark Hewitt's avatar
Mark Hewitt committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

from osducli.config import CLI_ENV_VAR_PREFIX, CLIConfig
from osducli.log import get_logger
from osducli.state import get_default_config


class State:  # pylint: disable=too-few-public-methods
    """Global state passed to all click commands"""

    def __init__(self):
        self.debug = False
        self.config_path = None
        self.config = None
        self.output = None
        self.jmes = None

    def __repr__(self):
        return f"State=Debug: {self.debug}, Config path: {self.config_path}"

Mark Hewitt's avatar
Mark Hewitt committed
45
46
47
48
49
50
51
52
    def is_user_friendly_mode(self) -> bool:
        """Return whether we are running in a user friendly output mode

        Returns:
            bool: whether running in user friendly mode
        """
        return self.output is None

Mark Hewitt's avatar
Mark Hewitt committed
53

54
55
56
57
58
59
60
def _format_click_options(cmd: click.Command, ctx: Context, formatter: HelpFormatter) -> None:
    """Writes options into the formatter split between Options and Common Options."""
    opts = []
    common_opts = []
    for param in cmd.get_params(ctx):
        _rv = param.get_help_record(ctx)
        if _rv is not None:
Mark Hewitt's avatar
Mark Hewitt committed
61
            if param.name in ["help", "debug", "config", "output", "filter"]:
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
                common_opts.append(_rv)
            else:
                opts.append(_rv)

    if opts:
        with formatter.section("Options"):
            formatter.write_dl(opts)

    if common_opts:
        with formatter.section("Common Options"):
            formatter.write_dl(common_opts)


class CustomClickGroup(click.Group):
    """Custom click.Group class providing customised help text"""

    def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
        _format_click_options(self, ctx, formatter)
        self.format_commands(ctx, formatter)


class CustomClickCommand(click.Command):
    """Custom click.GrouCommand class providing customised help text"""

    def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:
        _format_click_options(self, ctx, formatter)


Mark Hewitt's avatar
Mark Hewitt committed
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
def global_params(func):
    """Handle global parameters setting to setup state and remove parameters from those passed
    to the decorated function call."""

    def debug_callback(ctx, _, value):
        state = ctx.ensure_object(State)
        state.debug = value
        logging.basicConfig()
        root_logger = logging.getLogger()
        root_logger.setLevel(logging.INFO)
        if value:
            root_logger = logging.getLogger()
            root_logger.setLevel(logging.DEBUG)
            logger = get_logger(__name__)
            # logger.setLevel(logging.DEBUG)
            # requests_log = logging.getLogger("urllib3")
            # requests_log.setLevel(logging.DEBUG)
            # requests_log.propagate = True
            logger.debug("Debugging enabled")
        return value

    def config_callback(ctx, _, value):
        state = ctx.ensure_object(State)
        state.config_path = value
        if value:
            config_path, config_file = path.split(value)
            state.config = CLIConfig(config_path, CLI_ENV_VAR_PREFIX, config_file)
        else:
            state.config = get_default_config(True)
        return value

    pass_state = click.make_pass_decorator(State)

    @click.option(
        "--debug/--no-debug",
        default=False,
        envvar="REPO_DEBUG",
        help="Increase logging verbosity to show all debug logs.",
        callback=debug_callback,
    )
    @click.option(
        "-c",
        "--config",
        envvar="OSDU_CONFIG",
        help="Path to a configuration file. You can configure the default file using 'osducli config default'.",
        type=click.Path(readable=True),
        callback=config_callback,
    )
    @functools.wraps(func)
    @pass_state
    def wrapper(*args, **kwargs):
        kwargs.pop("debug")
        kwargs.pop("config")
        return func(*args, **kwargs)

    return wrapper


def command_with_output(table_transformer=None):
    """Handle global parameters setting to setup state and remove parameters from those passed
    to the decorated function call."""

    def wrapper_for_params(func):
        def output_callback(ctx, _, value):
            state = ctx.ensure_object(State)
            state.output = value
            return value

        def jmes_callback(ctx, _, value):
            state = ctx.ensure_object(State)
            state.jmes = value
            return value

        @click.option(
            "-o",
            "--output",
            envvar="OSDU_CONFIG",
            type=click.Choice(["json"], case_sensitive=False),
            help="Output format (default is a user friendly table format).",
            callback=output_callback,
        )
        @click.option(
Mark Hewitt's avatar
Mark Hewitt committed
172
173
            "--filter",
            help="JMESPath string for filtering output. See http://jmespath.org/ for more information and examples.",
Mark Hewitt's avatar
Mark Hewitt committed
174
175
176
177
178
179
180
            callback=jmes_callback,
        )
        @functools.wraps(func)
        @global_params
        def func_wrapper(*args, **kwargs):
            state = args[0]
            kwargs.pop("output")
Mark Hewitt's avatar
Mark Hewitt committed
181
            kwargs.pop("filter")
Mark Hewitt's avatar
Mark Hewitt committed
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
            result = func(*args, **kwargs)
            if result is not None:
                if type(result) in [dict, list]:
                    if state.jmes is not None or (
                        table_transformer is not None and state.output is None
                    ):
                        jmes = state.jmes if state.jmes is not None else table_transformer
                        try:
                            from jmespath import Options
                            from jmespath import compile as compile_jmespath

                            query_expression = compile_jmespath(jmes)
                            result = query_expression.search(
                                result, Options(collections.OrderedDict)
                            )
                        except KeyError as ex:
                            # Raise a ValueError which argparse can handle
                            raise ValueError from ex

                    if state.output == "json":
                        print(json.dumps(result, indent=2))
                    else:
                        result_list = result if isinstance(result, list) else [result]
                        # should_sort_keys = not state.jmes
                        table_output = _TableOutput(False)  # should_sort_keys)
                        print(table_output.dump(result_list))

        return func_wrapper

    return wrapper_for_params


class _TableOutput:  # pylint: disable=too-few-public-methods

    SKIP_KEYS = []

    def __init__(self, should_sort_keys=False):
        self.should_sort_keys = should_sort_keys

    @staticmethod
    def _capitalize_first_char(text: str):
        return text[0].upper() + text[1:] if text else text

    def _auto_table_item(self, item):
        new_entry = collections.OrderedDict()
        try:
            keys = sorted(item) if self.should_sort_keys and isinstance(item, dict) else item.keys()
            for k in keys:
                if k in _TableOutput.SKIP_KEYS:
                    continue
                if item[k] is not None and not isinstance(item[k], (list, dict, set)):
                    new_entry[_TableOutput._capitalize_first_char(k)] = item[k]
        except AttributeError:
            # handles odd cases where a string/bool/etc. is returned
            if isinstance(item, list):
                for col, val in enumerate(item):
                    new_entry["Column{}".format(col + 1)] = val
            else:
                new_entry["Result"] = item
        return new_entry

    def _auto_table(self, result):
        if isinstance(result, list):
            new_result = []
            for item in result:
                new_result.append(self._auto_table_item(item))
            return new_result
        return self._auto_table_item(result)

    def dump(self, data):
        """Dump table data to a tabulated string

        Args:
            data ([type]): [description]

        Raises:
            ValueError: [description]

        Returns:
            [type]: [description]
        """
        from tabulate import tabulate

        table_data = self._auto_table(data)
        table_str = (
            tabulate(table_data, headers="keys", tablefmt="simple", disable_numparse=True)
            if table_data
            else ""
        )
        if table_str == "\n":
            raise ValueError("Unable to extract fields for table.")
        return table_str + "\n"