diff --git a/swh/model/collections.py b/swh/model/collections.py new file mode 100644 --- /dev/null +++ b/swh/model/collections.py @@ -0,0 +1,36 @@ +# Copyright (C) 2020 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +from collections.abc import Mapping +from typing import Dict, Generic, Iterable, Tuple, TypeVar, Union + +KT = TypeVar("KT") +VT = TypeVar("VT") + + +class ImmutableDict(Mapping, Generic[KT, VT]): + data: Tuple[Tuple[KT, VT], ...] + + def __init__(self, data: Union[Iterable[Tuple[KT, VT]], Dict[KT, VT]] = {}): + if isinstance(data, dict): + self.data = tuple(item for item in data.items()) + else: + self.data = tuple(data) + + def __getitem__(self, key): + for (k, v) in self.data: + if k == key: + return v + raise KeyError(key) + + def __iter__(self): + for (k, v) in self.data: + yield k + + def __len__(self): + return len(self.data) + + def items(self): + yield from self.data diff --git a/swh/model/model.py b/swh/model/model.py --- a/swh/model/model.py +++ b/swh/model/model.py @@ -16,6 +16,8 @@ import dateutil.parser import iso8601 +from .collections import ImmutableDict +from .hashutil import DEFAULT_ALGORITHMS, hash_to_bytes, MultiHash from .identifiers import ( normalize_timestamp, directory_identifier, @@ -24,7 +26,6 @@ snapshot_identifier, PersistentId, ) -from .hashutil import DEFAULT_ALGORITHMS, hash_to_bytes, MultiHash class MissingData(Exception): @@ -40,13 +41,26 @@ Sha1Git = bytes +KT = TypeVar("KT") +VT = TypeVar("VT") + + +def freeze_optional_dict( + d: Union[None, Dict[KT, VT], ImmutableDict[KT, VT]] # type: ignore +) -> Optional[ImmutableDict[KT, VT]]: + if isinstance(d, dict): + return ImmutableDict(d) + else: + return d + + def dictify(value): "Helper function used by BaseModel.to_dict()" if isinstance(value, BaseModel): return value.to_dict() elif isinstance(value, Enum): return value.value - elif isinstance(value, dict): + elif isinstance(value, (dict, ImmutableDict)): return {k: dictify(v) for k, v in value.items()} elif isinstance(value, tuple): return tuple(dictify(v) for v in value) @@ -276,7 +290,10 @@ ) snapshot = attr.ib(type=Optional[Sha1Git], validator=type_validator()) metadata = attr.ib( - type=Optional[Dict[str, object]], validator=type_validator(), default=None + type=Optional[ImmutableDict[str, object]], + validator=type_validator(), + converter=freeze_optional_dict, + default=None, ) @@ -331,7 +348,9 @@ object_type: Final = "snapshot" branches = attr.ib( - type=Dict[bytes, Optional[SnapshotBranch]], validator=type_validator() + type=ImmutableDict[bytes, Optional[SnapshotBranch]], + validator=type_validator(), + converter=freeze_optional_dict, ) id = attr.ib(type=Sha1Git, validator=type_validator(), default=b"") @@ -343,10 +362,10 @@ def from_dict(cls, d): d = d.copy() return cls( - branches={ - name: SnapshotBranch.from_dict(branch) if branch else None + branches=ImmutableDict( + (name, SnapshotBranch.from_dict(branch) if branch else None) for (name, branch) in d.pop("branches").items() - }, + ), **d, ) @@ -365,7 +384,10 @@ type=Optional[TimestampWithTimezone], validator=type_validator(), default=None ) metadata = attr.ib( - type=Optional[Dict[str, object]], validator=type_validator(), default=None + type=Optional[ImmutableDict[str, object]], + validator=type_validator(), + converter=freeze_optional_dict, + default=None, ) id = attr.ib(type=Sha1Git, validator=type_validator(), default=b"") @@ -426,7 +448,10 @@ directory = attr.ib(type=Sha1Git, validator=type_validator()) synthetic = attr.ib(type=bool, validator=type_validator()) metadata = attr.ib( - type=Optional[Dict[str, object]], validator=type_validator(), default=None + type=Optional[ImmutableDict[str, object]], + validator=type_validator(), + converter=freeze_optional_dict, + default=None, ) parents = attr.ib(type=Tuple[Sha1Git, ...], validator=type_validator(), default=()) id = attr.ib(type=Sha1Git, validator=type_validator(), default=b"") @@ -687,7 +712,10 @@ type = attr.ib(type=MetadataAuthorityType, validator=type_validator()) url = attr.ib(type=str, validator=type_validator()) metadata = attr.ib( - type=Optional[Dict[str, Any]], default=None, validator=type_validator() + type=Optional[ImmutableDict[str, Any]], + default=None, + validator=type_validator(), + converter=freeze_optional_dict, ) @@ -699,7 +727,10 @@ name = attr.ib(type=str, validator=type_validator()) version = attr.ib(type=str, validator=type_validator()) metadata = attr.ib( - type=Optional[Dict[str, Any]], default=None, validator=type_validator() + type=Optional[ImmutableDict[str, Any]], + default=None, + validator=type_validator(), + converter=freeze_optional_dict, ) diff --git a/swh/model/tests/test_collections.py b/swh/model/tests/test_collections.py new file mode 100644 --- /dev/null +++ b/swh/model/tests/test_collections.py @@ -0,0 +1,42 @@ +# Copyright (C) 2020 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +import pytest + +from swh.model.collections import ImmutableDict + + +def test_immutabledict_empty(): + d = ImmutableDict() + + assert d == {} + assert d != {"foo": "bar"} + + assert list(d) == [] + assert list(d.items()) == [] + + +def test_immutabledict_one_item(): + d = ImmutableDict({"foo": "bar"}) + + assert d == {"foo": "bar"} + assert d != {} + + assert d["foo"] == "bar" + with pytest.raises(KeyError, match="bar"): + d["bar"] + + assert list(d) == ["foo"] + assert list(d.items()) == [("foo", "bar")] + + +def test_immutabledict_immutable(): + d = ImmutableDict({"foo": "bar"}) + + with pytest.raises(TypeError, match="item assignment"): + d["bar"] = "baz" + + with pytest.raises(TypeError, match="item deletion"): + del d["foo"]