diff --git a/swh/model/from_disk.py b/swh/model/from_disk.py --- a/swh/model/from_disk.py +++ b/swh/model/from_disk.py @@ -16,6 +16,7 @@ identifier_to_bytes as id_to_bytes, identifier_to_str as id_to_str, ) +from . import model class DentryPerms(enum.IntEnum): @@ -177,6 +178,13 @@ def compute_hash(self): return self.data['sha1_git'] + def to_model(self) -> model.BaseContent: + """Builds a `model.BaseContent` object based on this leaf.""" + data = self.get_data().copy() + for key in ('perms', 'path'): + data.pop(key, None) + return model.BaseContent.from_dict(data) + def accept_all_directories(dirname, entries): """Default filter for :func:`Directory.from_disk` accepting all @@ -333,6 +341,11 @@ def compute_hash(self): return id_to_bytes(directory_identifier({'entries': self.entries})) + def to_model(self) -> model.Directory: + """Builds a `model.Directory` object based on this node; + ignoring its children.""" + return model.Directory.from_dict(self.get_data()) + def __getitem__(self, key): if not isinstance(key, bytes): raise ValueError('Can only get a bytes from Directory') diff --git a/swh/model/tests/test_from_disk.py b/swh/model/tests/test_from_disk.py --- a/swh/model/tests/test_from_disk.py +++ b/swh/model/tests/test_from_disk.py @@ -14,6 +14,7 @@ from swh.model import from_disk from swh.model.from_disk import Content, DentryPerms, Directory from swh.model.hashutil import DEFAULT_ALGORITHMS, hash_to_bytes, hash_to_hex +from swh.model import model TEST_DATA = os.path.join(os.path.dirname(__file__), 'data') @@ -409,6 +410,8 @@ if isinstance(right, Content): right = right.get_data() + # Compare dictionaries + keys = DEFAULT_ALGORITHMS | { 'length', 'perms', @@ -443,6 +446,19 @@ ) ) + # Compare normalization to swh.model.BaseContent + + right = right.copy() + for key in ('perms', 'path', 'mode'): + right.pop(key, None) + if 'data' in left.data: + right['status'] = 'visible' + else: + right['status'] = 'absent' + right['reason'] = 'Skipping file content' + right.pop('data', None) + assert left.to_model() == model.BaseContent.from_dict(right) + def assertDirectoryEqual(self, left, right): # NoQA if not isinstance(left, Directory): raise ValueError('%s is not a Directory' % left) @@ -450,6 +466,9 @@ right = right.get_data() assert left.entries == right['entries'] + assert left.hash == right['id'] + + assert left.to_model() == model.Directory.from_dict(right) def make_contents(self, directory): for filename, content in self.contents.items():