Debian Codegraph @

cloup/constraints/_core.py

raw
1 import abc
2 from typing import (
3 Any, Callable, Optional, Sequence, TypeVar, Union, cast, overload,
4 )
5
6 import click
7
8 from cloup._util import (
9 FrozenSpace, check_arg, class_name,
10 first_bool, make_one_line_repr, make_repr, pluralize, reindent,
11 )
12 from .common import (
13 format_param_list,
14 get_param_label,
15 get_param_name,
16 get_params_whose_value_is_set,
17 get_required_params,
18 param_value_is_set,
19 )
20 from .exceptions import ConstraintViolated, UnsatisfiableConstraint
21 from ..typing import Decorator, F
22
23 Op = TypeVar('Op', bound='Operator')
24 HelpRephraser = Callable[[click.Context, 'Constraint'], str]
25 ErrorRephraser = Callable[[ConstraintViolated], str]
26
27
28 class Constraint(abc.ABC):
29 """
30 A constraint that can be checked against an arbitrary collection of CLI
31 parameters with respect to a specific :class:`click.Context` (which
32 contains the values assigned to the parameters in ``ctx.params``).
33
34 .. versionchanged:: 0.9.0
35 calling a constraint, previously equivalent to :meth:`~Constraint.check`,
36 is now equivalent to calling :func:`cloup.constrained_params` with this
37 constraint as first argument.
38 """
39
40 @staticmethod
41 def must_check_consistency(ctx: click.Context) -> bool:
42 """Return ``True`` if consistency checks are enabled.
43
44 .. versionchanged:: 0.9.0
45 this method now a static method and takes a ``click.Context`` in input.
46 """
47 return first_bool(
48 getattr(ctx, 'check_constraints_consistency', True),
49 True,
50 )
51
52 def __getattr__(self, attr: str) -> Any:
53 removed_attrs = ('toggle_consistency_checks', 'consistency_checks_toggled')
54 if attr in removed_attrs:
55 raise AttributeError(
56 f'attribute `{attr}` was removed in v0.9. You can now enable/disable '
57 f'consistency checks using the `click.Context` parameter '
58 f'`check_constraints_consistency`. '
59 f'Pass it as part of your `context_settings`.'
60 )
61 else:
62 raise AttributeError(attr)
63
64 @abc.abstractmethod
65 def help(self, ctx: click.Context) -> str:
66 """A description of the constraint. """
67
68 def check_consistency(self, params: Sequence[click.Parameter]) -> None:
69 """
70 Perform some sanity checks that detect inconsistencies between these
71 constraints and the properties of the input parameters (e.g. required).
72
73 For example, a constraint that requires the parameters to be mutually
74 exclusive is not consistent with a group of parameters with multiple
75 required options.
76
77 These sanity checks are meant to catch developer's mistakes and don't
78 depend on the values assigned to the parameters; therefore:
79
80 - they can be performed before any parameter parsing
81 - they can be disabled in production (setting
82 ``check_constraints_consistency=False`` in ``context_settings``)
83
84 :param params: list of :class:`click.Parameter` instances
85 :raises: :exc:`~cloup.constraints.errors.UnsatisfiableConstraint`
86 if the constraint cannot be satisfied independently from the values
87 provided by the user
88 """
89
90 @abc.abstractmethod
91 def check_values(self, params: Sequence[click.Parameter], ctx: click.Context) -> None:
92 """
93 Check that the constraint is satisfied by the input parameters in the
94 given context, which (among other things) contains the values assigned
95 to the parameters in ``ctx.params``.
96
97 You probably don't want to call this method directly.
98 Use :meth:`check` instead.
99
100 :param params: list of :class:`click.Parameter` instances
101 :param ctx: :class:`click.Context`
102 :raises:
103 :exc:`~cloup.constraints.ConstraintViolated`
104 """
105
106 @overload
107 def check(
108 self, params: Sequence[click.Parameter], ctx: Optional[click.Context] = None
109 ) -> None:
110 ...
111
112 @overload
113 def check(self, params: Sequence[str], ctx: Optional[click.Context] = None) -> None:
114 ...
115
116 def check(
117 self, params: Union[Sequence[click.Parameter], Sequence[str]],
118 ctx: Optional[click.Context] = None
119 ) -> None:
120 """
121 Raise an exception if the constraint is not satisfied by the input
122 parameters in the given (or current) context.
123
124 This method calls both :meth:`check_consistency` (if enabled) and
125 :meth:`check_values`.
126
127 .. tip::
128 By default :meth:`check_consistency` is called since it shouldn't
129 have any performance impact. Nonetheless, you can disable it in
130 production passing ``check_constraints_consistency=False`` as part
131 of your ``context_settings``.
132
133 :param params: an iterable of parameter names or a sequence of
134 :class:`click.Parameter`
135 :param ctx: a `click.Context`; if not provided, :func:`click.get_current_context`
136 is used
137 :raises:
138 :exc:`~cloup.constraints.ConstraintViolated`
139 :exc:`~cloup.constraints.UnsatisfiableConstraint`
140 """
141 from ._support import ConstraintMixin
142
143 if not params:
144 raise ValueError("argument `params` can't be empty")
145
146 ctx = click.get_current_context() if ctx is None else ctx
147 if not isinstance(ctx.command, ConstraintMixin): # this is needed for mypy
148 raise TypeError('constraints work only if the command inherits from '
149 '`ConstraintMixin`')
150
151 if isinstance(params[0], str):
152 param_names = cast(Sequence[str], params)
153 params_objects = ctx.command.get_params_by_name(param_names)
154 else:
155 params_objects = cast(Sequence[click.Parameter], params)
156
157 if Constraint.must_check_consistency(ctx):
158 self.check_consistency(params_objects)
159 return self.check_values(params_objects, ctx)
160
161 def rephrased(
162 self,
163 help: Union[None, str, HelpRephraser] = None,
164 error: Union[None, str, ErrorRephraser] = None,
165 ) -> 'Rephraser':
166 """
167 Override the help string and/or the error message of this constraint
168 wrapping it with a :class:`Rephraser`.
169
170 :param help:
171 if provided, overrides the help string of this constraint. It can be
172 a string or a function ``(ctx: click.Context, constr: Constraint) -> str``.
173 If you want to hide this constraint from the help, pass ``help=""``.
174 :param error:
175 if provided, overrides the error message of this constraint.
176 It can be:
177
178 - a string, eventually a ``format`` string supporting the replacement
179 fields described in :class:`ErrorFmt`.
180
181 - or a function ``(err: ConstraintViolated) -> str``; note that
182 a :class:`ConstraintViolated` error has fields for ``ctx``,
183 ``constraint`` and ``params``, so it's a complete description
184 of what happened.
185 """
186 return Rephraser(self, help=help, error=error)
187
188 def hidden(self) -> 'Rephraser':
189 """Hide this constraint from the command help."""
190 return Rephraser(self, help='')
191
192 def __call__(self, *param_adders: Decorator) -> Callable[[F], F]:
193 """Equivalent to calling :func:`cloup.constrained_params` with this
194 constraint as first argument.
195
196 .. versionchanged:: 0.9.0
197 this method, previously equivalent to :meth:`~Constraint.check`, is
198 now equivalent to calling :func:`cloup.constrained_params` with this
199 constraint as first argument.
200 """
201 from ._support import constrained_params
202 # TODO: remove this check in the future
203 if not callable(param_adders[0]):
204 from cloup import __version__
205 raise TypeError(reindent(f"""\n
206 since Cloup v0.9, calling a constraint has a completely different
207 semantics and takes parameter decorators as arguments, see:
208
209 https://cloup.readthedocs.io/en/v{__version__}/pages/constraints.html#constraints-as-decorators
210
211 To check a constraint imperatively, you can use the check() method.
212 """, 4))
213 return constrained_params(self, *param_adders)
214
215 def __or__(self, other: 'Constraint') -> 'Or':
216 return Or(self, other)
217
218 def __and__(self, other: 'Constraint') -> 'And':
219 return And(self, other)
220
221 def __repr__(self) -> str:
222 return f'{class_name(self)}()'
223
224
225 class Operator(Constraint, abc.ABC):
226 """Base class for all n-ary operators defined on constraints. """
227
228 HELP_SEP: str
229 """Used as separator of all constraints' help strings."""
230
231 def __init__(self, *constraints: Constraint):
232 """N-ary operator for constraints.
233 :param constraints: operands
234 """
235 self.constraints = constraints
236
237 def help(self, ctx: click.Context) -> str:
238 return self.HELP_SEP.join(
239 '(%s)' % c.help(ctx) if isinstance(c, Operator) else c.help(ctx)
240 for c in self.constraints
241 )
242
243 def check_consistency(self, params: Sequence[click.Parameter]) -> None:
244 for c in self.constraints:
245 c.check_consistency(params)
246
247 def __repr__(self) -> str:
248 return make_repr(self, *self.constraints)
249
250
251 class And(Operator):
252 """It's satisfied if all operands are satisfied."""
253 HELP_SEP = ' and '
254
255 def check_values(self, params: Sequence[click.Parameter], ctx: click.Context) -> None:
256 for c in self.constraints:
257 c.check_values(params, ctx)
258
259 def __and__(self, other: Constraint) -> 'And':
260 if isinstance(other, And):
261 return And(*self.constraints, *other.constraints)
262 return And(*self.constraints, other)
263
264
265 class Or(Operator):
266 """It's satisfied if at least one of the operands is satisfied."""
267 HELP_SEP = ' or '
268
269 def check_values(self, params: Sequence[click.Parameter], ctx: click.Context) -> None:
270 for c in self.constraints:
271 try:
272 c.check_values(params, ctx)
273 return
274 except ConstraintViolated:
275 pass
276 raise ConstraintViolated.default(
277 self.help(ctx), ctx=ctx, constraint=self, params=params
278 )
279
280 def __or__(self, other: Constraint) -> 'Or':
281 if isinstance(other, Or):
282 return Or(*self.constraints, *other.constraints)
283 return Or(*self.constraints, other)
284
285
286 class ErrorFmt(FrozenSpace):
287 """:class:`Rephraser` allows you to pass a ``format`` string as ``error``
288 argument; this class contains the "replacement fields" supported by such
289 format string. You can use them as following::
290
291 mutually_exclusive.rephrased(
292 error=f"{ErrorFmt.error}\\n"
293 f"Some extra information here."
294 )
295 """
296
297 error = '{error}'
298 """Replaced by the original error message. Useful if all you want is to
299 append or prepend some extra info to the original error message."""
300
301 param_list = '{param_list}'
302 """Replaced by a 2-space indented list of the constrained parameters."""
303
304
305 class Rephraser(Constraint):
306 """A constraint decorator that can override the help and/or the error
307 message of the wrapped constraint.
308
309 You'll rarely (if ever) use this class directly. In most cases, you'll use
310 the method :meth:`Constraint.rephrased`. Refer to it for more info.
311
312 .. seealso::
313
314 - :meth:`Constraint.rephrased` -- wraps a constraint with a ``Rephraser``.
315 - :class:`WrapperConstraint` -- alternative to ``Rephraser``.
316 - :class:`ErrorFmt` -- describes the keyword you can use in an error
317 format string.
318 """
319
320 def __init__(
321 self, constraint: Constraint,
322 help: Union[None, str, HelpRephraser] = None,
323 error: Union[None, str, ErrorRephraser] = None,
324 ):
325 if help is None and error is None:
326 raise ValueError('`help` and `error` cannot both be `None`')
327 self.constraint = constraint
328 self._help = help
329 self._error = error
330
331 def help(self, ctx: click.Context) -> str:
332 if self._help is None:
333 return self.constraint.help(ctx)
334 elif isinstance(self._help, str):
335 return self._help
336 else:
337 return self._help(ctx, self.constraint)
338
339 def _get_rephrased_error(self, err: ConstraintViolated) -> Optional[str]:
340 if self._error is None:
341 return None
342 elif isinstance(self._error, str):
343 return self._error.format(
344 error=str(err),
345 param_list=format_param_list(err.params),
346 )
347 else:
348 return self._error(err)
349
350 def check_consistency(self, params: Sequence[click.Parameter]) -> None:
351 try:
352 self.constraint.check_consistency(params)
353 except UnsatisfiableConstraint as exc:
354 raise UnsatisfiableConstraint(
355 self, params=params, reason=exc.reason)
356
357 def check_values(self, params: Sequence[click.Parameter], ctx: click.Context) -> None:
358 try:
359 self.constraint.check_values(params, ctx)
360 except ConstraintViolated as err:
361 rephrased_error = self._get_rephrased_error(err)
362 if rephrased_error:
363 raise ConstraintViolated(
364 rephrased_error, ctx=ctx, constraint=self, params=params)
365 raise
366
367 def __repr__(self) -> str:
368 return make_one_line_repr(self, help=self._help)
369
370
371 class WrapperConstraint(Constraint, metaclass=abc.ABCMeta):
372 """Abstract class that wraps another constraint and delegates all methods
373 to it. Useful when you want to define a parametric constraint combining
374 other existing constraints minimizing the boilerplate.
375
376 This is an alternative to defining a function and using :class:`Rephraser`.
377 Feel free to do that in your code, but cloup will stick to the convention
378 that parametric constraints are defined as classes and written in
379 camel-case."""
380
381 def __init__(self, constraint: Constraint, **attrs: Any):
382 """
383 :param constraint: the constraint to wrap
384 :param attrs: these are just used to generate a ``__repr__`` method
385 """
386 self._constraint = constraint
387 self._attrs = attrs
388
389 def help(self, ctx: click.Context) -> str:
390 return self._constraint.help(ctx)
391
392 def check_consistency(self, params: Sequence[click.Parameter]) -> None:
393 try:
394 self._constraint.check_consistency(params)
395 except UnsatisfiableConstraint as exc:
396 raise UnsatisfiableConstraint(self, params=params, reason=exc.reason)
397
398 def check_values(self, params: Sequence[click.Parameter], ctx: click.Context) -> None:
399 self._constraint.check_values(params, ctx)
400
401 def __repr__(self) -> str:
402 return make_repr(self, **self._attrs)
403
404
405 class _RequireAll(Constraint):
406 """Satisfied if all parameters are set."""
407
408 def help(self, ctx: click.Context) -> str:
409 return 'all required'
410
411 def check_values(self, params: Sequence[click.Parameter], ctx: click.Context) -> None:
412 values = ctx.params
413 unset_params = [param for param in params
414 if not param_value_is_set(param, values[get_param_name(param)])]
415 if any(unset_params):
416 raise ConstraintViolated(
417 pluralize(
418 len(unset_params),
419 one=f"{get_param_label(unset_params[0])} is required",
420 many=f"the following parameters are required:\n"
421 f"{format_param_list(unset_params)}"),
422 ctx=ctx,
423 constraint=self,
424 params=params,
425 )
426
427
428 class RequireAtLeast(Constraint):
429 """Satisfied if the number of set parameters is >= n."""
430
431 def __init__(self, n: int):
432 check_arg(n >= 0)
433 self.min_num_params = n
434
435 def help(self, ctx: click.Context) -> str:
436 return f'at least {self.min_num_params} required'
437
438 def check_consistency(self, params: Sequence[click.Parameter]) -> None:
439 n = self.min_num_params
440 if len(params) < n:
441 reason = (
442 f'the constraint requires a minimum of {n} parameters but '
443 f'it is applied on a group of only {len(params)} parameters!'
444 )
445 raise UnsatisfiableConstraint(self, params, reason)
446
447 def check_values(self, params: Sequence[click.Parameter], ctx: click.Context) -> None:
448 n = self.min_num_params
449 given_params = get_params_whose_value_is_set(params, ctx.params)
450 if len(given_params) < n:
451 raise ConstraintViolated(
452 f"at least {n} of the following parameters must be set:\n"
453 f"{format_param_list(params)}",
454 ctx=ctx, constraint=self, params=params,
455 )
456
457 def __repr__(self) -> str:
458 return make_repr(self, self.min_num_params)
459
460
461 class AcceptAtMost(Constraint):
462 """Satisfied if the number of set parameters is <= n."""
463
464 def __init__(self, n: int):
465 check_arg(n >= 0)
466 self.max_num_params = n
467
468 def help(self, ctx: click.Context) -> str:
469 return f'at most {self.max_num_params} accepted'
470
471 def check_consistency(self, params: Sequence[click.Parameter]) -> None:
472 num_required_params = len(get_required_params(params))
473 if num_required_params > self.max_num_params:
474 reason = f'{num_required_params} of the parameters are required'
475 raise UnsatisfiableConstraint(self, params, reason)
476
477 def check_values(self, params: Sequence[click.Parameter], ctx: click.Context) -> None:
478 n = self.max_num_params
479 given_params = get_params_whose_value_is_set(params, ctx.params)
480 if len(given_params) > n:
481 raise ConstraintViolated(
482 f"no more than {n} of the following parameters can be set:\n"
483 f"{format_param_list(params)}",
484 ctx=ctx, constraint=self, params=params,
485 )
486
487 def __repr__(self) -> str:
488 return make_repr(self, self.max_num_params)
489
490
491 class RequireExactly(WrapperConstraint):
492 """Requires an exact number of parameters to be set."""
493
494 def __init__(self, n: int):
495 check_arg(n > 0)
496 # Defined as a wrapper to reuse check_consistency() of the wrapped constraint.
497 super().__init__(RequireAtLeast(n) & AcceptAtMost(n))
498 self.num_params = n
499
500 def help(self, ctx: click.Context) -> str:
501 return f'exactly {self.num_params} required'
502
503 def check_values(self, params: Sequence[click.Parameter], ctx: click.Context) -> None:
504 n = self.num_params
505 given_params = get_params_whose_value_is_set(params, ctx.params)
506 if len(given_params) != n:
507 reason = pluralize(
508 count=n,
509 zero='none of the following parameters must be set:\n',
510 many=f'exactly {n} of the following parameters must be set:\n'
511 ) + format_param_list(params)
512 raise ConstraintViolated(
513 reason, ctx=ctx, constraint=self, params=params)
514
515 def __repr__(self) -> str:
516 return make_repr(self, self.num_params)
517
518
519 class AcceptBetween(WrapperConstraint):
520 def __init__(self, min: int, max: int): # noqa
521 """Satisfied if the number of set parameters is between
522 ``min`` and ``max`` (included).
523
524 :param min: must be an integer >= 0
525 :param max: must be an integer > min
526 """
527 check_arg(min >= 0, 'min must be non-negative')
528 if max is not None:
529 check_arg(min < max, 'must be: min < max.')
530 super().__init__(RequireAtLeast(min) & AcceptAtMost(max), min=min, max=max)
531 self.min_num_params = min
532 self.max_num_params = max
533
534 def help(self, ctx: click.Context) -> str:
535 return f'at least {self.min_num_params} required, ' \
536 f'at most {self.max_num_params} accepted'
537
538
539 require_all = _RequireAll()
540 """Satisfied if all parameters are set."""
541
542 accept_none = AcceptAtMost(0).rephrased(
543 help='all forbidden',
544 error=f'the following parameters should not be provided:\n'
545 f'{ErrorFmt.param_list}'
546 )
547 """Satisfied if none of the parameters is set. Useful only in conditional constraints."""
548
549 all_or_none = (require_all | accept_none).rephrased(
550 help='provide all or none',
551 error=f'the following parameters should be provided together (or none of '
552 f'them should be provided):\n'
553 f'{ErrorFmt.param_list}',
554 )
555 """Satisfied if either all or none of the parameters are set."""
556
557 mutually_exclusive = AcceptAtMost(1).rephrased(
558 help='mutually exclusive',
559 error=f'the following parameters are mutually exclusive:\n'
560 f'{ErrorFmt.param_list}'
561 )
562 """Satisfied if at most one of the parameters is set."""
563
564 require_any = RequireAtLeast(1)
565 """Alias for ``RequireAtLeast(1)``."""
566
567 require_one = RequireExactly(1)
568 """Alias for ``RequireExactly(1)``."""