File: _core.py

package info (click to toggle)
python-click-option-group 0.5.6-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 252 kB
  • sloc: python: 1,141; makefile: 16
file content (420 lines) | stat: -rw-r--r-- 14,130 bytes parent folder | download
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# -*- coding: utf-8 -*-

import collections
import inspect
import weakref
from typing import (
    Any,
    Callable,
    Dict,
    List,
    Mapping,
    Optional,
    Sequence,
    Set,
    Tuple,
    Union,
)

import click
from click.core import augment_usage_errors

from ._helpers import (
    get_callback_and_params,
    get_fake_option_name,
    raise_mixing_decorators_error,
    resolve_wrappers
)

FC = Union[Callable, click.Command]


class GroupedOption(click.Option):
    """Represents grouped (related) optional values

    The class should be used only with `OptionGroup` class for creating grouped options.

    :param param_decls: option declaration tuple
    :param group: `OptionGroup` instance (the group for this option)
    :param attrs: additional option attributes
    """

    def __init__(self, param_decls: Optional[Sequence[str]] = None, *, group: 'OptionGroup', **attrs: Any):
        super().__init__(param_decls, **attrs)

        for attr in group.forbidden_option_attrs:
            if attr in attrs:
                raise TypeError(
                    f"'{attr}' attribute is not allowed for '{type(group).__name__}' option `{self.name}'.")

        self.__group = group

    @property
    def group(self) -> 'OptionGroup':
        """Returns the reference to the group for this option

        :return: `OptionGroup` the group instance for this option
        """
        return self.__group

    def handle_parse_result(
            self, ctx: click.Context, opts: Mapping[str, Any], args: List[str]
    ) -> Tuple[Any, List[str]]:
        with augment_usage_errors(ctx, param=self):
            if not ctx.resilient_parsing:
                self.group.handle_parse_result(self, ctx, opts)
        return super().handle_parse_result(ctx, opts, args)

    def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:
        help_record = super().get_help_record(ctx)
        if help_record is None:
            # this happens if the option is hidden
            return help_record

        opts, opt_help = help_record

        formatter = ctx.make_formatter()
        with formatter.indentation():
            indent = ' ' * formatter.current_indent
            return f'{indent}{opts}', opt_help


class _GroupTitleFakeOption(click.Option):
    """The helper `Option` class to display option group title in help
    """

    def __init__(
        self, param_decls: Optional[Sequence[str]] = None, *, group: 'OptionGroup', **attrs: Any
    ) -> None:
        self.__group = group
        super().__init__(param_decls, hidden=True, expose_value=False, help=group.help, **attrs)

        # We remove parsed opts for the fake options just in case.
        # For example it is workaround for correct click-repl autocomplete
        self.opts = []
        self.secondary_opts = []

    def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:
        return self.__group.get_help_record(ctx)


