Debian Codegraph @

cloup/_option_groups.py

raw
1 """
2 Implements the "option groups" feature.
3 """
4 from collections import defaultdict
5 from typing import (
6 Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple, overload,
7 )
8
9 import click
10 from click import Option, Parameter
11
12 import cloup
13 from cloup._params import option, make_arg_metavar
14 from cloup._util import first_bool, make_repr
15 from cloup.constraints import Constraint
16 from cloup.formatting import HelpSection, ensure_is_cloup_formatter
17 from cloup.typing import Decorator, F
18
19
20 class OptionGroup:
21 def __init__(self, title: str,
22 help: Optional[str] = None,
23 constraint: Optional[Constraint] = None,
24 hidden: bool = False):
25 """Contains the information of an option group and identifies it.
26 Note that, as far as the clients of this library are concerned, an
27 ``OptionGroups`` acts as a "marker" for options, not as a container for
28 related options. When you call ``@optgroup.option(...)`` you are not
29 adding an option to a container, you are just adding an option marked
30 with this option group.
31
32 .. versionadded:: 0.8.0
33 The ``hidden`` parameter.
34 """
35 if not title:
36 raise ValueError('name is a mandatory argument') # pragma: no cover
37 self.title = title
38 self.help = help
39 self._options: Sequence[click.Option] = []
40 self.constraint = constraint
41 self.hidden = hidden
42
43 @property
44 def options(self) -> Sequence[click.Option]:
45 return self._options
46
47 @options.setter
48 def options(self, options: Iterable[click.Option]) -> None:
49 self._options = opts = tuple(options)
50 if self.hidden:
51 for opt in opts:
52 opt.hidden = True
53 elif all(opt.hidden for opt in opts):
54 self.hidden = True
55
56 def get_help_records(self, ctx: click.Context) -> List[Tuple[str, str]]:
57 if self.hidden:
58 return []
59 return [
60 opt.get_help_record(ctx) for opt in self if not opt.hidden # type: ignore
61 ] # get_help_record() should return None only if opt.hidden
62
63 def option(self, *param_decls: str, **attrs: Any) -> Callable[[F], F]:
64 """Refer to :func:`cloup.option`."""
65 return option(*param_decls, group=self, **attrs)
66
67 def __iter__(self) -> Iterator[click.Option]:
68 return iter(self.options)
69
70 def __getitem__(self, i: int) -> click.Option:
71 return self.options[i]
72
73 def __len__(self) -> int:
74 return len(self.options)
75
76 def __repr__(self) -> str:
77 return make_repr(self, self.title, help=self.help, options=self.options)
78
79 def __str__(self) -> str:
80 return make_repr(
81 self, self.title, options=[opt.name for opt in self.options])
82
83
84 def has_option_group(param: click.Parameter) -> bool:
85 return getattr(param, 'group', None) is not None
86
87
88 def get_option_group_of(param: click.Option) -> Optional[OptionGroup]:
89 return getattr(param, 'group', None)
90
91
92 # noinspection PyMethodMayBeStatic
93 class OptionGroupMixin:
94 """Implements support for:
95
96 - option groups
97 - the "Positional arguments" help section; this section is shown only if
98 at least one of your arguments has non-empty ``help``.
99
100 .. important::
101 In order to check the constraints defined on the option groups,
102 a command must inherits from :class:`cloup.ConstraintMixin` too!
103
104 .. versionadded:: 0.14.0
105 added the "Positional arguments" help section.
106
107 .. versionchanged:: 0.8.0
108 this mixin now relies on ``cloup.HelpFormatter`` to align help sections.
109 If a ``click.HelpFormatter`` is used with a ``TypeError`` is raised.
110
111 .. versionchanged:: 0.8.0
112 removed ``format_option_group``. Added ``get_default_option_group`` and
113 ``make_option_group_help_section``.
114
115 .. versionadded:: 0.5.0
116 """
117
118 def __init__(
119 self, *args: Any, align_option_groups: Optional[bool] = None, **kwargs: Any
120 ) -> None:
121 """
122 :param align_option_groups:
123 whether to align the columns of all option groups' help sections.
124 This is also available as a context setting having a lower priority
125 than this attribute. Given that this setting should be consistent
126 across all you commands, you should probably use the context
127 setting only.
128 :param args:
129 positional arguments forwarded to the next class in the MRO
130 :param kwargs:
131 keyword arguments forwarded to the next class in the MRO
132 """
133 super().__init__(*args, **kwargs)
134
135 self.align_option_groups = align_option_groups
136 params = kwargs.get('params') or []
137 arguments, option_groups, ungrouped_options = self._group_params(params)
138
139 self.arguments = arguments
140
141 self.option_groups = option_groups
142 """List of all option groups, except the "default option group"."""
143
144 self.ungrouped_options = ungrouped_options
145 """List of options not explicitly assigned to an user-defined option group.
146 These options will be included in the "default option group".
147 **Note:** this list does not include options added automatically by Click
148 based on context settings, like the ``--help`` option; use the
149 :meth:`get_ungrouped_options` method if you need the real full list
150 (which needs a ``Context`` object)."""
151
152 @staticmethod
153 def _group_params(
154 params: List[Parameter]
155 ) -> Tuple[List[click.Argument], List[OptionGroup], List[Option]]:
156
157 options_by_group: Dict[OptionGroup, List[click.Option]] = defaultdict(list)
158 arguments: List[click.Argument] = []
159 ungrouped_options: List[click.Option] = []
160 for param in params:
161 if isinstance(param, click.Argument):
162 arguments.append(param)
163 elif isinstance(param, click.Option):
164 grp = get_option_group_of(param)
165 if grp is None:
166 ungrouped_options.append(param)
167 else:
168 options_by_group[grp].append(param)
169
170 option_groups = list(options_by_group.keys())
171 for group, options in options_by_group.items():
172 group.options = options
173
174 return arguments, option_groups, ungrouped_options
175
176 def get_ungrouped_options(self, ctx: click.Context) -> Sequence[click.Option]:
177 """Return options not explicitly assigned to an option group
178 (eventually including the ``--help`` option), i.e. options that will be
179 part of the "default option group"."""
180 help_option = ctx.command.get_help_option(ctx)
181 if help_option is not None:
182 return self.ungrouped_options + [help_option]
183 else:
184 return self.ungrouped_options
185
186 def get_argument_help_record(
187 self, arg: click.Argument, ctx: click.Context
188 ) -> Tuple[str, str]:
189 if isinstance(arg, cloup.Argument):
190 return arg.get_help_record(ctx)
191 return make_arg_metavar(arg, ctx), ""
192
193 def get_arguments_help_section(self, ctx: click.Context) -> Optional[HelpSection]:
194 args_with_help = (arg for arg in self.arguments if getattr(arg, "help", None))
195 if not any(args_with_help):
196 return None
197 return HelpSection(
198 heading="Positional arguments",
199 definitions=[
200 self.get_argument_help_record(arg, ctx) for arg in self.arguments
201 ],
202 )
203
204 def make_option_group_help_section(
205 self, group: OptionGroup, ctx: click.Context
206 ) -> HelpSection:
207 """Return a ``HelpSection`` for an ``OptionGroup``, i.e. an object containing
208 the title, the optional description and the options' definitions for
209 this option group.
210
211 .. versionadded:: 0.8.0
212 """
213 return HelpSection(
214 heading=group.title,
215 definitions=group.get_help_records(ctx),
216 help=group.help,
217 constraint=group.constraint.help(ctx) if group.constraint else None
218 )
219
220 def must_align_option_groups(
221 self, ctx: Optional[click.Context], default: bool = True
222 ) -> bool:
223 """
224 Return ``True`` if the help sections of all options groups should have
225 their columns aligned.
226
227 .. versionadded:: 0.8.0
228 """
229 return first_bool(
230 self.align_option_groups,
231 getattr(ctx, 'align_option_groups', None),
232 default,
233 )
234
235 def get_default_option_group(
236 self, ctx: click.Context, is_the_only_visible_option_group: bool = False
237 ) -> OptionGroup:
238 """
239 Return an ``OptionGroup`` instance for the options not explicitly
240 assigned to an option group, eventually including the ``--help`` option.
241
242 .. versionadded:: 0.8.0
243 """
244 default_group = OptionGroup(
245 "Options" if is_the_only_visible_option_group else "Other options")
246 default_group.options = self.get_ungrouped_options(ctx)
247 return default_group
248
249 def format_params(
250 self, ctx: click.Context, formatter: click.HelpFormatter
251 ) -> None:
252 formatter = ensure_is_cloup_formatter(formatter)
253
254 visible_sections = []
255
256 # Positional arguments
257 positional_arguments_section = self.get_arguments_help_section(ctx)
258 if positional_arguments_section:
259 visible_sections.append(positional_arguments_section)
260
261 # Option groups
262 option_group_sections = [
263 self.make_option_group_help_section(group, ctx)
264 for group in self.option_groups
265 if not group.hidden
266 ]
267 default_group = self.get_default_option_group(
268 ctx, is_the_only_visible_option_group=not option_group_sections
269 )
270 if not default_group.hidden:
271 option_group_sections.append(
272 self.make_option_group_help_section(default_group, ctx))
273
274 visible_sections += option_group_sections
275
276 formatter.write_many_sections(
277 visible_sections,
278 aligned=self.must_align_option_groups(ctx),
279 )
280
281
282 @overload
283 def option_group(
284 title: str,
285 help: str,
286 *options: Decorator,
287 constraint: Optional[Constraint] = None,
288 hidden: bool = False,
289 ) -> Callable[[F], F]:
290 ...
291
292
293 @overload
294 def option_group(
295 title: str,
296 *options: Decorator,
297 help: Optional[str] = None,
298 constraint: Optional[Constraint] = None,
299 hidden: bool = False,
300 ) -> Callable[[F], F]:
301 ...
302
303
304 # noinspection PyIncorrectDocstring
305 def option_group(title: str, *args: Any, **kwargs: Any) -> Callable[[F], F]:
306 """
307 Return a decorator that annotates a function with an option group.
308
309 The ``help`` argument is an optional description and can be provided either
310 as keyword argument or as 2nd positional argument after the ``name`` of
311 the group::
312
313 # help as keyword argument
314 @option_group(name, *options, help=None, ...)
315
316 # help as 2nd positional argument
317 @option_group(name, help, *options, ...)
318
319 .. versionchanged:: 0.9.0
320 in order to support the decorator :func:`cloup.constrained_params`,
321 ``@option_group`` now allows each input decorators to add multiple
322 options.
323
324 :param title:
325 title of the help section describing the option group.
326 :param help:
327 an optional description shown below the name; can be provided as keyword
328 argument or 2nd positional argument.
329 :param options:
330 an arbitrary number of decorators like ``click.option``, which attach
331 one or multiple options to the decorated command function.
332 :param constraint:
333 an optional instance of :class:`~cloup.constraints.Constraint`
334 (see :doc:`Constraints </pages/constraints>` for more info);
335 a description of the constraint will be shown between squared brackets
336 aside the option group title (or below it if too long).
337 :param hidden:
338 if ``True``, the option group and all its options are hidden from the help page
339 (all contained options will have their ``hidden`` attribute set to ``True``).
340 """
341 if args and isinstance(args[0], str):
342 return _option_group(title, options=args[1:], help=args[0], **kwargs)
343 else:
344 return _option_group(title, options=args, **kwargs)
345
346
347 def _option_group(
348 title: str,
349 options: Sequence[Callable[[F], F]],
350 help: Optional[str] = None,
351 constraint: Optional[Constraint] = None,
352 hidden: bool = False,
353 ) -> Callable[[F], F]:
354 if not isinstance(title, str):
355 raise TypeError(
356 'the first argument of `@option_group` must be its title, a string; '
357 'you probably forgot it'
358 )
359
360 if not options:
361 raise ValueError('you must provide at least one option')
362
363 def decorator(f: F) -> F:
364 opt_group = OptionGroup(title, help=help, constraint=constraint, hidden=hidden)
365 if not hasattr(f, '__click_params__'):
366 f.__click_params__ = [] # type: ignore
367 cli_params = f.__click_params__ # type: ignore
368 for add_option in reversed(options):
369 prev_len = len(cli_params)
370 add_option(f)
371 added_options = cli_params[prev_len:]
372 for new_option in added_options:
373 if not isinstance(new_option, Option):
374 raise TypeError(
375 "only parameter of type `Option` can be added to option groups")
376 existing_group = get_option_group_of(new_option)
377 if existing_group is not None:
378 raise ValueError(
379 f'Option "{new_option}" was first assigned to group '
380 f'"{existing_group}" and then passed as argument to '
381 f'`@option_group({title!r}, ...)`'
382 )
383 new_option.group = opt_group # type: ignore
384 if hidden:
385 new_option.hidden = True
386 return f
387
388 return decorator