Debian Codegraph @

cloup/constraints/exceptions.py

raw
1 from typing import Iterable, Sequence, TYPE_CHECKING
2
3 import click
4 from click import Context, Parameter
5
6 from .common import join_param_labels
7
8 if TYPE_CHECKING:
9 from ._core import Constraint
10
11
12 def default_constraint_error(params: Iterable[Parameter], desc: str) -> str:
13 return (
14 'the following constraint on parameters [%s] was not satisfied: %s'
15 % (join_param_labels(params), desc)
16 )
17
18
19 class ConstraintViolated(click.UsageError):
20 def __init__(
21 self, message: str,
22 ctx: Context,
23 constraint: 'Constraint',
24 params: Sequence[click.Parameter]
25 ):
26 super().__init__(message, ctx=ctx)
27 self.ctx = ctx
28 self.constraint = constraint
29 self.params = params
30
31 @classmethod
32 def default(
33 cls,
34 desc: str,
35 ctx: Context,
36 constraint: 'Constraint',
37 params: Sequence[Parameter],
38 ) -> 'ConstraintViolated':
39 return ConstraintViolated(
40 default_constraint_error(params, desc),
41 ctx=ctx, constraint=constraint, params=params,
42 )
43
44
45 class UnsatisfiableConstraint(Exception):
46 """Raised if a constraint cannot be satisfied by a group of parameters
47 independently from their values at runtime; e.g. ``mutually_exclusive`` cannot
48 be satisfied if multiple of the parameters are required."""
49
50 def __init__(
51 self, constraint: 'Constraint', params: Iterable[Parameter], reason: str
52 ):
53 self.constraint = constraint
54 self.params = params
55 self.reason = reason
56 param_names = join_param_labels(params)
57 message = (f"\nthe constraint {constraint}\n"
58 f"defined on parameters [{param_names}]\n"
59 f"cannot be satisfied because {reason}")
60 super().__init__(message)