File: conditions.py

package info (click to toggle)
python-cloup 3.0.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 936 kB
  • sloc: python: 5,371; makefile: 120
file content (279 lines) | stat: -rw-r--r-- 9,420 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
"""
This modules contains predicates with an associated description that you can use
as conditions of conditional constraints (see :class:`cloup.constraints.If`).

Predicates should be treated as immutable objects, even though immutability
is not (at the moment) enforced.
"""
import abc
from typing import Any, Dict, Generic, TypeVar

import click

from ._support import ensure_constraints_support
from .common import (
    get_param_labels,
    get_param_name,
    join_with_and,
    param_label_by_name,
    param_value_by_name,
    param_value_is_set,
)
from .._util import make_repr

P = TypeVar('P', bound='Predicate')


class Predicate(abc.ABC):
    """
    A ``Callable`` that takes a ``click.Context`` and returns a boolean, with an
    associated description. Meant to be used as condition in a conditional
    constraint (see :class:`~cloup.constraints.If`).
    """

    @abc.abstractmethod
    def description(self, ctx: click.Context) -> str:
        """Succinct description of the predicate (alias: `desc`)."""

    def negated_description(self, ctx: click.Context) -> str:
        """Succinct description of the negation of this predicate (alias: `neg_desc`)."""
        return 'NOT(%s)' % self.description(ctx)

    def desc(self, ctx: click.Context) -> str:
        """Short alias for :meth:`description`."""
        return self.description(ctx)

    def neg_desc(self, ctx: click.Context) -> str:
        """Short alias for :meth:`negated_description`."""
        return self.negated_description(ctx)

    def negated(self) -> "Predicate":
        return ~self

    @abc.abstractmethod
    def __call__(self, ctx: click.Context) -> bool:
        """Evaluate the predicate on the given context."""

    def __invert__(self) -> "Predicate":
        return Not(self)

    def __or__(self, other: "Predicate") -> "Predicate":
        return _Or(self, other)

    def __and__(self, other: "Predicate") -> "Predicate":
        return _And(self, other)

    def __repr__(self) -> str:
        return make_repr(self, *self._public_fields().values())

    def _public_fields(self) -> Dict[str, Any]:
        return {k: v for k, v in vars(self).items() if not k.startswith('_')}

    def __eq__(self, other: object) -> bool:
        return isinstance(other, self.__class__) and (
            self._public_fields() == other._public_fields()
        )


class Not(Predicate, Generic[P]):
    """Logical NOT of a predicate."""

    def __init__(self, predicate: P):
        self.predicate = predicate

    def description(self, ctx: click.Context) -> str:
        return self.predicate.negated_description(ctx)

    def negated_description(self, ctx: click.Context) -> str:
        return self.predicate.description(ctx)

    def __call__(self, ctx: click.Context) -> bool:
        return not self.predicate(ctx)

    def __invert__(self) -> P:
        return self.predicate

    def __repr__(self) -> str:
        return 'Not(%r)' % self.predicate


class _Operator(Predicate, metaclass=abc.ABCMeta):
    """Operator between two or more predicates."""
    DESC_SEP: str

    def __init__(self, *predicates: Predicate):
        if len(predicates) < 2:
            raise ValueError('provide at least 2 predicates')
        self.predicates = predicates

    def description(self, ctx: click.Context) -> str:
        return self.DESC_SEP.join(
            '(%s)' % p.description(ctx) if isinstance(p, _Operator)
            else p.description(ctx)
            for p in self.predicates
        )

    def __repr__(self) -> str:
        return make_repr(self, *self.predicates)


class _And(_Operator):
    """Logical AND of two or more predicates."""
    DESC_SEP = ' and '

    def negated_description(self, ctx: click.Context) -> str:
        return ' or '.join(
            '(%s)' % p.neg_desc(ctx) if isinstance(p, _Operator) else p.neg_desc(ctx)
            for p in self.predicates
        )

    def __call__(self, ctx: click.Context) -> bool:
        return all(p(ctx) for p in self.predicates)

    def __and__(self, other: 'Predicate') -> Predicate:
        if isinstance(other, _And):
            return _And(*self.predicates, *other.predicates)
        return _And(*self.predicates, other)


class _Or(_Operator):
    """Logical OR of two or more predicates."""
    DESC_SEP = ' or '

    def negated_description(self, ctx: click.Context) -> str:
        return ' and '.join(
            '(%s)' % p.neg_desc(ctx) if isinstance(p, _Operator) else p.neg_desc(ctx)
            for p in self.predicates
        )

    def __call__(self, ctx: click.Context) -> bool:
        return any(p(ctx) for p in self.predicates)

    def __or__(self, other: 'Predicate') -> Predicate:
        if isinstance(other, _Or):
            return _Or(*self.predicates, *other.predicates)
        return _Or(*self.predicates, other)