class OptionGroup:
    """Option group manages grouped (related) options

    The class is used for creating the groups of options. The class can de used as based class to implement
    specific behavior for grouped options.

    :param name: the group name. If it is not set the default group name will be used
    :param help: the group help text or None
    """

    def __init__(
        self, name: Optional[str] = None, *, hidden: bool = False, help: Optional[str] = None
    ) -> None:
        self._name = name if name else ''
        self._help = inspect.cleandoc(help if help else '')
        self._hidden = hidden

        self._options: Mapping[Any, Any] = collections.defaultdict(weakref.WeakValueDictionary)
        self._group_title_options = weakref.WeakValueDictionary()

    @property
    def name(self) -> str:
        """Returns the group name or empty string if it was not set

        :return: group name
        """
        return self._name

    @property
    def help(self) -> str:
        """Returns the group help or empty string if it was not set

        :return: group help
        """
        return self._help

    @property
    def name_extra(self) -> List[str]:
        """Returns extra name attributes for the group
        """
        return []

    @property
    def forbidden_option_attrs(self) -> List[str]:
        """Returns the list of forbidden option attributes for the group
        """
        return []

    def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:
        """Returns the help record for the group

        :param ctx: Click Context object
        :return: the tuple of two fileds: `(name, help)`
        """
        if all(o.hidden for o in self.get_options(ctx).values()):
            return None

        name = self.name
        help_ = self.help if self.help else ''

        extra = ', '.join(self.name_extra)
        if extra:
            extra = f'[{extra}]'

        if name:
            name = f'{name}: {extra}'
        elif extra:
            name = f'{extra}:'

        if not name and not help_:
            return None

        return name, help_

    def option(self, *param_decls: str, **attrs: Any) -> Callable:
        """Decorator attaches a grouped option to the command

        The decorator is used for adding options to the group and to the Click-command
        """

        def decorator(func: FC) -> FC:
            option_attrs = attrs.copy()
            option_attrs.setdefault('cls', GroupedOption)
            if self._hidden:
                option_attrs.setdefault('hidden', self._hidden)

            if not issubclass(option_attrs['cls'], GroupedOption):
                raise TypeError("'cls' argument must be a subclass of 'GroupedOption' class.")

            self._check_mixing_decorators(func)
            func = click.option(*param_decls, group=self, **option_attrs)(func)
            self._option_memo(func)

            # Add the fake invisible option to use for print nice title help for grouped options
            self._add_title_fake_option(func)

            return func

        return decorator

    def get_options(self, ctx: click.Context) -> Dict[str, GroupedOption]:
        """Returns the dictionary with group options
        """
        return self._options.get(resolve_wrappers(ctx.command.callback), {})

    def get_option_names(self, ctx: click.Context) -> List[str]:
        """Returns the list with option names ordered by addition in the group
        """
        return list(reversed(list(self.get_options(ctx))))

    def get_error_hint(self, ctx: click.Context, option_names: Optional[Set[str]] = None) -> str:
        options = self.get_options(ctx)
        text = ''

        for name, opt in reversed(list(options.items())):
            if option_names and name not in option_names:
                continue
            text += f'  {opt.get_error_hint(ctx)}\n'

        if text:
            text = text[:-1]

        return text

    def handle_parse_result(self, option: GroupedOption, ctx: click.Context, opts: Mapping[str, Any]) -> None:
        """The method should be used for adding specific behavior and relation for options in the group
        """

    def _check_mixing_decorators(self, func: Callable) -> None:
        func, params = get_callback_and_params(func)

        if not params or func not in self._options:
            return

        last_param = params[-1]
        title_option = self._group_title_options[func]
        options = self._options[func]

        if last_param.name != title_option.name and last_param.name not in options:
            raise_mixing_decorators_error(last_param, func)

    def _add_title_fake_option(self, func: FC) -> None:
        callback, params = get_callback_and_params(func)

        if callback not in self._group_title_options:
            func = click.option(get_fake_option_name(),
                                group=self, cls=_GroupTitleFakeOption)(func)

            _, params = get_callback_and_params(func)
            self._group_title_options[callback] = params[-1]

        title_option = self._group_title_options[callback]
        last_option = params[-1]

        if title_option.name != last_option.name:
            # Hold title fake option on the top of the option group
            title_index = params.index(title_option)
            params[-1], params[title_index] = params[title_index], params[-1]

    def _option_memo(self, func: Callable) -> None:
        func, params = get_callback_and_params(func)
        option = params[-1]
        self._options[func][option.name] = option

    def _group_name_str(self) -> str:
        return f"'{self.name}'" if self.name else "the"


class RequiredAnyOptionGroup(OptionGroup):
    """Option group with required any options of this group

    `RequiredAnyOptionGroup` defines the behavior: At least one option from the group must be set.
    """

    @property
    def forbidden_option_attrs(self) -> List[str]:
        return ['required']

    @property
    def name_extra(self) -> List[str]:
        return super().name_extra + ['required_any']

    def handle_parse_result(self, option: GroupedOption, ctx: click.Context, opts: Mapping[str, Any]) -> None:
        if option.name in opts:
            return

        if all(o.hidden for o in self.get_options(ctx).values()):
            cls_name = self.__class__.__name__
            group_name = self._group_name_str()

            raise TypeError(
                f"Need at least one non-hidden option in {group_name} option group ({cls_name})."
            )

        option_names = set(self.get_options(ctx))

        if not option_names.intersection(opts):
            group_name = self._group_name_str()
            option_info = self.get_error_hint(ctx)

            raise click.UsageError(
                f"At least one of the following options from {group_name} option group is required:\n{option_info}",
                ctx=ctx
            )


