Skip to content

Commit 615ed7c

Browse files
committed
renames 'diffsync' fields and variables to 'adapter'
1 parent 6928565 commit 615ed7c

File tree

14 files changed

+263
-222
lines changed

14 files changed

+263
-222
lines changed

diffsync/__init__.py

+64-25
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,31 @@
1616
"""
1717
import sys
1818
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+
)
2031
import warnings
2132

2233
from pydantic import ConfigDict, BaseModel, PrivateAttr
2334
import structlog # type: ignore
2435

2536
from diffsync.diff import Diff
2637
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+
)
2844
from diffsync.helpers import DiffSyncDiffer, DiffSyncSyncer
2945
from diffsync.store import BaseStore
3046
from diffsync.store.local import LocalStore
@@ -97,15 +113,17 @@ class DiffSyncModel(BaseModel):
97113
Can be set as a class attribute or an instance attribute as needed.
98114
"""
99115

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."""
102118

103119
_status: DiffSyncStatus = PrivateAttr(DiffSyncStatus.SUCCESS)
104120
"""Status of the last attempt at creating/updating/deleting this model."""
105121

106122
_status_message: str = PrivateAttr("")
107123
"""Message, if any, associated with the create/update/delete status value."""
124+
108125
model_config = ConfigDict(arbitrary_types_allowed=True)
126+
"""Pydantic-specific configuration to allow arbitrary types on this class."""
109127

110128
@classmethod
111129
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
@@ -145,15 +163,15 @@ def __str__(self) -> str:
145163
return self.get_unique_id()
146164

147165
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."""
149167
if "exclude" not in kwargs:
150-
kwargs["exclude"] = {"diffsync"}
168+
kwargs["exclude"] = {"adapter"}
151169
return super().model_dump(**kwargs)
152170

153171
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."""
155173
if "exclude" not in kwargs:
156-
kwargs["exclude"] = {"diffsync"}
174+
kwargs["exclude"] = {"adapter"}
157175
if "exclude_defaults" not in kwargs:
158176
kwargs["exclude_defaults"] = True
159177
return super().model_dump_json(**kwargs)
@@ -167,12 +185,12 @@ def str(self, include_children: bool = True, indent: int = 0) -> StrType:
167185
child_ids = getattr(self, fieldname)
168186
if not child_ids:
169187
output += ": []"
170-
elif not self.diffsync or not include_children:
188+
elif not self.adapter or not include_children:
171189
output += f": {child_ids}"
172190
else:
173191
for child_id in child_ids:
174192
try:
175-
child = self.diffsync.get(modelname, child_id)
193+
child = self.adapter.get(modelname, child_id)
176194
output += "\n" + child.str(include_children=include_children, indent=indent + 4)
177195
except ObjectNotFound:
178196
output += f"\n{margin} {child_id} (ERROR: details unavailable)"
@@ -184,32 +202,32 @@ def set_status(self, status: DiffSyncStatus, message: StrType = "") -> None:
184202
self._status_message = message
185203

186204
@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]:
188206
"""Instantiate this class, along with any platform-specific data creation.
189207
190208
This method is not meant to be subclassed, users should redefine create() instead.
191209
192210
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
194212
ids: Dictionary of unique-identifiers needed to create the new object
195213
attrs: Dictionary of additional attributes to set on the new object
196214
197215
Returns:
198216
DiffSyncModel: instance of this class.
199217
"""
200-
model = cls(**ids, diffsync=diffsync, **attrs)
218+
model = cls(**ids, adapter=adapter, **attrs)
201219
model.set_status(DiffSyncStatus.SUCCESS, "Created successfully")
202220
return model
203221

204222
@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]:
206224
"""Instantiate this class, along with any platform-specific data creation.
207225
208226
Subclasses must call `super().create()` or `self.create_base()`; they may wish to then override the default status information
209227
by calling `set_status()` to provide more context (such as details of any interactions with underlying systems).
210228
211229
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
213231
ids: Dictionary of unique-identifiers needed to create the new object
214232
attrs: Dictionary of additional attributes to set on the new object
215233
@@ -220,7 +238,7 @@ def create(cls, diffsync: "Adapter", ids: Dict, attrs: Dict) -> Optional[Self]:
220238
Raises:
221239
ObjectNotCreated: if an error occurred.
222240
"""
223-
return cls.create_base(diffsync=diffsync, ids=ids, attrs=attrs)
241+
return cls.create_base(adapter=adapter, ids=ids, attrs=attrs)
224242

225243
def update_base(self, attrs: Dict) -> Optional[Self]:
226244
"""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:
376394
attr_name = self._children[child_type]
377395
childs = getattr(self, attr_name)
378396
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+
)
380401
childs.append(child.get_unique_id())
381402

382403
def remove_child(self, child: "DiffSyncModel") -> None:
@@ -417,7 +438,9 @@ class Adapter: # pylint: disable=too-many-public-methods
417438
"""List of top-level modelnames to begin from when diffing or synchronizing."""
418439

