-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy path_schema.py
More file actions
1212 lines (938 loc) · 37.3 KB
/
_schema.py
File metadata and controls
1212 lines (938 loc) · 37.3 KB
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
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from schematics.models import Model
from schematics.types import ModelType, ListType, PolyModelType
from schematics.types.serializable import serializable
from ._arg import CMDStringArg, CMDStringArgBase, \
CMDByteArg, CMDByteArgBase, \
CMDBinaryArg, CMDBinaryArgBase, \
CMDDurationArg, CMDDurationArgBase, \
CMDDateArg, CMDDateArgBase, \
CMDDateTimeArg, CMDDateTimeArgBase, \
CMDTimeArg, CMDTimeArgBase, \
CMDUuidArg, CMDUuidArgBase, \
CMDPasswordArg, CMDPasswordArgBase, \
CMDResourceIdArg, CMDResourceIdArgBase, \
CMDResourceLocationArg, CMDResourceLocationArgBase, \
CMDBooleanArg, CMDBooleanArgBase, \
CMDIntegerArg, CMDIntegerArgBase, \
CMDInteger32Arg, CMDInteger32ArgBase, \
CMDInteger64Arg, CMDInteger64ArgBase, \
CMDFloatArg, CMDFloatArgBase, \
CMDFloat32Arg, CMDFloat32ArgBase, \
CMDFloat64Arg, CMDFloat64ArgBase, \
CMDArrayArg, CMDArrayArgBase, \
CMDObjectArg, CMDObjectArgBase, CMDObjectArgAdditionalProperties, \
CMDClsArg, CMDClsArgBase, CMDAnyTypeArg, CMDAnyTypeArgBase
from ._fields import CMDVariantField, StringType, CMDClassField, CMDBooleanField, CMDPrimitiveField, CMDDescriptionField
from ._format import CMDStringFormat, CMDIntegerFormat, CMDFloatFormat, CMDObjectFormat, CMDArrayFormat, \
CMDResourceIdFormat
from ._utils import CMDDiffLevelEnum
from utils import exceptions
import logging
import re
logger = logging.getLogger('backend')
class CMDSchemaEnumItem(Model):
arg = CMDVariantField() # value will be used when specific argument is provided
# properties as nodes
value = CMDPrimitiveField() # json value format string, support null
class Options:
serialize_when_none = False
def diff(self, old, level):
if type(self) is not type(old):
return f"Type: {type(old)} != {type(self)}"
diff = {}
if level >= CMDDiffLevelEnum.BreakingChange:
if self.value != old.value:
diff["value"] = f"{old.value} != {self.value}"
if level >= CMDDiffLevelEnum.Associate:
if self.arg != old.arg:
diff["arg"] = f"{old.arg} != {self.arg}"
return diff
class CMDSchemaEnum(Model):
# properties as tags
# properties as nodes
items = ListType(ModelType(CMDSchemaEnumItem), min_size=1)
def diff(self, old, level):
if type(self) is not type(old):
return f"Type: {type(old)} != {type(self)}"
diff = []
if level >= CMDDiffLevelEnum.BreakingChange:
# old.items should be the subset of self.items
for old_item in old.items:
matched = False
for item in self.items:
if old_item.value == item.value:
matched = True
item_diff = item.diff(old_item, level)
if item_diff:
diff.append(item_diff)
break
if not matched:
diff.append(f"MissEnumItem: {old_item.value}")
if level >= CMDDiffLevelEnum.Structure:
for item in self.items:
matched = False
for old_item in old.items:
if item.value == old_item.value:
matched = True
break
if not matched:
diff.append(f"NewEnumItem: {item.value}")
return diff
def reformat(self, **kwargs):
try:
self.items = sorted(self.items, key=lambda it: it.value)
except:
# some of the value main not support sort
pass
class CMDSchemaDefault(Model):
""" The argument value if an argument is not used """
# properties as nodes
value = CMDPrimitiveField() # json value format string, support null
def diff(self, old, level):
if type(self) is not type(old):
return f"Type: {type(old)} != {type(self)}"
diff = {}
if level >= CMDDiffLevelEnum.BreakingChange:
if self.value != old.value:
diff["value"] = f"{old.value} != {self.value}"
return diff
class CMDSchemaBase(Model):
TYPE_VALUE = None
ARG_TYPE = None
# properties as tags
read_only = CMDBooleanField(
serialized_name="readOnly",
deserialize_from="readOnly"
)
frozen = CMDBooleanField() # frozen schema will not be used
const = CMDBooleanField() # when a schema is const it's default value is not None.
# properties as nodes
default = ModelType(CMDSchemaDefault)
nullable = CMDBooleanField() # whether null value is supported
action = StringType() # distinguish identity assign and remove
# base types: "array", "boolean", "integer", "float", "object", "string",
class Options:
serialize_when_none = False
@serializable
def type(self):
return self._get_type()
def _get_type(self):
assert self.TYPE_VALUE is not None
return self.TYPE_VALUE
@classmethod
def _claim_polymorphic(cls, data):
if cls.TYPE_VALUE is None:
return False
if isinstance(data, dict):
type_value = data.get('type', None)
if type_value is not None:
typ = type_value.replace("<", " ").replace(">", " ").strip().split()[0]
return typ == cls.TYPE_VALUE
elif isinstance(data, CMDSchemaBase):
return data.TYPE_VALUE == cls.TYPE_VALUE
return False
def _diff_base(self, old, level, diff):
if level >= CMDDiffLevelEnum.BreakingChange:
if self.type != old.type:
diff["type"] = f"{old.type} != {self.type}"
if self.read_only and not old.read_only:
diff["read_only"] = f"it's read_only now."
if self.const and not old.const:
diff["const"] = f"it's const now."
if old.default:
if not self.default:
diff["default"] = f"miss default now."
else:
default_diff = self.default.diff(old.default, level)
if default_diff:
diff["default"] = default_diff
if level >= CMDDiffLevelEnum.Structure:
if (not self.read_only) != (not old.read_only):
diff["read_only"] = f"{old.read_only} != {self.read_only}"
if (not self.const) != (not old.const):
diff['const'] = f"{old.const} != {self.const}"
if self.default:
default_diff = self.default.diff(old.default, level)
if default_diff:
diff["default"] = default_diff
return diff
def diff(self, old, level):
if type(self) is not type(old):
return f"Type: {type(old)} != {type(self)}"
if self.frozen and old.frozen:
return None
diff = {}
diff = self._diff_base(old, level, diff)
return diff
def _reformat_base(self, **kwargs):
pass
def reformat(self, **kwargs):
if self.frozen:
return
self._reformat_base(**kwargs)
class CMDSchemaBaseField(PolyModelType):
def __init__(self, **kwargs):
super(CMDSchemaBaseField, self).__init__(
model_spec=CMDSchemaBase,
allow_subclasses=True,
serialize_when_none=False,
**kwargs
)
def export(self, value, format, context=None):
if value.frozen:
# frozen schema base will be ignored
return None
return super(CMDSchemaBaseField, self).export(value, format, context)
def find_model(self, data):
if self.claim_function:
kls = self.claim_function(self, data)
if not kls:
raise Exception("Input for polymorphic field did not match any model")
return kls
fallback = None
matching_classes = set()
for kls in self._get_candidates():
if issubclass(kls, CMDSchema):
continue
try:
kls_claim = kls._claim_polymorphic
except AttributeError:
if not fallback:
fallback = kls
else:
if kls_claim(data):
matching_classes.add(kls)
if not matching_classes and fallback:
return fallback
elif len(matching_classes) != 1:
raise Exception("Got ambiguous input for polymorphic field")
return matching_classes.pop()
class CMDSchema(CMDSchemaBase):
# properties as tags
name = StringType(required=True)
arg = CMDVariantField()
required = CMDBooleanField()
description = CMDDescriptionField()
skip_url_encoding = CMDBooleanField(
serialized_name="skipUrlEncoding",
deserialize_from="skipUrlEncoding",
) # used in path and query parameters
secret = CMDBooleanField()
@classmethod
def _claim_polymorphic(cls, data):
if super(CMDSchema, cls)._claim_polymorphic(data):
if isinstance(data, dict):
# distinguish with CMDSchemaBase and CMDSchema
return 'name' in data
else:
return isinstance(data, CMDSchema)
return False
def _diff(self, old, level, diff):
if level >= CMDDiffLevelEnum.BreakingChange:
if self.name != old.name:
diff["name"] = f"{old.name} != {self.name}"
if self.required and not old.required:
diff["required"] = f"it's required now."
if (not self.skip_url_encoding) != (not old.skip_url_encoding): # None should be same as false
diff["skip_url_encoding"] = f"{old.skip_url_encoding} != {self.skip_url_encoding}"
if not self.secret and old.secret:
diff["secret"] = f"it's not secret property now."
if level >= CMDDiffLevelEnum.Structure:
if (not self.required) != (not old.required):
diff["required"] = f"{old.required} != {self.required}"
if self.secret != old.secret:
diff["secret"] = f"{old.secret} != {self.secret}"
if level >= CMDDiffLevelEnum.Associate:
if self.arg != old.arg:
diff["arg"] = f"{old.arg} != {self.arg}"
if level >= CMDDiffLevelEnum.All:
if self.description != old.description:
diff["description"] = f"'{old.description}' != '{self.description}'"
return diff
def diff(self, old, level):
if type(self) is not type(old):
return f"Type: {type(old)} != {type(self)}"
if self.frozen and old.frozen:
return None
diff = {}
diff = self._diff_base(old, level, diff)
diff = self._diff(old, level, diff)
return diff
def _reformat(self, **kwargs):
pass
def reformat(self, **kwargs):
if self.frozen:
return
self._reformat_base(**kwargs)
self._reformat(**kwargs)
class CMDSchemaField(PolyModelType):
def __init__(self, **kwargs):
super(CMDSchemaField, self).__init__(
model_spec=CMDSchema,
allow_subclasses=True,
serialize_when_none=False,
**kwargs
)
def export(self, value, format, context=None):
if value.frozen:
# frozen schema base will be ignored
return None
return super(CMDSchemaField, self).export(value, format, context)
# cls
class CMDClsSchemaBase(CMDSchemaBase):
ARG_TYPE = CMDClsArgBase
_type = StringType(
deserialize_from='type',
serialized_name='type',
required=True
)
def _get_type(self):
return self._type
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.implement = None
@classmethod
def _claim_polymorphic(cls, data):
if isinstance(data, dict):
type_value = data.get('type', None)
if type_value is not None and type_value.startswith("@"):
return True
elif isinstance(data, CMDClsSchemaBase):
return True
return False
@classmethod
def build_from_schema_base(cls, schema_base, implement):
assert isinstance(schema_base, (CMDObjectSchemaBase, CMDArraySchemaBase))
assert getattr(schema_base, 'cls', None)
cls_schema = cls()
cls_schema._type = f"@{schema_base.cls}"
cls_schema.read_only = schema_base.read_only
cls_schema.frozen = schema_base.frozen
cls_schema.const = schema_base.const
cls_schema.default = schema_base.default
cls_schema.implement = implement
return cls_schema
def get_unwrapped(self, **kwargs):
if self.implement is None:
return
assert isinstance(self.implement, CMDSchemaBase)
if isinstance(self.implement, CMDObjectSchemaBase):
cls = CMDObjectSchema if isinstance(self, CMDClsSchema) else CMDObjectSchemaBase
elif isinstance(self.implement, CMDArraySchemaBase):
cls = CMDArraySchema if isinstance(self, CMDClsSchema) else CMDArraySchemaBase
else:
raise NotImplementedError()
data = {k: v for k, v in self.implement.to_native().items() if k in cls._schema.valid_input_keys}
data.update(kwargs)
# uninherent read_only
uninherent = {
"read_only": self.read_only,
}
data.update(uninherent)
unwrapped = cls(data)
return unwrapped
class CMDClsSchema(CMDClsSchemaBase, CMDSchema):
ARG_TYPE = CMDClsArg
# properties as tags
client_flatten = CMDBooleanField(
serialized_name="clientFlatten",
deserialize_from="clientFlatten"
)
def _diff(self, old, level, diff):
# TODO: Handle Cls Schema compare with other Schema classes
diff = super(CMDClsSchema, self)._diff(old, level, diff)
if level >= CMDDiffLevelEnum.BreakingChange:
if (not self.client_flatten) != (not old.client_flatten):
diff["client_flatten"] = f"from {old.client_flatten} to {self.client_flatten}"
return diff
@classmethod
def build_from_schema(cls, schema, implement):
assert isinstance(schema, (CMDObjectSchema, CMDArraySchema))
cls_schema = cls.build_from_schema_base(schema, implement)
cls_schema.name = schema.name
cls_schema.arg = schema.arg
cls_schema.required = schema.required
cls_schema.description = schema.description
cls_schema.skip_url_encoding = schema.skip_url_encoding
if isinstance(schema, CMDObjectSchema):
cls_schema.client_flatten = schema.client_flatten
return cls_schema
def get_unwrapped(self, **kwargs):
uninherent = {
"name": self.name,
"arg": self.arg,
"required": self.required,
"description": self.description,
"skip_url_encoding": self.skip_url_encoding,
}
if isinstance(self.implement, CMDObjectSchema):
uninherent["client_flatten"] = self.client_flatten
uninherent.update(kwargs)
return super().get_unwrapped(**uninherent)
# string
class CMDStringSchemaBase(CMDSchemaBase):
TYPE_VALUE = "string"
ARG_TYPE = CMDStringArgBase
fmt = ModelType(
CMDStringFormat,
serialized_name='format',
deserialize_from='format'
)
enum = ModelType(CMDSchemaEnum)
def _diff_base(self, old, level, diff):
diff = super(CMDStringSchemaBase, self)._diff_base(old, level, diff)
fmt_diff = _diff_fmt(self.fmt, old.fmt, level)
if fmt_diff:
diff["fmt"] = fmt_diff
enum_diff = _diff_enum(self.enum, old.enum, level)
if enum_diff:
diff["enum"] = enum_diff
return diff
def _reformat_base(self, **kwargs):
super()._reformat_base(**kwargs)
if self.enum:
self.enum.reformat(**kwargs)
class CMDStringSchema(CMDStringSchemaBase, CMDSchema):
ARG_TYPE = CMDStringArg
# byte: base64 encoded characters
class CMDByteSchemaBase(CMDSchemaBase):
TYPE_VALUE = "byte"
ARG_TYPE = CMDByteArgBase
class CMDByteSchema(CMDByteSchemaBase, CMDSchema):
ARG_TYPE = CMDByteArg
# binary: any sequence of octets
class CMDBinarySchemaBase(CMDSchemaBase):
TYPE_VALUE = "binary"
ARG_TYPE = CMDBinaryArgBase
name = StringType(required=True)
arg = CMDVariantField()
required = CMDBooleanField()
description = CMDDescriptionField()
fmt = ModelType(
CMDStringFormat,
serialized_name='format',
deserialize_from='format'
)
class CMDBinarySchema(CMDBinarySchemaBase, CMDSchema):
ARG_TYPE = CMDBinaryArg
# duration
class CMDDurationSchemaBase(CMDStringSchemaBase):
TYPE_VALUE = "duration"
ARG_TYPE = CMDDurationArgBase
class CMDDurationSchema(CMDDurationSchemaBase, CMDStringSchema):
ARG_TYPE = CMDDurationArg
# date: As defined by full-date - https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
class CMDDateSchemaBase(CMDStringSchemaBase):
TYPE_VALUE = "date"
ARG_TYPE = CMDDateArgBase
class CMDDateSchema(CMDDateSchemaBase, CMDStringSchema):
ARG_TYPE = CMDDateArg
# date-time: As defined by date-time - https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14
class CMDDateTimeSchemaBase(CMDStringSchemaBase):
TYPE_VALUE = "dateTime"
ARG_TYPE = CMDDateTimeArgBase
class CMDDateTimeSchema(CMDDateTimeSchemaBase, CMDStringSchema):
ARG_TYPE = CMDDateTimeArg
class CMDTimeSchemaBase(CMDStringSchemaBase):
TYPE_VALUE = "time"
ARG_TYPE = CMDTimeArgBase
class CMDTimeSchema(CMDTimeSchemaBase, CMDStringSchema):
ARG_TYPE = CMDTimeArg
# uuid
class CMDUuidSchemaBase(CMDStringSchemaBase):
TYPE_VALUE = "uuid"
ARG_TYPE = CMDUuidArgBase
class CMDUuidSchema(CMDUuidSchemaBase, CMDStringSchema):
ARG_TYPE = CMDUuidArg
# password
class CMDPasswordSchemaBase(CMDStringSchemaBase):
TYPE_VALUE = "password"
ARG_TYPE = CMDPasswordArgBase
class CMDPasswordSchema(CMDPasswordSchemaBase, CMDStringSchema):
ARG_TYPE = CMDPasswordArg
# ResourceId
class CMDResourceIdSchemaBase(CMDStringSchemaBase):
TYPE_VALUE = "ResourceId"
ARG_TYPE = CMDResourceIdArgBase
fmt = ModelType(
CMDResourceIdFormat,
serialized_name='format',
deserialize_from='format'
)
class CMDResourceIdSchema(CMDResourceIdSchemaBase, CMDStringSchema):
ARG_TYPE = CMDResourceIdArg
# ResourceLocation
class CMDResourceLocationSchemaBase(CMDStringSchemaBase):
TYPE_VALUE = "ResourceLocation"
ARG_TYPE = CMDResourceLocationArgBase
class CMDResourceLocationSchema(CMDResourceLocationSchemaBase, CMDStringSchema):
ARG_TYPE = CMDResourceLocationArg
# integer
class CMDIntegerSchemaBase(CMDSchemaBase):
TYPE_VALUE = "integer"
ARG_TYPE = CMDIntegerArgBase
fmt = ModelType(
CMDIntegerFormat,
serialized_name='format',
deserialize_from='format',
)
enum = ModelType(CMDSchemaEnum)
def _diff_base(self, old, level, diff):
diff = super(CMDIntegerSchemaBase, self)._diff_base(old, level, diff)
fmt_diff = _diff_fmt(self.fmt, old.fmt, level)
if fmt_diff:
diff["fmt"] = fmt_diff
enum_diff = _diff_enum(self.enum, old.enum, level)
if enum_diff:
diff["enum"] = enum_diff
return diff
def _reformat_base(self, **kwargs):
super()._reformat_base(**kwargs)
if self.enum:
self.enum.reformat(**kwargs)
class CMDIntegerSchema(CMDIntegerSchemaBase, CMDSchema):
ARG_TYPE = CMDIntegerArg
# integer32
class CMDInteger32SchemaBase(CMDIntegerSchemaBase):
TYPE_VALUE = "integer32"
ARG_TYPE = CMDInteger32ArgBase
class CMDInteger32Schema(CMDInteger32SchemaBase, CMDIntegerSchema):
ARG_TYPE = CMDInteger32Arg
# integer64
class CMDInteger64SchemaBase(CMDIntegerSchemaBase):
TYPE_VALUE = "integer64"
ARG_TYPE = CMDInteger64ArgBase
class CMDInteger64Schema(CMDInteger64SchemaBase, CMDIntegerSchema):
ARG_TYPE = CMDInteger64Arg
# boolean
class CMDBooleanSchemaBase(CMDSchemaBase):
TYPE_VALUE = "boolean"
ARG_TYPE = CMDBooleanArgBase
class CMDBooleanSchema(CMDBooleanSchemaBase, CMDSchema):
ARG_TYPE = CMDBooleanArg
# float
class CMDFloatSchemaBase(CMDSchemaBase):
TYPE_VALUE = "float"
ARG_TYPE = CMDFloatArgBase
fmt = ModelType(
CMDFloatFormat,
serialized_name='format',
deserialize_from='format',
)
enum = ModelType(CMDSchemaEnum)
def _diff_base(self, old, level, diff):
diff = super(CMDFloatSchemaBase, self)._diff_base(old, level, diff)
fmt_diff = _diff_fmt(self.fmt, old.fmt, level)
if fmt_diff:
diff["fmt"] = fmt_diff
enum_diff = _diff_enum(self.enum, old.enum, level)
if enum_diff:
diff["enum"] = enum_diff
return diff
def _reformat_base(self, **kwargs):
super()._reformat_base(**kwargs)
if self.enum:
self.enum.reformat(**kwargs)
class CMDFloatSchema(CMDFloatSchemaBase, CMDSchema):
ARG_TYPE = CMDFloatArg
# float32
class CMDFloat32SchemaBase(CMDFloatSchemaBase):
TYPE_VALUE = "float32"
ARG_TYPE = CMDFloat32ArgBase
class CMDFloat32Schema(CMDFloat32SchemaBase, CMDFloatSchema):
ARG_TYPE = CMDFloat32Arg
# float64
class CMDFloat64SchemaBase(CMDFloatSchemaBase):
TYPE_VALUE = "float64"
ARG_TYPE = CMDFloat64ArgBase
class CMDFloat64Schema(CMDFloat64SchemaBase, CMDFloatSchema):
ARG_TYPE = CMDFloat64Arg
class CMDAnyTypeSchemaBase(CMDSchemaBase):
TYPE_VALUE = "any"
ARG_TYPE = CMDAnyTypeArgBase
class CMDAnyTypeSchema(CMDAnyTypeSchemaBase, CMDSchema):
ARG_TYPE = CMDAnyTypeArg
# object
# discriminator
class CMDObjectSchemaDiscriminatorField(ModelType):
def __init__(self, model_spec=None, **kwargs):
super(CMDObjectSchemaDiscriminatorField, self).__init__(
model_spec=model_spec or CMDObjectSchemaDiscriminator,
serialize_when_none=False,
**kwargs
)
def export(self, value, format, context=None):
if hasattr(value, 'frozen') and value.frozen:
# frozen schema base will be ignored
return None
return super(CMDObjectSchemaDiscriminatorField, self).export(value, format, context)
class CMDObjectSchemaDiscriminator(Model):
ARG_TYPE = CMDObjectArg
# properties as tags
property = StringType(required=True)
value = StringType(required=True)
frozen = CMDBooleanField() # frozen schema will not be used
# properties as nodes
props = ListType(CMDSchemaField())
discriminators = ListType(CMDObjectSchemaDiscriminatorField(model_spec='CMDObjectSchemaDiscriminator'))
class Options:
serialize_when_none = False
def diff(self, old, level):
if self.frozen and old.frozen:
return None
diff = {}
if level >= CMDDiffLevelEnum.BreakingChange:
if self.property != old.property:
diff["property"] = f"{old.property} != {self.property}"
if self.value != old.value:
diff["value"] = f"{old.value} != {self.value}"
props_diff = _diff_props(
self.props or [],
old.props or [],
level
)
if props_diff:
diff["props"] = props_diff
discs_diff = _diff_discriminators(
self.discriminators or [],
old.discriminators or [],
level
)
if discs_diff:
diff["discriminators"] = discs_diff
return diff
def reformat(self, **kwargs):
if self.frozen:
return
if self.props:
for prop in self.props:
prop.reformat(**kwargs)
self.props = sorted(self.props, key=lambda p: p.name)
if self.discriminators:
for disc in self.discriminators:
disc.reformat(**kwargs)
self.discriminators = sorted(self.discriminators, key=lambda disc: disc.value)
def get_safe_value(self):
"""Some value may contain special characters such as Microsoft.db/mysql, it will cause issues. This function will replase them by `_`
"""
safe_value = re.sub(r'[^A-Za-z0-9_-]', '_', self.value)
return safe_value
# additionalProperties
class CMDObjectSchemaAdditionalProperties(Model):
ARG_TYPE = CMDObjectArgAdditionalProperties
# properties as tags
read_only = CMDBooleanField(
serialized_name="readOnly",
deserialize_from="readOnly"
)
frozen = CMDBooleanField()
# properties as nodes
item = CMDSchemaBaseField()
# WARNING: this property will be deprecated as CMDAnyTypeSchemaBase are supported, should directly use CMDAnyTypeSchemaBase as item value
any_type = CMDBooleanField(
serialized_name="anyType",
deserialize_from="anyType"
)
def diff(self, old, level):
if self.frozen and old.frozen:
return None
diff = {}
if level >= CMDDiffLevelEnum.BreakingChange:
if self.read_only and not old.read_only:
diff["read_only"] = f"it's read_only now."
if not self.any_type and old.any_type:
diff["any_type"] = f"it's not any_type now"
# if level >= CMDDiffLevelEnum.Structure:
# if self.any_type:
# if not old.any_type:
# diff["any_type"] = f"Now support any_type"
item_diff = _diff_item(self.item, old.item, level)
if item_diff:
diff["item"] = item_diff
return diff
def reformat(self, **kwargs):
if self.frozen:
return
# deprecated the any_type property
if self.any_type:
self.item = CMDAnyTypeSchemaBase()
self.any_type = None
if self.item:
self.item.reformat(**kwargs)
class CMDObjectSchemaAdditionalPropertiesField(ModelType):
def __init__(self, **kwargs):
super(CMDObjectSchemaAdditionalPropertiesField, self).__init__(
model_spec=CMDObjectSchemaAdditionalProperties,
serialized_name="additionalProps",
deserialize_from="additionalProps",
serialize_when_none=False,
**kwargs
)
def export(self, value, format, context=None):
if value.frozen:
return None
return super(CMDObjectSchemaAdditionalPropertiesField, self).export(value, format, context)
class CMDObjectSchemaBase(CMDSchemaBase):
TYPE_VALUE = "object"
ARG_TYPE = CMDObjectArgBase
fmt = ModelType(
CMDObjectFormat,
serialized_name='format',
deserialize_from='format',
)
props = ListType(CMDSchemaField())
discriminators = ListType(CMDObjectSchemaDiscriminatorField())
additional_props = CMDObjectSchemaAdditionalPropertiesField()
# define a schema cls which can be used by others,
# cls definition will not include properties in CMDSchema only, such as following properties:
# - name
# - arg
# - required
# - description
# - skip_url_encoding
# - client_flatten
# - read_only
cls = CMDClassField()
def _diff_base(self, old, level, diff):
diff = super(CMDObjectSchemaBase, self)._diff_base(old, level, diff)
fmt_diff = _diff_fmt(self.fmt, old.fmt, level)
if fmt_diff:
diff["fmt"] = fmt_diff
props_diff = _diff_props(
self.props or [],
old.props or [],
level
)
if props_diff:
diff["props"] = props_diff
discs_diff = _diff_discriminators(
self.discriminators or [],
old.discriminators or [],
level
)
if discs_diff:
diff["discriminators"] = discs_diff
if level >= CMDDiffLevelEnum.BreakingChange:
if old.additional_props:
if not self.additional_props:
diff["additional_props"] = f"Miss additional props"
if level >= CMDDiffLevelEnum.Structure:
if self.additional_props:
if not old.additional_props:
diff["additional_props"] = f"New additional props"
if self.additional_props and old.additional_props:
additional_diff = self.additional_props.diff(old.additional_props, level)
if additional_diff:
diff["additional_props"] = additional_diff
return diff
def _reformat_base(self, **kwargs):
super()._reformat_base(**kwargs)
if self.props:
for prop in self.props:
prop.reformat(**kwargs)
self.props = sorted(self.props, key=lambda prop: prop.name)
if self.discriminators:
for disc in self.discriminators:
disc.reformat(**kwargs)
self.discriminators = sorted(self.discriminators, key=lambda disc: disc.value)
if self.additional_props:
self.additional_props.reformat(**kwargs)
class CMDObjectSchema(CMDObjectSchemaBase, CMDSchema):
ARG_TYPE = CMDObjectArg
# properties as tags
client_flatten = CMDBooleanField(
serialized_name="clientFlatten",
deserialize_from="clientFlatten"
)
def _diff(self, old, level, diff):
diff = super(CMDObjectSchema, self)._diff(old, level, diff)
if level >= CMDDiffLevelEnum.BreakingChange:
if (not self.client_flatten) != (not old.client_flatten):
diff["client_flatten"] = f"from {old.client_flatten} to {self.client_flatten}"
cls_diff = _diff_cls(self.cls, old.cls, level)
if cls_diff:
diff["cls"] = cls_diff
return diff
class CMDIdentityObjectSchemaBase(CMDObjectSchemaBase):
""" And identity object which contains 'userAssignedIdentities' property and 'type' property
with "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned" and "None" enum values.
"""
TYPE_VALUE = "IdentityObject"
ARG_TYPE = CMDObjectArgBase
user_assigned = CMDSchemaField(
serialized_name="userAssigned",
deserialize_from="userAssigned"
)
system_assigned = CMDSchemaField(
serialized_name="systemAssigned",
deserialize_from="systemAssigned"
)