class RequiredAllOptionGroup(OptionGroup):
    """Option group with required all options of this group

    `RequiredAllOptionGroup` defines the behavior: All options from the group must be set.
    """

    @property
    def forbidden_option_attrs(self) -> List[str]:
        return ['required', 'hidden']

    @property
    def name_extra(self) -> List[str]:
        return super().name_extra + ['required_all']

    def handle_parse_result(self, option: GroupedOption, ctx: click.Context, opts: Mapping[str, Any]) -> None:
        option_names = set(self.get_options(ctx))

        if not option_names.issubset(opts):
            group_name = self._group_name_str()
            required_names = option_names.difference(option_names.intersection(opts))
            option_info = self.get_error_hint(ctx, required_names)

            raise click.UsageError(
                f"Missing required options from {group_name} option group:\n{option_info}",
                ctx=ctx
            )


class MutuallyExclusiveOptionGroup(OptionGroup):
    """Option group with mutually exclusive behavior for grouped options

    `MutuallyExclusiveOptionGroup` defines the behavior:
        - Only one or none option from the group must be set
    """

    @property
    def forbidden_option_attrs(self) -> List[str]:
        return ['required']

    @property
    def name_extra(self) -> List[str]:
        return super().name_extra + ['mutually_exclusive']

    def handle_parse_result(self, option: GroupedOption, ctx: click.Context, opts: Mapping[str, Any]) -> None:
        option_names = set(self.get_options(ctx))
        given_option_names = option_names.intersection(opts)
        given_option_count = len(given_option_names)

        if given_option_count > 1:
            group_name = self._group_name_str()
            option_info = self.get_error_hint(ctx, given_option_names)

            raise click.UsageError(
                f"Mutually exclusive options from {group_name} option group "
                f"cannot be used at the same time:\n{option_info}",
                ctx=ctx
            )


class RequiredMutuallyExclusiveOptionGroup(MutuallyExclusiveOptionGroup):
    """Option group with required and mutually exclusive behavior for grouped options

    `RequiredMutuallyExclusiveOptionGroup` defines the behavior:
        - Only one required option from the group must be set
    """

    @property
    def name_extra(self) -> List[str]:
        return super().name_extra + ['required']

    def handle_parse_result(self, option: GroupedOption, ctx: click.Context, opts: Mapping[str, Any]) -> None:
        super().handle_parse_result(option, ctx, opts)

        option_names = set(self.get_option_names(ctx))
        given_option_names = option_names.intersection(opts)

        if len(given_option_names) == 0:
            group_name = self._group_name_str()
            option_info = self.get_error_hint(ctx)

            raise click.UsageError(
                "Missing one of the required mutually exclusive options from "
                f"{group_name} option group:\n{option_info}",
                ctx=ctx
            )


class AllOptionGroup(OptionGroup):
    """Option group with required all/none options of this group

    `AllOptionGroup` defines the behavior:
        - All options from the group must be set or None must be set
    """

    @property
    def forbidden_option_attrs(self) -> List[str]:
        return ['required', 'hidden']

    @property
    def name_extra(self) -> List[str]:
        return super().name_extra + ['all_or_none']

    def handle_parse_result(self, option: GroupedOption, ctx: click.Context, opts: Mapping[str, Any]) -> None:
        option_names = set(self.get_options(ctx))

        if not option_names.isdisjoint(opts) and option_names.intersection(opts) != option_names:
            group_name = self._group_name_str()
            option_info = self.get_error_hint(ctx)

            raise click.UsageError(
                f"All options from {group_name} option group should be specified or none should be specified. "
                f"Missing required options:\n{option_info}",
                ctx=ctx
            )