419440
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,
421444
) -> None:
422445
"""Generic initialization function.
423446
@@ -426,9 +449,9 @@ def __init__(
426449

427450
if isinstance(internal_storage_engine, BaseStore):
428451
self.store = internal_storage_engine
429-
self.store.diffsync = self
452+
self.store.adapter = self
430453
else:
431-
self.store = internal_storage_engine(diffsync=self)
454+
self.store = internal_storage_engine(adapter=self)
432455

433456
# If the type is not defined, use the name of the class as the default value
434457
if self.type is None:
@@ -565,7 +588,13 @@ def sync_from( # pylint: disable=too-many-arguments
565588
# Generate the diff if an existing diff was not provided
566589
if not diff:
567590
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+
)
569598
result = syncer.perform_sync()
570599
if result:
571600
self.sync_complete(source, diff, flags, syncer.base_logger)
@@ -639,7 +668,11 @@ def diff_from(
639668
calculation of the diff proceeds.
640669
"""
641670
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,
643676
)
644677
return differ.calculate_diffs()
645678

@@ -674,7 +707,9 @@ def get_all_model_names(self) -> Set[StrType]:
674707
return self.store.get_all_model_names()
675708

676709
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],
678713
) -> DiffSyncModel:
679714
"""Get one object from the data store based on its unique id.
680715
@@ -689,7 +724,9 @@ def get(
689724
return self.store.get(model=obj, identifier=identifier)
690725

691726
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],
693730
) -> Optional[DiffSyncModel]:
694731
"""Get one object from the data store based on its unique id or get a None
695732
@@ -720,7 +757,9 @@ def get_all(self, obj: Union[StrType, DiffSyncModel, Type[DiffSyncModel]]) -> Li
720757
return self.store.get_all(model=obj)
721758

