Debian Codegraph @

cloup/constraints/_support.py

raw
1 from typing import (
2 Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Sequence,
3 TYPE_CHECKING, Tuple, Union,
4 )
5
6 import click
7
8 from ._core import Constraint
9 from .common import join_param_labels
10 from .._util import first_bool
11 from ..typing import Decorator, F
12
13 if TYPE_CHECKING:
14 from cloup import HelpFormatter, OptionGroup
15
16
17 class BoundConstraintSpec(NamedTuple):
18 """A NamedTuple storing a ``Constraint`` and the **names of the parameters**
19 it has to check."""
20 constraint: Constraint
21 param_names: Union[Sequence[str]]
22
23 def resolve_params(self, cmd: 'ConstraintMixin') -> 'BoundConstraint':
24 return BoundConstraint(
25 self.constraint,
26 cmd.get_params_by_name(self.param_names)
27 )
28
29
30 def _constraint_memo(
31 f: Any, constr: Union[BoundConstraintSpec, 'BoundConstraint']
32 ) -> None:
33 if not hasattr(f, '__cloup_constraints__'):
34 f.__cloup_constraints__ = []
35 f.__cloup_constraints__.append(constr)
36
37
38 def constraint(constr: Constraint, params: Iterable[str]) -> Callable[[F], F]:
39 """Register a constraint on a list of parameters specified by (destination) name
40 (e.g. the default name of ``--input-file`` is ``input_file``)."""
41 spec = BoundConstraintSpec(constr, tuple(params))
42
43 def decorator(f: F) -> F:
44 _constraint_memo(f, spec)
45 return f
46
47 return decorator
48
49
50 def constrained_params(
51 constr: Constraint,
52 *param_adders: Decorator,
53 ) -> Callable[[F], F]:
54 """
55 Return a decorator that adds the given parameters and applies a constraint
56 to them. Equivalent to::
57
58 @param_adders[0]
59 ...
60 @param_adders[-1]
61 @constraint(constr, <param names>)
62
63 This decorator saves you to manually (re)type the parameter names.
64 It can also be used inside ``@option_group``.
65
66 Instead of using this decorator, you can also call the constraint itself::
67
68 @constr(*param_adders)
69
70 but remember that:
71
72 - Python 3.9 is the first that allows arbitrary expressions on the right of ``@``;
73 - using a long conditional/composite constraint as decorator may be less
74 readable.
75
76 In these cases, you may consider using ``@constrained_params``.
77
78 .. versionadded:: 0.9.0
79
80 :param constr: an instance of :class:`Constraint`
81 :param param_adders:
82 function decorators, each attaching a single parameter to the decorated
83 function.
84 """
85
86 def decorator(f: F) -> F:
87 reversed_params = []
88 for add_param in reversed(param_adders):
89 add_param(f)
90 param = f.__click_params__[-1] # type: ignore
91 reversed_params.append(param)
92 bound_constr = BoundConstraint(constr, tuple(reversed_params[::-1]))
93 _constraint_memo(f, bound_constr)
94 return f
95
96 return decorator
97
98
99 class BoundConstraint(NamedTuple):
100 """Internal utility ``NamedTuple`` that represents a ``Constraint``
101 bound to a collection of ``click.Parameter`` instances.
102 Note: this is not a subclass of Constraint."""
103
104 constraint: Constraint
105 params: Sequence[click.Parameter]
106
107 def check_consistency(self) -> None:
108 self.constraint.check_consistency(self.params)
109
110 def check_values(self, ctx: click.Context) -> None:
111 self.constraint.check_values(self.params, ctx)
112
113 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:
114 constr_help = self.constraint.help(ctx)
115 if not constr_help:
116 return None
117 param_list = '{%s}' % join_param_labels(self.params)
118 return param_list, constr_help
119
120
121 class ConstraintMixin:
122 """Provides support for constraints."""
123
124 def __init__(
125 self, *args: Any,
126 constraints: Sequence[Union[BoundConstraintSpec, BoundConstraint]] = (),
127 show_constraints: Optional[bool] = None,
128 **kwargs: Any,
129 ):
130 """
131 :param constraints:
132 sequence of constraints bound to specific groups of parameters.
133 Note that constraints applied to option groups are collected from
134 the option groups themselves, so they don't need to be included in
135 this argument.
136 :param show_constraints:
137 whether to include a "Constraint" section in the command help. This
138 is also available as a context setting having a lower priority than
139 this attribute.
140 :param args:
141 positional arguments forwarded to the next class in the MRO
142 :param kwargs:
143 keyword arguments forwarded to the next class in the MRO
144 """
145 super().__init__(*args, **kwargs)
146
147 self.show_constraints = show_constraints
148
149 # This allows constraints to efficiently access parameters by name
150 self._params_by_name: Dict[str, click.Parameter] = {
151 param.name: param for param in self.params # type: ignore
152 }
153
154 # Collect constraints applied to option groups and bind them to the
155 # corresponding Option instances
156 option_groups: Tuple[OptionGroup, ...] = getattr(self, 'option_groups', tuple())
157 self.optgroup_constraints = tuple(
158 BoundConstraint(grp.constraint, grp.options)
159 for grp in option_groups
160 if grp.constraint is not None
161 )
162 """Constraints applied to ``OptionGroup`` instances."""
163
164 # Bind constraints defined via @constraint to click.Parameter instances
165 self.param_constraints: Tuple[BoundConstraint, ...] = tuple(
166 (
167 constr if isinstance(constr, BoundConstraint)
168 else constr.resolve_params(self)
169 )
170 for constr in constraints
171 )
172 """Constraints registered using ``@constraint`` (or equivalent method)."""
173
174 self.all_constraints = self.optgroup_constraints + self.param_constraints
175 """All constraints applied to parameter/option groups of this command."""
176
177 def parse_args(self, ctx: click.Context, args: List[str]) -> List[str]:
178 # Check constraints' consistency *before* parsing
179 if not ctx.resilient_parsing and Constraint.must_check_consistency(ctx):
180 for constr in self.all_constraints:
181 constr.check_consistency()
182
183 args = super().parse_args(ctx, args) # type: ignore
184
185 # Skip constraints checking if the user wants to see --help for subcommand
186 # or if resilient parsing is enabled
187 should_show_subcommand_help = isinstance(ctx.command, click.Group) and any(
188 help_flag in args for help_flag in ctx.help_option_names
189 )
190 if ctx.resilient_parsing or should_show_subcommand_help:
191 return args
192
193 # Check constraints
194 for constr in self.all_constraints:
195 constr.check_values(ctx)
196 return args
197
198 def get_param_by_name(self, name: str) -> click.Parameter:
199 try:
200 return self._params_by_name[name]
201 except KeyError:
202 raise KeyError(f"there's no CLI parameter named '{name}'")
203
204 def get_params_by_name(self, names: Iterable[str]) -> Sequence[click.Parameter]:
205 return tuple(self.get_param_by_name(name) for name in names)
206
207 def format_constraints(self, ctx: click.Context, formatter: "HelpFormatter") -> None:
208 records_gen = (constr.get_help_record(ctx) for constr in self.param_constraints)
209 records = [rec for rec in records_gen if rec is not None]
210 if records:
211 with formatter.section('Constraints'):
212 formatter.write_dl(records)
213
214 def must_show_constraints(self, ctx: click.Context) -> bool:
215 # By default, don't show constraints
216 return first_bool(
217 self.show_constraints,
218 getattr(ctx, "show_constraints", None),
219 False,
220 )
221
222
223 def ensure_constraints_support(command: click.Command) -> ConstraintMixin:
224 if isinstance(command, ConstraintMixin):
225 return command
226 raise TypeError(
227 'a Command must inherits from ConstraintMixin to support constraints')