pboot-validator 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. pboot_validator/__init__.py +461 -0
  2. pboot_validator/_internal/__init__.py +0 -0
  3. pboot_validator/_internal/_config.py +408 -0
  4. pboot_validator/_internal/_contextlib.py +84 -0
  5. pboot_validator/_internal/_core_metadata.py +97 -0
  6. pboot_validator/_internal/_core_utils.py +156 -0
  7. pboot_validator/_internal/_dataclasses.py +327 -0
  8. pboot_validator/_internal/_decorators.py +906 -0
  9. pboot_validator/_internal/_decorators_v1.py +174 -0
  10. pboot_validator/_internal/_discriminated_union.py +510 -0
  11. pboot_validator/_internal/_docs_extraction.py +128 -0
  12. pboot_validator/_internal/_fields.py +910 -0
  13. pboot_validator/_internal/_forward_ref.py +23 -0
  14. pboot_validator/_internal/_generate_schema.py +3053 -0
  15. pboot_validator/_internal/_generics.py +572 -0
  16. pboot_validator/_internal/_git.py +27 -0
  17. pboot_validator/_internal/_import_utils.py +20 -0
  18. pboot_validator/_internal/_known_annotated_metadata.py +412 -0
  19. pboot_validator/_internal/_mock_val_ser.py +241 -0
  20. pboot_validator/_internal/_model_construction.py +833 -0
  21. pboot_validator/_internal/_namespace_utils.py +300 -0
  22. pboot_validator/_internal/_repr.py +129 -0
  23. pboot_validator/_internal/_schema_gather.py +49 -0
  24. pboot_validator/_internal/_schema_generation_shared.py +126 -0
  25. pboot_validator/_internal/_serializers.py +59 -0
  26. pboot_validator/_internal/_signature.py +193 -0
  27. pboot_validator/_internal/_type_refs.py +128 -0
  28. pboot_validator/_internal/_typing_extra.py +506 -0
  29. pboot_validator/_internal/_utils.py +433 -0
  30. pboot_validator/_internal/_validate_call.py +141 -0
  31. pboot_validator/_internal/_validators.py +541 -0
  32. pboot_validator/_migration.py +317 -0
  33. pboot_validator/alias_generators.py +62 -0
  34. pboot_validator/aliases.py +136 -0
  35. pboot_validator/annotated_handlers.py +123 -0
  36. pboot_validator/class_validators.py +5 -0
  37. pboot_validator/color.py +605 -0
  38. pboot_validator/config.py +1295 -0
  39. pboot_validator/dataclasses.py +385 -0
  40. pboot_validator/datetime_parse.py +5 -0
  41. pboot_validator/decorator.py +5 -0
  42. pboot_validator/deprecated/__init__.py +0 -0
  43. pboot_validator/deprecated/class_validators.py +257 -0
  44. pboot_validator/deprecated/config.py +72 -0
  45. pboot_validator/deprecated/copy_internals.py +224 -0
  46. pboot_validator/deprecated/decorator.py +286 -0
  47. pboot_validator/deprecated/json.py +142 -0
  48. pboot_validator/deprecated/parse.py +81 -0
  49. pboot_validator/deprecated/tools.py +104 -0
  50. pboot_validator/env_settings.py +5 -0
  51. pboot_validator/error_wrappers.py +5 -0
  52. pboot_validator/errors.py +185 -0
  53. pboot_validator/experimental/__init__.py +1 -0
  54. pboot_validator/experimental/arguments_schema.py +44 -0
  55. pboot_validator/experimental/missing_sentinel.py +29 -0
  56. pboot_validator/experimental/pipeline.py +684 -0
  57. pboot_validator/fields.py +2065 -0
  58. pboot_validator/functional_serializers.py +461 -0
  59. pboot_validator/functional_validators.py +920 -0
  60. pboot_validator/generics.py +5 -0
  61. pboot_validator/json.py +5 -0
  62. pboot_validator/json_schema.py +3283 -0
  63. pboot_validator/main.py +1947 -0
  64. pboot_validator/mypy.py +1469 -0
  65. pboot_validator/networks.py +1417 -0
  66. pboot_validator/parse.py +5 -0
  67. pboot_validator/plugin/__init__.py +190 -0
  68. pboot_validator/plugin/_loader.py +56 -0
  69. pboot_validator/plugin/_schema_validator.py +152 -0
  70. pboot_validator/py.typed +0 -0
  71. pboot_validator/root_model.py +189 -0
  72. pboot_validator/schema.py +5 -0
  73. pboot_validator/tools.py +5 -0
  74. pboot_validator/type_adapter.py +780 -0
  75. pboot_validator/types.py +3405 -0
  76. pboot_validator/typing.py +5 -0
  77. pboot_validator/utils.py +5 -0
  78. pboot_validator/v1/__init__.py +131 -0
  79. pboot_validator/v1/_hypothesis_plugin.py +391 -0
  80. pboot_validator/v1/annotated_types.py +72 -0
  81. pboot_validator/v1/class_validators.py +361 -0
  82. pboot_validator/v1/color.py +494 -0
  83. pboot_validator/v1/config.py +191 -0
  84. pboot_validator/v1/dataclasses.py +503 -0
  85. pboot_validator/v1/datetime_parse.py +248 -0
  86. pboot_validator/v1/decorator.py +264 -0
  87. pboot_validator/v1/env_settings.py +350 -0
  88. pboot_validator/v1/error_wrappers.py +161 -0
  89. pboot_validator/v1/errors.py +646 -0
  90. pboot_validator/v1/fields.py +1253 -0
  91. pboot_validator/v1/generics.py +400 -0
  92. pboot_validator/v1/json.py +112 -0
  93. pboot_validator/v1/main.py +1130 -0
  94. pboot_validator/v1/mypy.py +950 -0
  95. pboot_validator/v1/networks.py +747 -0
  96. pboot_validator/v1/parse.py +66 -0
  97. pboot_validator/v1/py.typed +0 -0
  98. pboot_validator/v1/schema.py +1163 -0
  99. pboot_validator/v1/tools.py +92 -0
  100. pboot_validator/v1/types.py +1213 -0
  101. pboot_validator/v1/typing.py +627 -0
  102. pboot_validator/v1/utils.py +807 -0
  103. pboot_validator/v1/validators.py +768 -0
  104. pboot_validator/v1/version.py +38 -0
  105. pboot_validator/validate_call_decorator.py +121 -0
  106. pboot_validator/validators.py +5 -0
  107. pboot_validator/version.py +113 -0
  108. pboot_validator/warnings.py +130 -0
  109. pboot_validator-1.0.0.dist-info/METADATA +93 -0
  110. pboot_validator-1.0.0.dist-info/RECORD +112 -0
  111. pboot_validator-1.0.0.dist-info/WHEEL +4 -0
  112. pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,494 @@