722759
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]],
724763
) -> List[DiffSyncModel]:
725764
"""Get multiple objects from the store by their unique IDs/Keys and type.
726765

diffsync/helpers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ def sync_model( # pylint: disable=too-many-branches, unused-argument
425425
if self.action == DiffSyncActions.CREATE:
426426
if dst_model is not None:
427427
raise ObjectNotCreated(f"Failed to create {self.model_class.get_type()} {ids} - it already exists!")
428-
dst_model = self.model_class.create(diffsync=self.dst_diffsync, ids=ids, attrs=attrs)
428+
dst_model = self.model_class.create(adapter=self.dst_diffsync, ids=ids, attrs=attrs)
429429
elif self.action == DiffSyncActions.UPDATE:
430430
if dst_model is None:
431431
raise ObjectNotUpdated(f"Failed to update {self.model_class.get_type()} {ids} - not found!")

diffsync/store/__init__.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,12 @@ class BaseStore:
1515
def __init__(
1616
self, # pylint: disable=unused-argument
1717
*args: Any, # pylint: disable=unused-argument
18-
diffsync: Optional["Adapter"] = None,
18+
adapter: Optional["Adapter"] = None,
1919
name: str = "",
2020
**kwargs: Any, # pylint: disable=unused-argument
2121
) -> None:
2222
"""Init method for BaseStore."""
23-
self.diffsync = diffsync
23+
self.adapter = adapter
2424
self.name = name or self.__class__.__name__
2525
self._log = structlog.get_logger().new(store=self)
2626

@@ -95,8 +95,8 @@ def remove(self, *, obj: "DiffSyncModel", remove_children: bool = False) -> None
9595

9696
self.remove_item(modelname, uid)
9797

98-
if obj.diffsync:
99-
obj.diffsync = None
98+
if obj.adapter:
99+
obj.adapter = None
100100

101101
if remove_children:
102102
for child_type, child_fieldname in obj.get_children_mapping().items():
@@ -243,9 +243,9 @@ def _get_object_class_and_model(
243243
"""Get object class and model name for a model."""
244244
if isinstance(model, str):
245245
modelname = model
246-
if not hasattr(self.diffsync, model):
246+
if not hasattr(self.adapter, model):
247247
return None, modelname
248-
object_class = getattr(self.diffsync, model)
248+
object_class = getattr(self.adapter, model)
249249
else:
250250
object_class = model
251251
modelname = model.get_type()

diffsync/store/local.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ def add(self, *, obj: "DiffSyncModel") -> None:
108108
# Return so we don't have to change anything on the existing object and underlying data
109109
return
110110

111-
if not obj.diffsync:
112-
obj.diffsync = self.diffsync
111+
if not obj.adapter:
112+
obj.adapter = self.adapter
113113

114114
self._data[modelname][uid] = obj
115115

diffsync/store/redis.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def _get_object_from_redis_key(self, key: str) -> "DiffSyncModel":
6565
pickled_object = self._store.get(key)
6666
if pickled_object:
6767
obj_result = loads(pickled_object) # nosec
68-
obj_result.diffsync = self.diffsync
68+
obj_result.adapter = self.adapter
6969
return obj_result
7070
raise ObjectNotFound(f"{key} not present in Cache")
7171

@@ -178,7 +178,7 @@ def add(self, *, obj: "DiffSyncModel") -> None:
178178

179179
# Remove the diffsync object before sending to Redis
180180
obj_copy = copy.copy(obj)
181-
obj_copy.diffsync = None
181+
obj_copy.adapter = None
182182

183183
self._store.set(object_key, dumps(obj_copy))
184184

@@ -193,7 +193,7 @@ def update(self, *, obj: "DiffSyncModel") -> None:
193193

194194
object_key = self._get_key_for_object(modelname, uid)
195195
obj_copy = copy.copy(obj)
196-
obj_copy.diffsync = None
196+
obj_copy.adapter = None
197197

198198
self._store.set(object_key, dumps(obj_copy))
199199

docs/source/getting_started/01-getting-started.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -181,10 +181,10 @@ class Device(DiffSyncModel):
181181
[...]
182182

183183
@classmethod
184-
def create(cls, diffsync, ids, attrs):
184+
def create(cls, adapter, ids, attrs):
185185
## TODO add your own logic here to create the device on the remote system
186186
# Call the super().create() method to create the in-memory DiffSyncModel instance
187-
return super().create(ids=ids, diffsync=diffsync, attrs=attrs)
187+
return super().create(ids=ids, adapter=adapter, attrs=attrs)
188188

189189
def update(self, attrs):
190190
## TODO add your own logic here to update the device on the remote system

docs/source/upgrading/01-upgrading-to-2.0.md

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ With diffsync 2.0, there a couple of breaking changes. What they are and how to
66

77
The main diffsync class `diffsync.Diffsync` has been renamed to `diffsync.Adapter` as we have found that this is the verbiage that is most often used by users and explains the intent of the class clearer. The old name will still be around until 2.1, but is considered deprecated at this point.
88

9+
As a consequence, a lot of fields have been renamed all across diffsync. To the end user, this will most prominently appear in the signature of the `create` method, where you will have to rename the `diffsync` parameter to `adapter`.
10+
911
## Upgrade to Pydantic's major version 2
1012

1113
A [migration guide](https://docs.pydantic.dev/latest/migration/) is available in the Pydantic documentation. Here are the key things that may apply to your usage of diffsync:

examples/03-remote-system/nautobot_models.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,11 @@ class NautobotCountry(Country):
3030
"""Store the nautobot uuid in the object to allow update and delete of existing object."""
3131

3232
@classmethod
33-
def create(cls, diffsync: Adapter, ids: dict, attrs: dict):
33+
def create(cls, adapter: Adapter, ids: dict, attrs: dict):
3434
"""Create a country object in Nautobot.
3535
3636
Args:
37-
diffsync: The master data store for other DiffSyncModel instances that we might need to reference
37+
adapter: The master data store for other DiffSyncModel instances that we might need to reference
3838
ids: Dictionary of unique-identifiers needed to create the new object
3939
attrs: Dictionary of additional attributes to set on the new object
4040
@@ -43,11 +43,11 @@ def create(cls, diffsync: Adapter, ids: dict, attrs: dict):
4343
"""
4444
# Retrieve the parent region in internal cache to access its UUID
4545
# because the UUID is required to associate the object to its parent region in Nautobot
46-
region = diffsync.get(diffsync.region, attrs.get("region"))
46+
region = adapter.get(adapter.region, attrs.get("region"))
4747

4848
# Create the new country in Nautobot and attach it to its parent
4949
try:
50-
country = diffsync.nautobot.dcim.regions.create(
50+
country = adapter.nautobot.dcim.regions.create(
5151
slug=ids.get("slug"),
5252
name=attrs.get("name"),
5353
custom_fields=dict(population=attrs.get("population")),
@@ -61,7 +61,7 @@ def create(cls, diffsync: Adapter, ids: dict, attrs: dict):
6161

6262
# Add the newly created remote_id and create the internal object for this resource.
6363
attrs["remote_id"] = country.id
64-
item = super().create(ids=ids, diffsync=diffsync, attrs=attrs)
64+
item = super().create(ids=ids, adapter=adapter, attrs=attrs)
6565
return item
6666

6767
def update(self, attrs: dict):
@@ -78,7 +78,7 @@ def update(self, attrs: dict):
7878
ObjectNotUpdated: if an error occurred.
7979
"""
8080
# Retrive the pynautobot object from Nautobot since we only have the UUID internally
81-
remote = self.diffsync.nautobot.dcim.regions.get(self.remote_id)
81+
remote = self.adapter.nautobot.dcim.regions.get(self.remote_id)
8282

8383
# Convert the internal attrs to Nautobot format
8484
if "population" in attrs:
@@ -98,7 +98,7 @@ def delete(self):
9898
NautobotCountry: DiffSync object
9999
"""
100100
# Retrieve the pynautobot object and delete the object in Nautobot
101-
remote = self.diffsync.nautobot.dcim.regions.get(self.remote_id)
101+
remote = self.adapter.nautobot.dcim.regions.get(self.remote_id)
102102
remote.delete()
103103

104104
super().delete()

0 commit comments

Comments
 (0)