| 1 |
""" |
| 2 |
This modules contains predicates with an associated description that you can use |
| 3 |
as conditions of conditional constraints (see :class:`cloup.constraints.If`). |
| 4 |
|
| 5 |
Predicates should be treated as immutable objects, even though immutability |
| 6 |
is not (at the moment) enforced. |
| 7 |
""" |
| 8 |
import abc |
| 9 |
from typing import Any, Dict, Generic, TypeVar |
| 10 |
|
| 11 |
import click |
| 12 |
|
| 13 |
from ._support import ensure_constraints_support |
| 14 |
from .common import ( |
| 15 |
get_param_labels, |
| 16 |
get_param_name, |
| 17 |
join_with_and, |
| 18 |
param_label_by_name, |
| 19 |
param_value_by_name, |
| 20 |
param_value_is_set, |
| 21 |
) |
| 22 |
from .._util import make_repr |
| 23 |
|
| 24 |
P = TypeVar('P', bound='Predicate') |
| 25 |
|
| 26 |
|
| 27 |
class Predicate(abc.ABC): |
| 28 |
""" |
| 29 |
A ``Callable`` that takes a ``click.Context`` and returns a boolean, with an |
| 30 |
associated description. Meant to be used as condition in a conditional |
| 31 |
constraint (see :class:`~cloup.constraints.If`). |
| 32 |
""" |
| 33 |
|
| 34 |
@abc.abstractmethod |
| 35 |
def description(self, ctx: click.Context) -> str: |
| 36 |
"""Succinct description of the predicate (alias: `desc`).""" |
| 37 |
|
| 38 |
def negated_description(self, ctx: click.Context) -> str: |
| 39 |
"""Succinct description of the negation of this predicate (alias: `neg_desc`).""" |
| 40 |
return 'NOT(%s)' % self.description(ctx) |
| 41 |
|
| 42 |
def desc(self, ctx: click.Context) -> str: |
| 43 |
"""Short alias for :meth:`description`.""" |
| 44 |
return self.description(ctx) |
| 45 |
|
| 46 |
def neg_desc(self, ctx: click.Context) -> str: |
| 47 |
"""Short alias for :meth:`negated_description`.""" |
| 48 |
return self.negated_description(ctx) |
| 49 |
|
| 50 |
def negated(self) -> "Predicate": |
| 51 |
return ~self |
| 52 |
|
| 53 |
@abc.abstractmethod |
| 54 |
def __call__(self, ctx: click.Context) -> bool: |
| 55 |
"""Evaluate the predicate on the given context.""" |
| 56 |
|
| 57 |
def __invert__(self) -> "Predicate": |
| 58 |
return Not(self) |
| 59 |
|
| 60 |
def __or__(self, other: "Predicate") -> "Predicate": |
| 61 |
return _Or(self, other) |
| 62 |
|
| 63 |
def __and__(self, other: "Predicate") -> "Predicate": |
| 64 |
return _And(self, other) |
| 65 |
|
| 66 |
def __repr__(self) -> str: |
| 67 |
return make_repr(self, *self._public_fields().values()) |
| 68 |
|
| 69 |
def _public_fields(self) -> Dict[str, Any]: |
| 70 |
return {k: v for k, v in vars(self).items() if not k.startswith('_')} |
| 71 |
|
| 72 |
def __eq__(self, other: object) -> bool: |
| 73 |
return isinstance(other, self.__class__) and ( |
| 74 |
self._public_fields() == other._public_fields() |
| 75 |
) |
| 76 |
|
| 77 |
|
| 78 |
class Not(Predicate, Generic[P]): |
| 79 |
"""Logical NOT of a predicate.""" |
| 80 |
|
| 81 |
def __init__(self, predicate: P): |
| 82 |
self.predicate = predicate |
| 83 |
|
| 84 |
def description(self, ctx: click.Context) -> str: |
| 85 |
return self.predicate.negated_description(ctx) |
| 86 |
|
| 87 |
def negated_description(self, ctx: click.Context) -> str: |
| 88 |
return self.predicate.description(ctx) |
| 89 |
|
| 90 |
def __call__(self, ctx: click.Context) -> bool: |
| 91 |
return not self.predicate(ctx) |
| 92 |
|
| 93 |
def __invert__(self) -> P: |
| 94 |
return self.predicate |
| 95 |
|
| 96 |
def __repr__(self) -> str: |
| 97 |
return 'Not(%r)' % self.predicate |
| 98 |
|
| 99 |
|
| 100 |
class _Operator(Predicate, metaclass=abc.ABCMeta): |
| 101 |
"""Operator between two or more predicates.""" |
| 102 |
DESC_SEP: str |
| 103 |
|
| 104 |
def __init__(self, *predicates: Predicate): |
| 105 |
if len(predicates) < 2: |
| 106 |
raise ValueError('provide at least 2 predicates') |
| 107 |
self.predicates = predicates |
| 108 |
|
| 109 |
def description(self, ctx: click.Context) -> str: |
| 110 |
return self.DESC_SEP.join( |
| 111 |
'(%s)' % p.description(ctx) if isinstance(p, _Operator) |
| 112 |
else p.description(ctx) |
| 113 |
for p in self.predicates |
| 114 |
) |
| 115 |
|
| 116 |
def __repr__(self) -> str: |
| 117 |
return make_repr(self, *self.predicates) |
| 118 |
|
| 119 |
|
| 120 |
class _And(_Operator): |
| 121 |
"""Logical AND of two or more predicates.""" |
| 122 |
DESC_SEP = ' and ' |
| 123 |
|
| 124 |
def negated_description(self, ctx: click.Context) -> str: |
| 125 |
return ' or '.join( |
| 126 |
'(%s)' % p.neg_desc(ctx) if isinstance(p, _Operator) else p.neg_desc(ctx) |
| 127 |
for p in self.predicates |
| 128 |
) |
| 129 |
|
| 130 |
def __call__(self, ctx: click.Context) -> bool: |
| 131 |
return all(p(ctx) for p in self.predicates) |
| 132 |
|
| 133 |
def __and__(self, other: 'Predicate') -> Predicate: |
| 134 |
if isinstance(other, _And): |
| 135 |
return _And(*self.predicates, *other.predicates) |
| 136 |
return _And(*self.predicates, other) |
| 137 |
|
| 138 |
|
| 139 |
class _Or(_Operator): |
| 140 |
"""Logical OR of two or more predicates.""" |
| 141 |
DESC_SEP = ' or ' |
| 142 |
|
| 143 |
def negated_description(self, ctx: click.Context) -> str: |
| 144 |
return ' and '.join( |
| 145 |
'(%s)' % p.neg_desc(ctx) if isinstance(p, _Operator) else p.neg_desc(ctx) |
| 146 |
for p in self.predicates |
| 147 |
) |
| 148 |
|
| 149 |
def __call__(self, ctx: click.Context) -> bool: |
| 150 |
return any(p(ctx) for p in self.predicates) |
| 151 |
|
| 152 |
def __or__(self, other: 'Predicate') -> Predicate: |
| 153 |
if isinstance(other, _Or): |
| 154 |
return _Or(*self.predicates, *other.predicates) |
| 155 |
return _Or(*self.predicates, other) |
| 156 |
|
| 157 |
|
| 158 |
class IsSet(Predicate): |
| 159 |
"""True if the parameter is set.""" |
| 160 |
|
| 161 |
def __init__(self, param_name: str): |
| 162 |
self.param_name = param_name |
| 163 |
|
| 164 |
def description(self, ctx: click.Context) -> str: |
| 165 |
return '%s is set' % param_label_by_name(ctx, self.param_name) |
| 166 |
|
| 167 |
def negated_description(self, ctx: click.Context) -> str: |
| 168 |
return '%s is not set' % param_label_by_name(ctx, self.param_name) |
| 169 |
|
| 170 |
def __call__(self, ctx: click.Context) -> bool: |
| 171 |
command = ensure_constraints_support(ctx.command) |
| 172 |
param = command.get_param_by_name(self.param_name) |
| 173 |
value = param_value_by_name(ctx, self.param_name) |
| 174 |
return param_value_is_set(param, value) |
| 175 |
|
| 176 |
def __and__(self, other: Predicate) -> Predicate: |
| 177 |
if isinstance(other, IsSet): |
| 178 |
return AllSet(self.param_name, other.param_name) |
| 179 |
return super().__and__(other) |
| 180 |
|
| 181 |
def __or__(self, other: Predicate) -> Predicate: |
| 182 |
if isinstance(other, IsSet): |
| 183 |
return AnySet(self.param_name, other.param_name) |
| 184 |
return super().__or__(other) |
| 185 |
|
| 186 |
|
| 187 |
class AllSet(Predicate): |
| 188 |
"""True if all listed parameters are set. |
| 189 |
|
| 190 |
.. versionadded:: 0.8.0 |
| 191 |
""" |
| 192 |
|
| 193 |
def __init__(self, *param_names: str): |
| 194 |
if not param_names: |
| 195 |
raise ValueError('you must provide at least one param name') |
| 196 |
self.param_names = param_names |
| 197 |
|
| 198 |
def negated_description(self, ctx: click.Context) -> str: |
| 199 |
labels = get_param_labels(ctx, self.param_names) |
| 200 |
if len(labels) == 1: |
| 201 |
return f'{labels[0]} is not set' |
| 202 |
pronoun = 'both' if len(labels) == 2 else 'all' |
| 203 |
return f'{join_with_and(labels)} are not {pronoun} set' |
| 204 |
|
| 205 |
def description(self, ctx: click.Context) -> str: |
| 206 |
labels = get_param_labels(ctx, self.param_names) |
| 207 |
if len(labels) == 1: |
| 208 |
return f'{labels[0]} is set' |
| 209 |
pronoun = 'both' if len(labels) == 2 else 'all' |
| 210 |
return f'{join_with_and(labels)} are {pronoun} set' |
| 211 |
|
| 212 |
def __call__(self, ctx: click.Context) -> bool: |
| 213 |
command = ensure_constraints_support(ctx.command) |
| 214 |
params = command.get_params_by_name(self.param_names) |
| 215 |
return all(param_value_is_set(param, ctx.params[get_param_name(param)]) |
| 216 |
for param in params) |
| 217 |
|
| 218 |
def __and__(self, other: Predicate) -> Predicate: |
| 219 |
if isinstance(other, AllSet): |
| 220 |
return AllSet(*self.param_names, *other.param_names) |
| 221 |
return super().__and__(other) |
| 222 |
|
| 223 |
|
| 224 |
class AnySet(Predicate): |
| 225 |
"""True if any of the listed parameters is set. |
| 226 |
|
| 227 |
.. versionadded:: 0.8.0 |
| 228 |
""" |
| 229 |
|
| 230 |
def __init__(self, *param_names: str): |
| 231 |
if not param_names: |
| 232 |
raise ValueError('you must provide at least one param name') |
| 233 |
self.param_names = param_names |
| 234 |
|
| 235 |
def negated_description(self, ctx: click.Context) -> str: |
| 236 |
labels = get_param_labels(ctx, self.param_names) |
| 237 |
if len(labels) == 1: |
| 238 |
return f'{labels[0]} is not set' |
| 239 |
if len(labels) == 2: |
| 240 |
return 'neither {} nor {} is set'.format(*labels) |
| 241 |
return f'none of {join_with_and(labels)} is set' |
| 242 |
|
| 243 |
def description(self, ctx: click.Context) -> str: |
| 244 |
labels = get_param_labels(ctx, self.param_names) |
| 245 |
if len(labels) == 1: |
| 246 |
return f'{labels[0]} is set' |
| 247 |
if len(labels) == 2: |
| 248 |
return 'either {} or {} is set'.format(*labels) |
| 249 |
return f'any of {join_with_and(labels)} is set' |
| 250 |
|
| 251 |
def __call__(self, ctx: click.Context) -> bool: |
| 252 |
command = ensure_constraints_support(ctx.command) |
| 253 |
params = command.get_params_by_name(self.param_names) |
| 254 |
return any(param_value_is_set(param, ctx.params[get_param_name(param)]) |
| 255 |
for param in params) |
| 256 |
|
| 257 |
def __or__(self, other: Predicate) -> Predicate: |
| 258 |
if isinstance(other, AnySet): |
| 259 |
return AnySet(*self.param_names, *other.param_names) |
| 260 |
return super().__or__(other) |
| 261 |
|
| 262 |
|
| 263 |
class Equal(Predicate): |
| 264 |
"""True if the parameter value equals ``value``.""" |
| 265 |
|
| 266 |
def __init__(self, param_name: str, value: Any): |
| 267 |
self.param_name = param_name |
| 268 |
self.value = value |
| 269 |
|
| 270 |
def description(self, ctx: click.Context) -> str: |
| 271 |
param_label = param_label_by_name(ctx, self.param_name) |
| 272 |
return f'{param_label}="{self.value}"' |
| 273 |
|
| 274 |
def negated_description(self, ctx: click.Context) -> str: |
| 275 |
param_label = param_label_by_name(ctx, self.param_name) |
| 276 |
return f'{param_label}!="{self.value}"' |
| 277 |
|
| 278 |
def __call__(self, ctx: click.Context) -> bool: |
| 279 |
return param_value_by_name(ctx, self.param_name) == self.value # type: ignore |