class IsSet(Predicate):
    """True if the parameter is set."""

    def __init__(self, param_name: str):
        self.param_name = param_name

    def description(self, ctx: click.Context) -> str:
        return '%s is set' % param_label_by_name(ctx, self.param_name)

    def negated_description(self, ctx: click.Context) -> str:
        return '%s is not set' % param_label_by_name(ctx, self.param_name)

    def __call__(self, ctx: click.Context) -> bool:
        command = ensure_constraints_support(ctx.command)
        param = command.get_param_by_name(self.param_name)
        value = param_value_by_name(ctx, self.param_name)
        return param_value_is_set(param, value)

    def __and__(self, other: Predicate) -> Predicate:
        if isinstance(other, IsSet):
            return AllSet(self.param_name, other.param_name)
        return super().__and__(other)

    def __or__(self, other: Predicate) -> Predicate:
        if isinstance(other, IsSet):
            return AnySet(self.param_name, other.param_name)
        return super().__or__(other)


class AllSet(Predicate):
    """True if all listed parameters are set.

    .. versionadded:: 0.8.0
    """

    def __init__(self, *param_names: str):
        if not param_names:
            raise ValueError('you must provide at least one param name')
        self.param_names = param_names

    def negated_description(self, ctx: click.Context) -> str:
        labels = get_param_labels(ctx, self.param_names)
        if len(labels) == 1:
            return f'{labels[0]} is not set'
        pronoun = 'both' if len(labels) == 2 else 'all'
        return f'{join_with_and(labels)} are not {pronoun} set'

    def description(self, ctx: click.Context) -> str:
        labels = get_param_labels(ctx, self.param_names)
        if len(labels) == 1:
            return f'{labels[0]} is set'
        pronoun = 'both' if len(labels) == 2 else 'all'
        return f'{join_with_and(labels)} are {pronoun} set'

    def __call__(self, ctx: click.Context) -> bool:
        command = ensure_constraints_support(ctx.command)
        params = command.get_params_by_name(self.param_names)
        return all(param_value_is_set(param, ctx.params[get_param_name(param)])
                   for param in params)

    def __and__(self, other: Predicate) -> Predicate:
        if isinstance(other, AllSet):
            return AllSet(*self.param_names, *other.param_names)
        return super().__and__(other)


class AnySet(Predicate):
    """True if any of the listed parameters is set.

    .. versionadded:: 0.8.0
    """

    def __init__(self, *param_names: str):
        if not param_names:
            raise ValueError('you must provide at least one param name')
        self.param_names = param_names

    def negated_description(self, ctx: click.Context) -> str:
        labels = get_param_labels(ctx, self.param_names)
        if len(labels) == 1:
            return f'{labels[0]} is not set'
        if len(labels) == 2:
            return 'neither {} nor {} is set'.format(*labels)
        return f'none of {join_with_and(labels)} is set'

    def description(self, ctx: click.Context) -> str:
        labels = get_param_labels(ctx, self.param_names)
        if len(labels) == 1:
            return f'{labels[0]} is set'
        if len(labels) == 2:
            return 'either {} or {} is set'.format(*labels)
        return f'any of {join_with_and(labels)} is set'

    def __call__(self, ctx: click.Context) -> bool:
        command = ensure_constraints_support(ctx.command)
        params = command.get_params_by_name(self.param_names)
        return any(param_value_is_set(param, ctx.params[get_param_name(param)])
                   for param in params)

    def __or__(self, other: Predicate) -> Predicate:
        if isinstance(other, AnySet):
            return AnySet(*self.param_names, *other.param_names)
        return super().__or__(other)


class Equal(Predicate):
    """True if the parameter value equals ``value``."""

    def __init__(self, param_name: str, value: Any):
        self.param_name = param_name
        self.value = value

    def description(self, ctx: click.Context) -> str:
        param_label = param_label_by_name(ctx, self.param_name)
        return f'{param_label}="{self.value}"'

    def negated_description(self, ctx: click.Context) -> str:
        param_label = param_label_by_name(ctx, self.param_name)
        return f'{param_label}!="{self.value}"'

    def __call__(self, ctx: click.Context) -> bool:
        return param_value_by_name(ctx, self.param_name) == self.value  # type: ignore