-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvtjson.py
2921 lines (2462 loc) · 85 KB
/
vtjson.py
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import datetime
import ipaddress
import math
import pathlib
import re
import sys
import types
import typing
import urllib.parse
import warnings
from collections.abc import Sequence, Set, Sized
from dataclasses import dataclass
from typing import (
Any,
Callable,
Container,
Generic,
Mapping,
Type,
TypeVar,
Union,
cast,
overload,
)
try:
from typing import Literal
supports_Literal = True
except ImportError:
supports_Literal = False
if hasattr(typing, "is_typeddict"):
supports_TypedDict = True
else:
supports_TypedDict = False
try:
from typing import NotRequired, Required
supports_NotRequired = True
except ImportError:
supports_NotRequired = False
try:
from typing import Annotated
supports_Annotated = True
except ImportError:
supports_Annotated = False
if hasattr(typing, "get_origin"):
supports_Generics = True
else:
supports_Generics = False
try:
Sequence[str]
supports_Generic_ABC = True
except Exception:
supports_Generic_ABC = False
try:
typing.get_type_hints(int, include_extras=True)
supports_structural = True
except Exception:
supports_structural = False
try:
from types import UnionType
supports_UnionType = True
except Exception:
supports_UnionType = False
if sys.version_info >= (3, 8):
from typing import Protocol
else:
from typing_extensions import (
Protocol,
)
import dns.resolver
import email_validator
import idna
def safe_cast(schema: Type[T], obj: Any) -> T:
"""
Validates the given object against the given schema and changes its type
accordingly.
:param schema: the given schema
:param obj: the object to be validated
:return: the validated object with its type changed
:raises ValidationError: exception thrown when the object does not
validate; the exception message contains an explanation about what went
wrong
:raises SchemaError: exception thrown when the schema definition is found
to contain an error
"""
validate(schema, obj)
return cast(T, obj)
class compiled_schema:
"""
The result of compiling a schema. A :py:class:`compiled_schema` is
produced by the factory function :py:func:`vtjson.compile`.
"""
def __validate__(
self,
obj: object,
name: str,
strict: bool,
subs: Mapping[str, object],
) -> str:
"""
Validates the given object against the given schema.
:param schema: the given schema
:param obj: the object to be validated
:param name: common name for the object to be validated; used in
non-validation messages
:param strict: indicates whether or not the object being validated is
allowed to have keys/entries which are not in the schema
:param subs: a dictionary whose keys are labels and whose values are
substitution schemas for schemas with those labels
:return: an empty string if validation succeeds; otherwise an
explanation about what went wrong
"""
return ""
class wrapper:
"""
Base class for schemas that refer to other schemas.
Handling such schemas is somewhat delicate since `vtjson` allows them to
be recursive.
"""
def __compile__(
self, _deferred_compiles: _mapping | None = None
) -> compiled_schema:
"""
Compiles a schema.
:param _deferred_compiles: an opaque data structure used for handling
recursive schemas; it should be passed unmodifed to any internal
invocations of :py:func:`vtjson._compile` or
:py:meth:`vtjson.wrapper.__compile__`
:raises SchemaError: exception thrown when the schema definition is
found to contain an error
"""
return anything()
class comparable(Protocol):
"""
Base class for objects that are comparable with each other.
"""
def __eq__(self, x: Any) -> bool: ...
def __lt__(self, x: Any) -> bool: ...
def __le__(self, x: Any) -> bool: ...
def __gt__(self, x: Any) -> bool: ...
def __ge__(self, x: Any) -> bool: ...
HAS_MAGIC = True
try:
import magic as magic_
except Exception:
HAS_MAGIC = False
class ValidationError(Exception):
"""
Raised if validation fails. The associated message explains what went
wrong.
"""
pass
class SchemaError(Exception):
"""
Raised if a schema contains an error.
"""
pass
__version__ = "2.2.4"
@dataclass
class Apply:
"""
Modifies the treatement of the previous arguments in an `Annotated` schema.
:param skip_first: if `True` do not use the first argument (the Python
type annotation) in an `Annotated` construct for validation because this
is already covered by the other arguments
:param name: apply the corresponding :py:class:`vtjson.set_name` command
to the previous arguments
:param labels: apply the corresponding :py:class:`vtjson.set_label`
command to the previous arguments
"""
skip_first: bool | None = None
name: str | None = None
labels: Sequence[str] | None = None
def __call__(self, schemas: tuple[object, ...]) -> object:
if len(schemas) == 0:
raise SchemaError("Called Apply with an empty tuple")
if self.skip_first:
schemas = schemas[1:]
if len(schemas) == 0:
raise SchemaError("Called Apply with an empty tuple")
if len(schemas) == 1:
ret = schemas[0]
else:
ret = intersect(*schemas)
if self.labels is not None:
ret = set_label(ret, *self.labels)
if self.name is not None:
ret = set_name(ret, self.name)
return ret
skip_first = Apply(skip_first=True)
_dns_resolver: dns.resolver.Resolver | None = None
def _generic_name(origin: type, args: tuple[object, ...]) -> str:
def to_name(c: object) -> str:
if hasattr(c, "__name__"):
return str(c.__name__)
else:
return str(c)
return to_name(origin) + "[" + ",".join([to_name(arg) for arg in args]) + "]"
def _get_type_hints(schema: object) -> dict[str, object]:
if not supports_structural:
raise SchemaError(
"Structural subtyping in not supported in this " "Python version"
)
if isinstance(schema, type) and hasattr(schema, "__annotations__"):
type_hints = typing.get_type_hints(schema, include_extras=True)
else:
raise SchemaError("The schema does not have type hints")
return type_hints
def _to_dict(
type_hints: Mapping[str, object], total: bool = True
) -> dict[optional_key[str], object]:
d: dict[optional_key[str], object] = {}
if not supports_Generics:
raise SchemaError("Generic types are not supported")
for k, v in type_hints.items():
v_ = v
k_ = optional_key(k, _optional=False)
value_type = typing.get_origin(v)
if supports_NotRequired and value_type in (Required, NotRequired):
v_ = typing.get_args(v)[0]
if total and supports_NotRequired and value_type == NotRequired:
k_ = optional_key(k)
elif not total and (not supports_NotRequired or value_type != Required):
k_ = optional_key(k)
d[k_] = v_
return d
def _get_dns_resolver() -> dns.resolver.Resolver:
global _dns_resolver
if _dns_resolver is not None:
return _dns_resolver
_dns_resolver = dns.resolver.Resolver()
_dns_resolver.cache = dns.resolver.LRUCache()
_dns_resolver.timeout = 10
_dns_resolver.lifetime = 10
return _dns_resolver
def _c(s: object) -> str:
ss = str(s)
if len(ss) > 0:
c = ss[-1]
else:
c = ""
if len(ss) < 120:
ret = ss
else:
ret = f"{ss[:99]}...[TRUNCATED]..."
if not isinstance(s, str) and c in r"])}":
ret += c
if isinstance(s, str):
return repr(ret)
else:
return ret
T = TypeVar("T")
@overload
def _canonize_key(key: StringKeyType) -> optional_key[str]: ...
@overload
def _canonize_key(key: object) -> object: ...
def _canonize_key(key: object) -> object:
if isinstance(key, str):
if len(key) > 0 and key[-1] == "?":
if not (len(key) > 2 and key[-2] == "\\"):
return optional_key(key[:-1])
else:
return optional_key(key[:-2] + "?", _optional=False)
else:
return optional_key(key, _optional=False)
return key
def _wrong_type_message(
obj: object,
name: str,
type_name: str,
explanation: str | None = None,
skip_value: bool = False,
) -> str:
if not skip_value:
message = f"{name} (value:{_c(obj)}) is not of type '{type_name}'"
else:
message = f"{name} is not of type '{type_name}'"
if explanation is not None:
message += f": {explanation}"
return message
class _validate_meta(type):
__schema__: object
__strict__: bool
__subs__: Mapping[str, object]
__dbg__: bool
def __instancecheck__(cls, obj: object) -> bool:
valid = _validate(
cls.__schema__, obj, "object", strict=cls.__strict__, subs=cls.__subs__
)
if cls.__dbg__ and valid != "":
print(f"DEBUG: {valid}")
return valid == ""
def make_type(
schema: object,
name: str | None = None,
strict: bool = True,
debug: bool = False,
subs: Mapping[str, object] = {},
) -> _validate_meta:
"""
Transforms a schema into a genuine Python type.
:param schema: the given schema
:param name: sets the `__name__` attribute of the type; if it is not
supplied then `vtjson` makes an educated guess
:param strict: indicates whether or not the object being validated is
allowed to have keys/entries which are not in the schema
:param debug: print feedback on the console if validation fails
:param subs: a dictionary whose keys are labels and whose values are
substitution schemas for schemas with those labels
:raises SchemaError: exception thrown when the schema definition is found
to contain an error
"""
if name is None:
if hasattr(schema, "__name__"):
name = schema.__name__
else:
name = "schema"
return _validate_meta(
name,
(),
{
"__schema__": schema,
"__strict__": strict,
"__dbg__": debug,
"__subs__": subs,
},
)
K = TypeVar("K")
class optional_key(Generic[K]):
"""
Make a key in a Mapping schema optional. In the common case that the key
is a string, the same effect can be achieved by appending `?`. If you
absolutely positively need a non-optional string key that ends in `?`
you can quote the `?` by preceding it with a backslash.
"""
key: K
optional: bool
def __init__(self, key: K, _optional: bool = True) -> None:
"""
:param key: the key to be made optional
:param _optional: if `False` create a mandatory key; this is normally
for internal use only
"""
self.key = key
self.optional = _optional
def __eq__(self, key: object) -> bool:
if not isinstance(key, optional_key):
return False
k: object = key.key
o: object = key.optional
return (self.key, key.optional) == (k, o)
def __hash__(self) -> int:
return hash(self.key)
StringKeyType = TypeVar("StringKeyType", bound=Union[str, optional_key[str]])
class _union(compiled_schema):
schemas: list[compiled_schema]
def __init__(
self,
schemas: tuple[object, ...],
_deferred_compiles: _mapping | None = None,
) -> None:
self.schemas = [
_compile(s, _deferred_compiles=_deferred_compiles) for s in schemas
]
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
messages = []
for schema in self.schemas:
message = schema.__validate__(obj, name=name, strict=strict, subs=subs)
if message == "":
return ""
else:
messages.append(message)
return " and ".join(messages)
class union(wrapper):
"""
An object matches the schema `union(schema1, ..., schemaN)` if it matches
one of the schemas `schema1, ..., schemaN`.
"""
schemas: tuple[object, ...]
def __init__(self, *schemas: object) -> None:
"""
:param schemas: collection of schemas, one of which should match
"""
self.schemas = schemas
def __compile__(self, _deferred_compiles: _mapping | None = None) -> _union:
return _union(self.schemas, _deferred_compiles=_deferred_compiles)
class _intersect(compiled_schema):
schema: list[compiled_schema]
def __init__(
self,
schemas: tuple[object, ...],
_deferred_compiles: _mapping | None = None,
) -> None:
self.schemas = [
_compile(s, _deferred_compiles=_deferred_compiles) for s in schemas
]
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
for schema in self.schemas:
message = schema.__validate__(obj, name=name, strict=strict, subs=subs)
if message != "":
return message
return ""
class intersect(wrapper):
"""
An object matches the schema `intersect(schema1, ..., schemaN)` if it
matches all the schemas `schema1, ..., schemaN`.
"""
schemas: tuple[object, ...]
def __init__(self, *schemas: object) -> None:
"""
:param schemas: collection of schemas, all of which should match
"""
self.schemas = schemas
def __compile__(self, _deferred_compiles: _mapping | None = None) -> _intersect:
return _intersect(self.schemas, _deferred_compiles=_deferred_compiles)
class _complement(compiled_schema):
schema: compiled_schema
def __init__(
self, schema: object, _deferred_compiles: _mapping | None = None
) -> None:
self.schema = _compile(schema, _deferred_compiles=_deferred_compiles)
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
message = self.schema.__validate__(obj, name=name, strict=strict, subs=subs)
if message != "":
return ""
else:
return f"{name} does not match the complemented schema"
class complement(wrapper):
"""
An object matches the schema `complement(schema)` if it does not match
`schema`.
"""
schema: object
def __init__(self, schema: object) -> None:
"""
:param schema: the schema that should not be matched
"""
self.schema = schema
def __compile__(self, _deferred_compiles: _mapping | None = None) -> _complement:
return _complement(self.schema, _deferred_compiles=_deferred_compiles)
class _lax(compiled_schema):
schema: compiled_schema
def __init__(
self, schema: object, _deferred_compiles: _mapping | None = None
) -> None:
self.schema = _compile(schema, _deferred_compiles=_deferred_compiles)
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
return self.schema.__validate__(obj, name=name, strict=False, subs=subs)
class lax(wrapper):
"""
An object matches the schema `lax(schema)` if it matches `schema` when
validated with `strict=False`.
"""
schema: object
def __init__(self, schema: object) -> None:
"""
:param schema: schema that should be validated against with
`strict=False`
"""
self.schema = schema
def __compile__(self, _deferred_compiles: _mapping | None = None) -> _lax:
return _lax(self.schema, _deferred_compiles=_deferred_compiles)
class _strict(compiled_schema):
schema: compiled_schema
def __init__(
self, schema: object, _deferred_compiles: _mapping | None = None
) -> None:
self.schema = _compile(schema, _deferred_compiles=_deferred_compiles)
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
return self.schema.__validate__(obj, name=name, strict=True, subs=subs)
class strict(wrapper):
"""
An object matches the schema `strict(schema)` if it matches `schema` when
validated with `strict=True`.
"""
def __init__(self, schema: object) -> None:
"""
:param schema: schema that should be validated against with
`strict=True`
"""
self.schema = schema
def __compile__(self, _deferred_compiles: _mapping | None = None) -> _strict:
return _strict(self.schema, _deferred_compiles=_deferred_compiles)
class _set_label(compiled_schema):
schema: compiled_schema
labels: set[str]
debug: bool
def __init__(
self,
schema: object,
labels: set[str],
debug: bool,
_deferred_compiles: _mapping | None = None,
) -> None:
self.schema = _compile(schema, _deferred_compiles=_deferred_compiles)
self.labels = labels
self.debug = debug
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
common_labels = tuple(set(subs.keys()).intersection(self.labels))
if len(common_labels) >= 2:
raise ValidationError(
f"multiple substitutions for {name} "
f"(applicable keys:{common_labels})"
)
elif len(common_labels) == 1:
key = common_labels[0]
if self.debug:
print(f"The schema for {name} (key:{key}) was replaced")
# We have to recompile subs[key]. This seems unavoidable as it is not
# known at schema creation time.
#
# But the user can always pre-compile subs[key].
return _validate(subs[key], obj, name=name, strict=True, subs=subs)
else:
return self.schema.__validate__(obj, name=name, strict=True, subs=subs)
class set_label(wrapper):
"""
An object matches the schema `set_label(schema, label1, ..., labelN,
debug=False)` if it matches `schema`, unless the schema is replaced by a
different one via the `subs` argument to `validate`.
"""
schema: object
labels: set[str]
debug: bool
def __init__(self, schema: object, *labels: str, debug: bool = False) -> None:
"""
:param schema: the schema that will be labeled
:param labels: labels that will be attached to the schema
:param debug: it `True` print a message on the console if the schema
was changed via substitution
:raises SchemaError: exception thrown when the schema definition is
found to contain an error
"""
self.schema = schema
for L in labels:
if not isinstance(L, str):
raise SchemaError(f"The label {L} is not a string")
self.labels = set(labels)
if not isinstance(debug, bool):
raise SchemaError(f"The option {debug} is not a boolean")
self.debug = debug
def __compile__(self, _deferred_compiles: _mapping | None = None) -> _set_label:
return _set_label(
self.schema, self.labels, self.debug, _deferred_compiles=_deferred_compiles
)
class _quote(compiled_schema):
def __init__(self, schema: object) -> None:
setattr(self, "__validate__", _const(schema, strict_eq=True).__validate__)
class quote(wrapper):
"""
An object matches the schema `quote(schema)` if it is equal to `schema`.
For example the schema `str` matches strings but the schema `quote(str)`
matches the object `str`.
"""
schema: object
def __init__(self, schema: object) -> None:
"""
:param schema: the schema to be quoted
"""
self.schema = schema
def __compile__(self, _deferred_compiles: _mapping | None = None) -> _quote:
return _quote(self.schema)
class _set_name(compiled_schema):
reason: bool
schema: compiled_schema
__name__: str
def __init__(
self,
schema: object,
name: str,
reason: bool = False,
_deferred_compiles: _mapping | None = None,
) -> None:
self.schema = _compile(schema, _deferred_compiles=_deferred_compiles)
self.__name__ = name
self.reason = reason
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
message = self.schema.__validate__(obj, name=name, strict=strict, subs=subs)
if message != "":
if not self.reason:
return _wrong_type_message(obj, name, self.__name__)
else:
return _wrong_type_message(
obj, name, self.__name__, explanation=message, skip_value=True
)
return ""
class set_name(wrapper):
"""
An object matches the schema `set_name(schema, name)` if it matches `schema`,
but the `name` argument will be used in non-validation messages.
"""
reason: bool
schema: object
name: str
def __init__(self, schema: object, name: str, reason: bool = False) -> None:
"""
:param schema: the original schema
:param name: name for use in non-validation messages
:param reason: if `True` then the original non-validation message
will not be suppressed
"""
if not isinstance(name, str):
raise SchemaError(f"The name {_c(name)} is not a string")
if not isinstance(reason, bool):
raise SchemaError(
f"The parameter 'reason' (value:{repr(reason)}) is not a boolean"
)
self.schema = schema
self.name = name
self.reason = reason
def __compile__(self, _deferred_compiles: _mapping | None = None) -> _set_name:
return _set_name(
self.schema,
self.name,
reason=self.reason,
_deferred_compiles=_deferred_compiles,
)
class regex(compiled_schema):
"""
This matches the strings which match the given pattern.
"""
regex: str
fullmatch: bool
__name__: str
pattern: re.Pattern[str]
def __init__(
self,
regex: str,
name: str | None = None,
fullmatch: bool = True,
flags: int = 0,
) -> None:
"""
:param regex: the regular expression pattern
:param name: common name for the pattern that will be used in
non-validation messages
:param fullmatch: indicates whether or not the full string should be
matched
:param flags: the flags argument used when invoking `re.compile`
:raises SchemaError: exception thrown when the schema definition is
found to contain an error
"""
self.regex = regex
self.fullmatch = fullmatch
if name is not None:
if not isinstance(name, str):
raise SchemaError(f"The regex name {_c(name)} is not a string")
self.__name__ = name
else:
_flags = "" if flags == 0 else f", flags={flags}"
_fullmatch = "" if fullmatch else ", fullmatch=False"
self.__name__ = f"regex({repr(regex)}{_fullmatch}{_flags})"
try:
self.pattern = re.compile(regex, flags)
except Exception as e:
_name = f" (name: {repr(name)})" if name is not None else ""
raise SchemaError(
f"{regex}{_name} is an invalid regular expression: {str(e)}"
) from None
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
if not isinstance(obj, str):
return _wrong_type_message(obj, name, self.__name__)
try:
if self.fullmatch and self.pattern.fullmatch(obj):
return ""
elif not self.fullmatch and self.pattern.match(obj):
return ""
except Exception:
pass
return _wrong_type_message(obj, name, self.__name__)
class glob(compiled_schema):
"""
Unix style filename matching. This is implemented using
`pathlib.PurePath().match()`.
"""
pattern: str
__name__: str
def __init__(self, pattern: str, name: str | None = None) -> None:
"""
:param pattern: the wild card pattern to match
:param name: common name for the pattern that will be used in
non-validation messages
:raises SchemaError: exception thrown when the schema definition is
found to contain an error
"""
self.pattern = pattern
if name is None:
self.__name__ = f"glob({repr(pattern)})"
else:
self.__name__ = name
try:
pathlib.PurePath("").match(pattern)
except Exception as e:
_name = f" (name: {repr(name)})" if name is not None else ""
raise SchemaError(
f"{repr(pattern)}{_name} is not a valid filename pattern: {str(e)}"
) from None
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
if not isinstance(obj, str):
return _wrong_type_message(obj, name, self.__name__)
try:
if pathlib.PurePath(obj).match(self.pattern):
return ""
else:
return _wrong_type_message(obj, name, self.__name__)
except Exception as e:
return _wrong_type_message(obj, name, self.__name__, str(e))
class magic(compiled_schema):
"""
Checks if a buffer (for example a string or a byte array) has the given
mime type. This is implemented using the `python-magic` package.
"""
mime_type: str
__name__: str
def __init__(self, mime_type: str, name: str | None = None) -> None:
"""
:param mime_type: the mime type
:param name: common name to refer to this mime type
:raises SchemaError: exception thrown when the schema definition is
found to contain an error
"""
if not HAS_MAGIC:
raise SchemaError("Failed to load python-magic")
if not isinstance(mime_type, str):
raise SchemaError(f"{repr(mime_type)} is not a string")
self.mime_type = mime_type
if name is None:
self.__name__ = f"magic({repr(mime_type)})"
else:
self.__name__ = name
def __validate__(
self,
obj: object,
name: str = "object",
strict: bool = True,
subs: Mapping[str, object] = {},
) -> str:
if not isinstance(obj, (str, bytes)):
return _wrong_type_message(obj, name, self.__name__)
try:
objmime_type = magic_.from_buffer(obj, mime=True)
except Exception as e:
return _wrong_type_message(obj, name, self.__name__, str(e))
if objmime_type != self.mime_type:
return _wrong_type_message(
obj,
name,
self.__name__,
f"{repr(objmime_type)} is different from {repr(self.mime_type)}",
)
return ""
class div(compiled_schema):
"""
This matches the integers `x` such that `(x - remainder) % divisor` == 0.
"""