1
+ """
2
+ Color definitions are used as per CSS3 specification:
3
+ http://www.w3.org/TR/css3-color/#svg-color
4
+
5
+ A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`.
6
+
7
+ In these cases the LAST color when sorted alphabetically takes preferences,
8
+ eg. Color((0, 255, 255)).as_named() == 'cyan' because "cyan" comes after "aqua".
9
+ """
10
+ import math
11
+ import re
12
+ from colorsys import hls_to_rgb, rgb_to_hls
13
+ from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union, cast
14
+
15
+ from pboot_validator.v1.errors import ColorError
16
+ from pboot_validator.v1.utils import Representation, almost_equal_floats
17
+
18
+ if TYPE_CHECKING:
19
+ from pboot_validator.v1.typing import CallableGenerator, ReprArgs
20
+
21
+ ColorTuple = Union[Tuple[int, int, int], Tuple[int, int, int, float]]
22
+ ColorType = Union[ColorTuple, str]
23
+ HslColorTuple = Union[Tuple[float, float, float], Tuple[float, float, float, float]]
24
+
25
+
26
+ class RGBA:
27
+ """
28
+ Internal use only as a representation of a color.
29
+ """
30
+
31
+ __slots__ = 'r', 'g', 'b', 'alpha', '_tuple'
32
+
33
+ def __init__(self, r: float, g: float, b: float, alpha: Optional[float]):
34
+ self.r = r
35
+ self.g = g
36
+ self.b = b
37
+ self.alpha = alpha
38
+
39
+ self._tuple: Tuple[float, float, float, Optional[float]] = (r, g, b, alpha)
40
+
41
+ def __getitem__(self, item: Any) -> Any:
42
+ return self._tuple[item]
43
+
44
+
45
+ # these are not compiled here to avoid import slowdown, they'll be compiled the first time they're used, then cached
46
+ r_hex_short = r'\s*(?:#|0x)?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?\s*'
47
+ r_hex_long = r'\s*(?:#|0x)?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?\s*'
48
+ _r_255 = r'(\d{1,3}(?:\.\d+)?)'
49
+ _r_comma = r'\s*,\s*'
50
+ r_rgb = fr'\s*rgb\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}\)\s*'
51
+ _r_alpha = r'(\d(?:\.\d+)?|\.\d+|\d{1,2}%)'
52
+ r_rgba = fr'\s*rgba\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_alpha}\s*\)\s*'
53
+ _r_h = r'(-?\d+(?:\.\d+)?|-?\.\d+)(deg|rad|turn)?'
54
+ _r_sl = r'(\d{1,3}(?:\.\d+)?)%'
55
+ r_hsl = fr'\s*hsl\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}\s*\)\s*'
56
+ r_hsla = fr'\s*hsl\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}{_r_comma}{_r_alpha}\s*\)\s*'
57
+
58
+ # colors where the two hex characters are the same, if all colors match this the short version of hex colors can be used
59
+ repeat_colors = {int(c * 2, 16) for c in '0123456789abcdef'}
60
+ rads = 2 * math.pi
61
+
62
+
63
+ class Color(Representation):
64
+ __slots__ = '_original', '_rgba'
65
+
66
+ def __init__(self, value: ColorType) -> None:
67
+ self._rgba: RGBA
68
+ self._original: ColorType
69
+ if isinstance(value, (tuple, list)):
70
+ self._rgba = parse_tuple(value)
71
+ elif isinstance(value, str):
72
+ self._rgba = parse_str(value)
73
+ elif isinstance(value, Color):
74
+ self._rgba = value._rgba
75
+ value = value._original
76
+ else:
77
+ raise ColorError(reason='value must be a tuple, list or string')
78
+
79
+ # if we've got here value must be a valid color
80
+ self._original = value
81
+
82
+ @classmethod
83
+ def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
84
+ field_schema.update(type='string', format='color')
85
+
86
+ def original(self) -> ColorType:
87
+ """
88
+ Original value passed to Color
89
+ """
90
+ return self._original
91
+
92
+ def as_named(self, *, fallback: bool = False) -> str:
93
+ if self._rgba.alpha is None:
94
+ rgb = cast(Tuple[int, int, int], self.as_rgb_tuple())
95
+ try:
96
+ return COLORS_BY_VALUE[rgb]
97
+ except KeyError as e:
98
+ if fallback:
99
+ return self.as_hex()
100
+ else:
101
+ raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e
102
+ else:
103
+ return self.as_hex()
104
+
105
+ def as_hex(self) -> str:
106
+ """
107
+ Hex string representing the color can be 3, 4, 6 or 8 characters depending on whether the string
108
+ a "short" representation of the color is possible and whether there's an alpha channel.
109
+ """
110
+ values = [float_to_255(c) for c in self._rgba[:3]]
111
+ if self._rgba.alpha is not None:
112
+ values.append(float_to_255(self._rgba.alpha))
113
+
114
+ as_hex = ''.join(f'{v:02x}' for v in values)
115
+ if all(c in repeat_colors for c in values):
116
+ as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2))
117
+ return '#' + as_hex
118
+
119
+ def as_rgb(self) -> str:
120
+ """
121
+ Color as an rgb(<r>, <g>, <b>) or rgba(<r>, <g>, <b>, <a>) string.
122
+ """
123
+ if self._rgba.alpha is None:
124
+ return f'rgb({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)})'
125
+ else:
126
+ return (
127
+ f'rgba({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)}, '
128
+ f'{round(self._alpha_float(), 2)})'
129
+ )
130
+
131
+ def as_rgb_tuple(self, *, alpha: Optional[bool] = None) -> ColorTuple:
132
+ """
133
+ Color as an RGB or RGBA tuple; red, green and blue are in the range 0 to 255, alpha if included is
134
+ in the range 0 to 1.
135
+
136
+ :param alpha: whether to include the alpha channel, options are
137
+ None - (default) include alpha only if it's set (e.g. not None)
138
+ True - always include alpha,
139
+ False - always omit alpha,
140
+ """
141
+ r, g, b = (float_to_255(c) for c in self._rgba[:3])
142
+ if alpha is None:
143
+ if self._rgba.alpha is None:
144
+ return r, g, b
145
+ else:
146
+ return r, g, b, self._alpha_float()
147
+ elif alpha:
148
+ return r, g, b, self._alpha_float()
149
+ else:
150
+ # alpha is False
151
+ return r, g, b
152
+
153
+ def as_hsl(self) -> str:
154
+ """
155
+ Color as an hsl(<h>, <s>, <l>) or hsl(<h>, <s>, <l>, <a>) string.
156
+ """
157
+ if self._rgba.alpha is None:
158
+ h, s, li = self.as_hsl_tuple(alpha=False) # type: ignore
159
+ return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%})'
160
+ else:
161
+ h, s, li, a = self.as_hsl_tuple(alpha=True) # type: ignore
162
+ return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%}, {round(a, 2)})'
163
+
164
+ def as_hsl_tuple(self, *, alpha: Optional[bool] = None) -> HslColorTuple:
165
+ """
166
+ Color as an HSL or HSLA tuple, e.g. hue, saturation, lightness and optionally alpha; all elements are in
167
+ the range 0 to 1.
168
+
169
+ NOTE: this is HSL as used in HTML and most other places, not HLS as used in python's colorsys.
170
+
171
+ :param alpha: whether to include the alpha channel, options are
172
+ None - (default) include alpha only if it's set (e.g. not None)
173
+ True - always include alpha,
174
+ False - always omit alpha,
175
+ """
176
+ h, l, s = rgb_to_hls(self._rgba.r, self._rgba.g, self._rgba.b)
177
+ if alpha is None:
178
+ if self._rgba.alpha is None:
179
+ return h, s, l
180
+ else:
181
+ return h, s, l, self._alpha_float()
182
+ if alpha:
183
+ return h, s, l, self._alpha_float()
184
+ else:
185
+ # alpha is False
186
+ return h, s, l
187
+
188
+ def _alpha_float(self) -> float:
189
+ return 1 if self._rgba.alpha is None else self._rgba.alpha
190
+
191
+ @classmethod
192
+ def __get_validators__(cls) -> 'CallableGenerator':
193
+ yield cls
194
+
195
+ def __str__(self) -> str:
196
+ return self.as_named(fallback=True)
197
+
198
+ def __repr_args__(self) -> 'ReprArgs':
199
+ return [(None, self.as_named(fallback=True))] + [('rgb', self.as_rgb_tuple())] # type: ignore
200
+
201
+ def __eq__(self, other: Any) -> bool:
202
+ return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple()
203
+
204
+ def __hash__(self) -> int:
205
+ return hash(self.as_rgb_tuple())
206
+
207
+
208
+ def parse_tuple(value: Tuple[Any, ...]) -> RGBA:
209
+ """
210
+ Parse a tuple or list as a color.
211
+ """
212
+ if len(value) == 3:
213
+ r, g, b = (parse_color_value(v) for v in value)
214
+ return RGBA(r, g, b, None)
215
+ elif len(value) == 4:
216
+ r, g, b = (parse_color_value(v) for v in value[:3])
217
+ return RGBA(r, g, b, parse_float_alpha(value[3]))
218
+ else:
219
+ raise ColorError(reason='tuples must have length 3 or 4')
220
+
221
+
222
+ def parse_str(value: str) -> RGBA:
223
+ """
224
+ Parse a string to an RGBA tuple, trying the following formats (in this order):
225
+ * named color, see COLORS_BY_NAME below
226
+ * hex short eg. `<prefix>fff` (prefix can be `#`, `0x` or nothing)
227
+ * hex long eg. `<prefix>ffffff` (prefix can be `#`, `0x` or nothing)
228
+ * `rgb(<r>, <g>, <b>) `
229
+ * `rgba(<r>, <g>, <b>, <a>)`
230
+ """
231
+ value_lower = value.lower()
232
+ try:
233
+ r, g, b = COLORS_BY_NAME[value_lower]
234
+ except KeyError:
235
+ pass
236
+ else:
237
+ return ints_to_rgba(r, g, b, None)
238
+
239
+ m = re.fullmatch(r_hex_short, value_lower)
240
+ if m:
241
+ *rgb, a = m.groups()
242
+ r, g, b = (int(v * 2, 16) for v in rgb)
243
+ if a:
244
+ alpha: Optional[float] = int(a * 2, 16) / 255
245
+ else:
246
+ alpha = None
247
+ return ints_to_rgba(r, g, b, alpha)
248
+
249
+ m = re.fullmatch(r_hex_long, value_lower)
250
+ if m:
251
+ *rgb, a = m.groups()
252
+ r, g, b = (int(v, 16) for v in rgb)
253
+ if a:
254
+ alpha = int(a, 16) / 255
255
+ else:
256
+ alpha = None
257
+ return ints_to_rgba(r, g, b, alpha)
258
+
259
+ m = re.fullmatch(r_rgb, value_lower)
260
+ if m:
261
+ return ints_to_rgba(*m.groups(), None) # type: ignore
262
+
263
+ m = re.fullmatch(r_rgba, value_lower)
264
+ if m:
265
+ return ints_to_rgba(*m.groups()) # type: ignore
266
+
267
+ m = re.fullmatch(r_hsl, value_lower)
268
+ if m:
269
+ h, h_units, s, l_ = m.groups()
270
+ return parse_hsl(h, h_units, s, l_)
271
+
272
+ m = re.fullmatch(r_hsla, value_lower)
273
+ if m:
274
+ h, h_units, s, l_, a = m.groups()
275
+ return parse_hsl(h, h_units, s, l_, parse_float_alpha(a))
276
+
277
+ raise ColorError(reason='string not recognised as a valid color')
278
+
279
+
280
+ def ints_to_rgba(r: Union[int, str], g: Union[int, str], b: Union[int, str], alpha: Optional[float]) -> RGBA:
281
+ return RGBA(parse_color_value(r), parse_color_value(g), parse_color_value(b), parse_float_alpha(alpha))
282
+
283
+
284
+ def parse_color_value(value: Union[int, str], max_val: int = 255) -> float:
285
+ """
286
+ Parse a value checking it's a valid int in the range 0 to max_val and divide by max_val to give a number
287
+ in the range 0 to 1
288
+ """
289
+ try:
290
+ color = float(value)
291
+ except ValueError:
292
+ raise ColorError(reason='color values must be a valid number')
293
+ if 0 <= color <= max_val:
294
+ return color / max_val
295
+ else:
296
+ raise ColorError(reason=f'color values must be in the range 0 to {max_val}')
297
+
298
+
299
+ def parse_float_alpha(value: Union[None, str, float, int]) -> Optional[float]:
300
+ """
301
+ Parse a value checking it's a valid float in the range 0 to 1
302
+ """
303
+ if value is None:
304
+ return None
305
+ try:
306
+ if isinstance(value, str) and value.endswith('%'):
307
+ alpha = float(value[:-1]) / 100
308
+ else:
309
+ alpha = float(value)
310
+ except ValueError:
311
+ raise ColorError(reason='alpha values must be a valid float')
312
+
313
+ if almost_equal_floats(alpha, 1):
314
+ return None
315
+ elif 0 <= alpha <= 1:
316
+ return alpha
317
+ else:
318
+ raise ColorError(reason='alpha values must be in the range 0 to 1')
319
+
320
+
321
+ def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: Optional[float] = None) -> RGBA:
322
+ """
323
+ Parse raw hue, saturation, lightness and alpha values and convert to RGBA.
324
+ """
325
+ s_value, l_value = parse_color_value(sat, 100), parse_color_value(light, 100)
326
+
327
+ h_value = float(h)
328
+ if h_units in {None, 'deg'}:
329
+ h_value = h_value % 360 / 360
330
+ elif h_units == 'rad':
331
+ h_value = h_value % rads / rads
332
+ else:
333
+ # turns
334
+ h_value = h_value % 1
335
+
336
+ r, g, b = hls_to_rgb(h_value, l_value, s_value)
337
+ return RGBA(r, g, b, alpha)
338
+
339
+
340
+ def float_to_255(c: float) -> int:
341
+ return int(round(c * 255))
342
+
343
+
344
+ COLORS_BY_NAME = {
345
+ 'aliceblue': (240, 248, 255),
346
+ 'antiquewhite': (250, 235, 215),
347
+ 'aqua': (0, 255, 255),
348
+ 'aquamarine': (127, 255, 212),
349
+ 'azure': (240, 255, 255),
350
+ 'beige': (245, 245, 220),
351
+ 'bisque': (255, 228, 196),
352
+ 'black': (0, 0, 0),
353
+ 'blanchedalmond': (255, 235, 205),
354
+ 'blue': (0, 0, 255),
355
+ 'blueviolet': (138, 43, 226),
356
+ 'brown': (165, 42, 42),
357
+ 'burlywood': (222, 184, 135),
358
+ 'cadetblue': (95, 158, 160),
359
+ 'chartreuse': (127, 255, 0),
360
+ 'chocolate': (210, 105, 30),
361
+ 'coral': (255, 127, 80),
362
+ 'cornflowerblue': (100, 149, 237),
363
+ 'cornsilk': (255, 248, 220),
364
+ 'crimson': (220, 20, 60),
365
+ 'cyan': (0, 255, 255),
366
+ 'darkblue': (0, 0, 139),
367
+ 'darkcyan': (0, 139, 139),
368
+ 'darkgoldenrod': (184, 134, 11),
369
+ 'darkgray': (169, 169, 169),
370
+ 'darkgreen': (0, 100, 0),
371
+ 'darkgrey': (169, 169, 169),
372
+ 'darkkhaki': (189, 183, 107),
373
+ 'darkmagenta': (139, 0, 139),
374
+ 'darkolivegreen': (85, 107, 47),
375
+ 'darkorange': (255, 140, 0),
376
+ 'darkorchid': (153, 50, 204),
377
+ 'darkred': (139, 0, 0),
378
+ 'darksalmon': (233, 150, 122),
379
+ 'darkseagreen': (143, 188, 143),
380
+ 'darkslateblue': (72, 61, 139),
381
+ 'darkslategray': (47, 79, 79),
382
+ 'darkslategrey': (47, 79, 79),
383
+ 'darkturquoise': (0, 206, 209),
384
+ 'darkviolet': (148, 0, 211),
385
+ 'deeppink': (255, 20, 147),
386
+ 'deepskyblue': (0, 191, 255),
387
+ 'dimgray': (105, 105, 105),
388
+ 'dimgrey': (105, 105, 105),
389
+ 'dodgerblue': (30, 144, 255),
390
+ 'firebrick': (178, 34, 34),
391
+ 'floralwhite': (255, 250, 240),
392
+ 'forestgreen': (34, 139, 34),
393
+ 'fuchsia': (255, 0, 255),
394
+ 'gainsboro': (220, 220, 220),
395
+ 'ghostwhite': (248, 248, 255),
396
+ 'gold': (255, 215, 0),
397
+ 'goldenrod': (218, 165, 32),
398
+ 'gray': (128, 128, 128),
399
+ 'green': (0, 128, 0),
400
+ 'greenyellow': (173, 255, 47),
401
+ 'grey': (128, 128, 128),
402
+ 'honeydew': (240, 255, 240),
403
+ 'hotpink': (255, 105, 180),
404
+ 'indianred': (205, 92, 92),
405
+ 'indigo': (75, 0, 130),
406
+ 'ivory': (255, 255, 240),
407
+ 'khaki': (240, 230, 140),
408
+ 'lavender': (230, 230, 250),
409
+ 'lavenderblush': (255, 240, 245),
410
+ 'lawngreen': (124, 252, 0),
411
+ 'lemonchiffon': (255, 250, 205),
412
+ 'lightblue': (173, 216, 230),
413
+ 'lightcoral': (240, 128, 128),
414
+ 'lightcyan': (224, 255, 255),
415
+ 'lightgoldenrodyellow': (250, 250, 210),
416
+ 'lightgray': (211, 211, 211),
417
+ 'lightgreen': (144, 238, 144),
418
+ 'lightgrey': (211, 211, 211),
419
+ 'lightpink': (255, 182, 193),
420
+ 'lightsalmon': (255, 160, 122),
421
+ 'lightseagreen': (32, 178, 170),
422
+ 'lightskyblue': (135, 206, 250),
423
+ 'lightslategray': (119, 136, 153),
424
+ 'lightslategrey': (119, 136, 153),
425
+ 'lightsteelblue': (176, 196, 222),
426
+ 'lightyellow': (255, 255, 224),
427
+ 'lime': (0, 255, 0),
428
+ 'limegreen': (50, 205, 50),
429
+ 'linen': (250, 240, 230),
430
+ 'magenta': (255, 0, 255),
431
+ 'maroon': (128, 0, 0),
432
+ 'mediumaquamarine': (102, 205, 170),
433
+ 'mediumblue': (0, 0, 205),
434
+ 'mediumorchid': (186, 85, 211),
435
+ 'mediumpurple': (147, 112, 219),
436
+ 'mediumseagreen': (60, 179, 113),
437
+ 'mediumslateblue': (123, 104, 238),
438
+ 'mediumspringgreen': (0, 250, 154),
439
+ 'mediumturquoise': (72, 209, 204),
440
+ 'mediumvioletred': (199, 21, 133),
441
+ 'midnightblue': (25, 25, 112),
442
+ 'mintcream': (245, 255, 250),
443
+ 'mistyrose': (255, 228, 225),
444
+ 'moccasin': (255, 228, 181),
445
+ 'navajowhite': (255, 222, 173),
446
+ 'navy': (0, 0, 128),
447
+ 'oldlace': (253, 245, 230),
448
+ 'olive': (128, 128, 0),
449
+ 'olivedrab': (107, 142, 35),
450
+ 'orange': (255, 165, 0),
451
+ 'orangered': (255, 69, 0),
452
+ 'orchid': (218, 112, 214),
453
+ 'palegoldenrod': (238, 232, 170),
454
+ 'palegreen': (152, 251, 152),
455
+ 'paleturquoise': (175, 238, 238),
456
+ 'palevioletred': (219, 112, 147),
457
+ 'papayawhip': (255, 239, 213),
458
+ 'peachpuff': (255, 218, 185),
459
+ 'peru': (205, 133, 63),
460
+ 'pink': (255, 192, 203),
461
+ 'plum': (221, 160, 221),
462
+ 'powderblue': (176, 224, 230),
463
+ 'purple': (128, 0, 128),
464
+ 'red': (255, 0, 0),
465
+ 'rosybrown': (188, 143, 143),
466
+ 'royalblue': (65, 105, 225),
467
+ 'saddlebrown': (139, 69, 19),
468
+ 'salmon': (250, 128, 114),
469
+ 'sandybrown': (244, 164, 96),
470
+ 'seagreen': (46, 139, 87),
471
+ 'seashell': (255, 245, 238),
472
+ 'sienna': (160, 82, 45),
473
+ 'silver': (192, 192, 192),
474
+ 'skyblue': (135, 206, 235),
475
+ 'slateblue': (106, 90, 205),
476
+ 'slategray': (112, 128, 144),
477
+ 'slategrey': (112, 128, 144),
478
+ 'snow': (255, 250, 250),
479
+ 'springgreen': (0, 255, 127),
480
+ 'steelblue': (70, 130, 180),
481
+ 'tan': (210, 180, 140),
482
+ 'teal': (0, 128, 128),
483
+ 'thistle': (216, 191, 216),
484
+ 'tomato': (255, 99, 71),
485
+ 'turquoise': (64, 224, 208),
486
+ 'violet': (238, 130, 238),
487
+ 'wheat': (245, 222, 179),
488
+ 'white': (255, 255, 255),
489
+ 'whitesmoke': (245, 245, 245),
490
+ 'yellow': (255, 255, 0),
491
+ 'yellowgreen': (154, 205, 50),
492
+ }
493
+
494
+ COLORS_BY_VALUE = {v: k for k, v in COLORS_BY_NAME.items()}
@@ -0,0 +1,191 @@
1
+ import json
2
+ from enum import Enum
3
+ from typing import TYPE_CHECKING, Any, Callable, Dict, ForwardRef, Optional, Tuple, Type, Union
4
+
5
+ from typing_extensions import Literal, Protocol
6
+
7
+ from pboot_validator.v1.typing import AnyArgTCallable, AnyCallable
8
+ from pboot_validator.v1.utils import GetterDict
9
+ from pboot_validator.v1.version import compiled
10
+
11
+ if TYPE_CHECKING:
12
+ from typing import overload
13
+
14
+ from pboot_validator.v1.fields import ModelField
15
+ from pboot_validator.v1.main import BaseModel
16
+
17
+ ConfigType = Type['BaseConfig']
18
+
19
+ class SchemaExtraCallable(Protocol):
20
+ @overload
21
+ def __call__(self, schema: Dict[str, Any]) -> None:
22
+ pass
23
+
24
+ @overload
25
+ def __call__(self, schema: Dict[str, Any], model_class: Type[BaseModel]) -> None:
26
+ pass
27
+
28
+ else:
29
+ SchemaExtraCallable = Callable[..., None]
30
+
31
+ __all__ = 'BaseConfig', 'ConfigDict', 'get_config', 'Extra', 'inherit_config', 'prepare_config'
32
+
33
+
34
+ class Extra(str, Enum):
35
+ allow = 'allow'
36
+ ignore = 'ignore'
37
+ forbid = 'forbid'
38
+
39
+
40
+ # https://github.com/cython/cython/issues/4003
41
+ # Fixed in Cython 3 and Pydantic v1 won't support Cython 3.
42
+ # Pydantic v2 doesn't depend on Cython at all.
43
+ if not compiled:
44
+ from typing_extensions import TypedDict
45
+
46
+ class ConfigDict(TypedDict, total=False):
47
+ title: Optional[str]
48
+ anystr_lower: bool
49
+ anystr_strip_whitespace: bool
50
+ min_anystr_length: int
51
+ max_anystr_length: Optional[int]
52
+ validate_all: bool
53
+ extra: Extra
54
+ allow_mutation: bool
55
+ frozen: bool
56
+ allow_population_by_field_name: bool
57
+ use_enum_values: bool
58
+ fields: Dict[str, Union[str, Dict[str, str]]]
59
+ validate_assignment: bool
60
+ error_msg_templates: Dict[str, str]
61
+ arbitrary_types_allowed: bool
62
+ orm_mode: bool
63
+ getter_dict: Type[GetterDict]
64
+ alias_generator: Optional[Callable[[str], str]]
65
+ keep_untouched: Tuple[type, ...]
66
+ schema_extra: Union[Dict[str, object], 'SchemaExtraCallable']
67
+ json_loads: Callable[[str], object]
68
+ json_dumps: AnyArgTCallable[str]
69
+ json_encoders: Dict[Type[object], AnyCallable]
70
+ underscore_attrs_are_private: bool
71
+ allow_inf_nan: bool
72
+ copy_on_model_validation: Literal['none', 'deep', 'shallow']
73
+ # whether dataclass `__post_init__` should be run after validation
74
+ post_init_call: Literal['before_validation', 'after_validation']
75
+
76
+ else:
77
+ ConfigDict = dict # type: ignore
78
+
79
+
80
+ class BaseConfig:
81
+ title: Optional[str] = None
82
+ anystr_lower: bool = False
83
+ anystr_upper: bool = False
84
+ anystr_strip_whitespace: bool = False
85
+ min_anystr_length: int = 0
86
+ max_anystr_length: Optional[int] = None
87
+ validate_all: bool = False
88
+ extra: Extra = Extra.ignore
89
+ allow_mutation: bool = True
90
+ frozen: bool = False
91
+ allow_population_by_field_name: bool = False
92
+ use_enum_values: bool = False
93
+ fields: Dict[str, Union[str, Dict[str, str]]] = {}
94
+ validate_assignment: bool = False
95
+ error_msg_templates: Dict[str, str] = {}
96
+ arbitrary_types_allowed: bool = False
97
+ orm_mode: bool = False
98
+ getter_dict: Type[GetterDict] = GetterDict
99
+ alias_generator: Optional[Callable[[str], str]] = None
100
+ keep_untouched: Tuple[type, ...] = ()
101
+ schema_extra: Union[Dict[str, Any], 'SchemaExtraCallable'] = {}
102
+ json_loads: Callable[[str], Any] = json.loads
103
+ json_dumps: Callable[..., str] = json.dumps
104
+ json_encoders: Dict[Union[Type[Any], str, ForwardRef], AnyCallable] = {}
105
+ underscore_attrs_are_private: bool = False
106
+ allow_inf_nan: bool = True
107
+
108
+ # whether inherited models as fields should be reconstructed as base model,
109
+ # and whether such a copy should be shallow or deep
110
+ copy_on_model_validation: Literal['none', 'deep', 'shallow'] = 'shallow'
111
+
112
+ # whether `Union` should check all allowed types before even trying to coerce
113
+ smart_union: bool = False
114
+ # whether dataclass `__post_init__` should be run before or after validation
115
+ post_init_call: Literal['before_validation', 'after_validation'] = 'before_validation'
116
+
117
+ @classmethod
118
+ def get_field_info(cls, name: str) -> Dict[str, Any]:
119
+ """
120
+ Get properties of FieldInfo from the `fields` property of the config class.
121
+ """
122
+
123
+ fields_value = cls.fields.get(name)
124
+
125
+ if isinstance(fields_value, str):
126
+ field_info: Dict[str, Any] = {'alias': fields_value}
127
+ elif isinstance(fields_value, dict):
128
+ field_info = fields_value
129
+ else:
130
+ field_info = {}
131
+
132
+ if 'alias' in field_info:
133
+ field_info.setdefault('alias_priority', 2)
134
+
135
+ if field_info.get('alias_priority', 0) <= 1 and cls.alias_generator:
136
+ alias = cls.alias_generator(name)
137
+ if not isinstance(alias, str):
138
+ raise TypeError(f'Config.alias_generator must return str, not {alias.__class__}')
139
+ field_info.update(alias=alias, alias_priority=1)
140
+ return field_info
141
+
142
+ @classmethod
143
+ def prepare_field(cls, field: 'ModelField') -> None:
144
+ """
145
+ Optional hook to check or modify fields during model creation.
146
+ """
147
+ pass
148
+
149
+
150
+ def get_config(config: Union[ConfigDict, Type[object], None]) -> Type[BaseConfig]:
151
+ if config is None:
152
+ return BaseConfig
153
+
154
+ else:
155
+ config_dict = (
156
+ config
157
+ if isinstance(config, dict)
158
+ else {k: getattr(config, k) for k in dir(config) if not k.startswith('__')}
159
+ )
160
+
161
+ class Config(BaseConfig):
162
+ ...
163
+
164
+ for k, v in config_dict.items():
165
+ setattr(Config, k, v)
166
+ return Config
167
+
168
+
169
+ def inherit_config(self_config: 'ConfigType', parent_config: 'ConfigType', **namespace: Any) -> 'ConfigType':
170
+ if not self_config:
171
+ base_classes: Tuple['ConfigType', ...] = (parent_config,)
172
+ elif self_config == parent_config:
173
+ base_classes = (self_config,)
174
+ else:
175
+ base_classes = self_config, parent_config
176
+
177
+ namespace['json_encoders'] = {
178
+ **getattr(parent_config, 'json_encoders', {}),
179
+ **getattr(self_config, 'json_encoders', {}),
180
+ **namespace.get('json_encoders', {}),
181
+ }
182
+
183
+ return type('Config', base_classes, namespace)
184
+
185
+
186
+ def prepare_config(config: Type[BaseConfig], cls_name: str) -> None:
187
+ if not isinstance(config.extra, Extra):
188
+ try:
189
+ config.extra = Extra(config.extra)
190
+ except ValueError:
191
+ raise ValueError(f'"{cls_name}": {config.extra} is not a valid value for "extra"')