16
16
"""
17
17
import sys
18
18
from inspect import isclass
19
- from typing import Callable , ClassVar , Dict , List , Optional , Tuple , Type , Union , Any , Set
19
+ from typing import (
20
+ Callable ,
21
+ ClassVar ,
22
+ Dict ,
23
+ List ,
24
+ Optional ,
25
+ Tuple ,
26
+ Type ,
27
+ Union ,
28
+ Any ,
29
+ Set ,
30
+ )
20
31
import warnings
21
32
22
33
from pydantic import ConfigDict , BaseModel , PrivateAttr
23
34
import structlog # type: ignore
24
35
25
36
from diffsync .diff import Diff
26
37
from diffsync .enum import DiffSyncModelFlags , DiffSyncFlags , DiffSyncStatus
27
- from diffsync .exceptions import DiffClassMismatch , ObjectAlreadyExists , ObjectStoreWrongType , ObjectNotFound
38
+ from diffsync .exceptions import (
39
+ DiffClassMismatch ,
40
+ ObjectAlreadyExists ,
41
+ ObjectStoreWrongType ,
42
+ ObjectNotFound ,
43
+ )
28
44
from diffsync .helpers import DiffSyncDiffer , DiffSyncSyncer
29
45
from diffsync .store import BaseStore
30
46
from diffsync .store .local import LocalStore
@@ -97,15 +113,17 @@ class DiffSyncModel(BaseModel):
97
113
Can be set as a class attribute or an instance attribute as needed.
98
114
"""
99
115
100
- diffsync : Optional ["Adapter" ] = None
101
- """Optional: the DiffSync instance that owns this model instance."""
116
+ adapter : Optional ["Adapter" ] = None
117
+ """Optional: the Adapter instance that owns this model instance."""
102
118
103
119
_status : DiffSyncStatus = PrivateAttr (DiffSyncStatus .SUCCESS )
104
120
"""Status of the last attempt at creating/updating/deleting this model."""
105
121
106
122
_status_message : str = PrivateAttr ("" )
107
123
"""Message, if any, associated with the create/update/delete status value."""
124
+
108
125
model_config = ConfigDict (arbitrary_types_allowed = True )
126
+ """Pydantic-specific configuration to allow arbitrary types on this class."""
109
127
110
128
@classmethod
111
129
def __pydantic_init_subclass__ (cls , ** kwargs : Any ) -> None :
@@ -145,15 +163,15 @@ def __str__(self) -> str:
145
163
return self .get_unique_id ()
146
164
147
165
def dict (self , ** kwargs : Any ) -> Dict :
148
- """Convert this DiffSyncModel to a dict, excluding the diffsync field by default as it is not serializable."""
166
+ """Convert this DiffSyncModel to a dict, excluding the adapter field by default as it is not serializable."""
149
167
if "exclude" not in kwargs :
150
- kwargs ["exclude" ] = {"diffsync " }
168
+ kwargs ["exclude" ] = {"adapter " }
151
169
return super ().model_dump (** kwargs )
152
170
153
171
def json (self , ** kwargs : Any ) -> StrType :
154
- """Convert this DiffSyncModel to a JSON string, excluding the diffsync field by default as it is not serializable."""
172
+ """Convert this DiffSyncModel to a JSON string, excluding the adapter field by default as it is not serializable."""
155
173
if "exclude" not in kwargs :
156
- kwargs ["exclude" ] = {"diffsync " }
174
+ kwargs ["exclude" ] = {"adapter " }
157
175
if "exclude_defaults" not in kwargs :
158
176
kwargs ["exclude_defaults" ] = True
159
177
return super ().model_dump_json (** kwargs )
@@ -167,12 +185,12 @@ def str(self, include_children: bool = True, indent: int = 0) -> StrType:
167
185
child_ids = getattr (self , fieldname )
168
186
if not child_ids :
169
187
output += ": []"
170
- elif not self .diffsync or not include_children :
188
+ elif not self .adapter or not include_children :
171
189
output += f": { child_ids } "
172
190
else :
173
191
for child_id in child_ids :
174
192
try :
175
- child = self .diffsync .get (modelname , child_id )
193
+ child = self .adapter .get (modelname , child_id )
176
194
output += "\n " + child .str (include_children = include_children , indent = indent + 4 )
177
195
except ObjectNotFound :
178
196
output += f"\n { margin } { child_id } (ERROR: details unavailable)"
@@ -184,32 +202,32 @@ def set_status(self, status: DiffSyncStatus, message: StrType = "") -> None:
184
202
self ._status_message = message
185
203
186
204
@classmethod
187
- def create_base (cls , diffsync : "Adapter" , ids : Dict , attrs : Dict ) -> Optional [Self ]:
205
+ def create_base (cls , adapter : "Adapter" , ids : Dict , attrs : Dict ) -> Optional [Self ]:
188
206
"""Instantiate this class, along with any platform-specific data creation.
189
207
190
208
This method is not meant to be subclassed, users should redefine create() instead.
191
209
192
210
Args:
193
- diffsync : The master data store for other DiffSyncModel instances that we might need to reference
211
+ adapter : The master data store for other DiffSyncModel instances that we might need to reference
194
212
ids: Dictionary of unique-identifiers needed to create the new object
195
213
attrs: Dictionary of additional attributes to set on the new object
196
214
197
215
Returns:
198
216
DiffSyncModel: instance of this class.
199
217
"""
200
- model = cls (** ids , diffsync = diffsync , ** attrs )
218
+ model = cls (** ids , adapter = adapter , ** attrs )
201
219
model .set_status (DiffSyncStatus .SUCCESS , "Created successfully" )
202
220
return model
203
221
204
222
@classmethod
205
- def create (cls , diffsync : "Adapter" , ids : Dict , attrs : Dict ) -> Optional [Self ]:
223
+ def create (cls , adapter : "Adapter" , ids : Dict , attrs : Dict ) -> Optional [Self ]:
206
224
"""Instantiate this class, along with any platform-specific data creation.
207
225
208
226
Subclasses must call `super().create()` or `self.create_base()`; they may wish to then override the default status information
209
227
by calling `set_status()` to provide more context (such as details of any interactions with underlying systems).
210
228
211
229
Args:
212
- diffsync : The master data store for other DiffSyncModel instances that we might need to reference
230
+ adapter : The master data store for other DiffSyncModel instances that we might need to reference
213
231
ids: Dictionary of unique-identifiers needed to create the new object
214
232
attrs: Dictionary of additional attributes to set on the new object
215
233
@@ -220,7 +238,7 @@ def create(cls, diffsync: "Adapter", ids: Dict, attrs: Dict) -> Optional[Self]:
220
238
Raises:
221
239
ObjectNotCreated: if an error occurred.
222
240
"""
223
- return cls .create_base (diffsync = diffsync , ids = ids , attrs = attrs )
241
+ return cls .create_base (adapter = adapter , ids = ids , attrs = attrs )
224
242
225
243
def update_base (self , attrs : Dict ) -> Optional [Self ]:
226
244
"""Base Update method to update the attributes of this instance, along with any platform-specific data updates.
@@ -376,7 +394,10 @@ def add_child(self, child: "DiffSyncModel") -> None:
376
394
attr_name = self ._children [child_type ]
377
395
childs = getattr (self , attr_name )
378
396
if child .get_unique_id () in childs :
379
- raise ObjectAlreadyExists (f"Already storing a { child_type } with unique_id { child .get_unique_id ()} " , child )
397
+ raise ObjectAlreadyExists (
398
+ f"Already storing a { child_type } with unique_id { child .get_unique_id ()} " ,
399
+ child ,
400
+ )
380
401
childs .append (child .get_unique_id ())
381
402
382
403
def remove_child (self , child : "DiffSyncModel" ) -> None :
@@ -417,7 +438,9 @@ class Adapter: # pylint: disable=too-many-public-methods
417
438
"""List of top-level modelnames to begin from when diffing or synchronizing."""
418
439
419
440
def __init__ (
420
- self , name : Optional [str ] = None , internal_storage_engine : Union [Type [BaseStore ], BaseStore ] = LocalStore
441
+ self ,
442
+ name : Optional [str ] = None ,
443
+ internal_storage_engine : Union [Type [BaseStore ], BaseStore ] = LocalStore ,
421
444
) -> None :
422
445
"""Generic initialization function.
423
446
@@ -426,9 +449,9 @@ def __init__(
426
449
427
450
if isinstance (internal_storage_engine , BaseStore ):
428
451
self .store = internal_storage_engine
429
- self .store .diffsync = self
452
+ self .store .adapter = self
430
453
else :
431
- self .store = internal_storage_engine (diffsync = self )
454
+ self .store = internal_storage_engine (adapter = self )
432
455
433
456
# If the type is not defined, use the name of the class as the default value
434
457
if self .type is None :
@@ -565,7 +588,13 @@ def sync_from( # pylint: disable=too-many-arguments
565
588
# Generate the diff if an existing diff was not provided
566
589
if not diff :
567
590
diff = self .diff_from (source , diff_class = diff_class , flags = flags , callback = callback )
568
- syncer = DiffSyncSyncer (diff = diff , src_diffsync = source , dst_diffsync = self , flags = flags , callback = callback )
591
+ syncer = DiffSyncSyncer (
592
+ diff = diff ,
593
+ src_diffsync = source ,
594
+ dst_diffsync = self ,
595
+ flags = flags ,
596
+ callback = callback ,
597
+ )
569
598
result = syncer .perform_sync ()
570
599
if result :
571
600
self .sync_complete (source , diff , flags , syncer .base_logger )
@@ -639,7 +668,11 @@ def diff_from(
639
668
calculation of the diff proceeds.
640
669
"""
641
670
differ = DiffSyncDiffer (
642
- src_diffsync = source , dst_diffsync = self , flags = flags , diff_class = diff_class , callback = callback
671
+ src_diffsync = source ,
672
+ dst_diffsync = self ,
673
+ flags = flags ,
674
+ diff_class = diff_class ,
675
+ callback = callback ,
643
676
)
644
677
return differ .calculate_diffs ()
645
678
@@ -674,7 +707,9 @@ def get_all_model_names(self) -> Set[StrType]:
674
707
return self .store .get_all_model_names ()
675
708
676
709
def get (
677
- self , obj : Union [StrType , DiffSyncModel , Type [DiffSyncModel ]], identifier : Union [StrType , Dict ]
710
+ self ,
711
+ obj : Union [StrType , DiffSyncModel , Type [DiffSyncModel ]],
712
+ identifier : Union [StrType , Dict ],
678
713
) -> DiffSyncModel :
679
714
"""Get one object from the data store based on its unique id.
680
715
@@ -689,7 +724,9 @@ def get(
689
724
return self .store .get (model = obj , identifier = identifier )
690
725
691
726
def get_or_none (
692
- self , obj : Union [StrType , DiffSyncModel , Type [DiffSyncModel ]], identifier : Union [StrType , Dict ]
727
+ self ,
728
+ obj : Union [StrType , DiffSyncModel , Type [DiffSyncModel ]],
729
+ identifier : Union [StrType , Dict ],
693
730
) -> Optional [DiffSyncModel ]:
694
731
"""Get one object from the data store based on its unique id or get a None
695
732
@@ -720,7 +757,9 @@ def get_all(self, obj: Union[StrType, DiffSyncModel, Type[DiffSyncModel]]) -> Li
720
757
return self .store .get_all (model = obj )
721
758
722
759
def get_by_uids (
723
- self , uids : List [StrType ], obj : Union [StrType , DiffSyncModel , Type [DiffSyncModel ]]
760
+ self ,
761
+ uids : List [StrType ],
762
+ obj : Union [StrType , DiffSyncModel , Type [DiffSyncModel ]],
724
763
) -> List [DiffSyncModel ]:
725
764
"""Get multiple objects from the store by their unique IDs/Keys and type.
726
765
0 commit comments