datasettree.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from typing import (
  2. cast,
  3. List,
  4. Optional,
  5. Tuple,
  6. )
  7. from dataladmetadatamodel.metadatapath import MetadataPath
  8. from dataladmetadatamodel.metadatarootrecord import MetadataRootRecord
  9. from dataladmetadatamodel.mtreenode import MTreeNode
  10. from dataladmetadatamodel.mtreeproxy import MTreeProxy
  11. from dataladmetadatamodel.mapper.reference import Reference
  12. datalad_root_record_name = ".datalad_metadata_root_record"
  13. class DatasetTree(MTreeProxy):
  14. def __init__(self,
  15. mtree: Optional[MTreeNode] = None,
  16. realm: Optional[str] = None,
  17. reference: Optional[Reference] = None):
  18. assert isinstance(mtree, (type(None), MTreeNode))
  19. assert isinstance(realm, (type(None), str))
  20. assert isinstance(reference, (type(None), Reference))
  21. super().__init__(MetadataRootRecord, mtree, realm, reference)
  22. def __contains__(self, path: MetadataPath) -> bool:
  23. return self.mtree.get_object_at_path(path / datalad_root_record_name) is not None
  24. def add_dataset(self,
  25. path: MetadataPath,
  26. metadata_root_record: MetadataRootRecord):
  27. self.mtree.add_child_at(metadata_root_record,
  28. path / datalad_root_record_name)
  29. def get_metadata_root_record(self,
  30. path: MetadataPath
  31. ) -> Optional[MetadataRootRecord]:
  32. mrr = self.mtree.get_object_at_path(
  33. path / datalad_root_record_name)
  34. if mrr is None:
  35. return None
  36. assert isinstance(mrr, MetadataRootRecord)
  37. mrr.ensure_mapped()
  38. return mrr
  39. @property
  40. def dataset_paths(self
  41. ) -> List[Tuple[MetadataPath, MetadataRootRecord]]:
  42. return [
  43. (
  44. MetadataPath("/".join(path.parts[:-1])),
  45. cast(MetadataRootRecord, node)
  46. )
  47. for path, node in self.mtree.get_paths_recursive()
  48. if path.parts[-1] == datalad_root_record_name
  49. ]
  50. def add_subtree(self,
  51. subtree: "DatasetTree",
  52. subtree_path: MetadataPath):
  53. self.mtree.add_child_at(subtree.mtree, subtree_path)
  54. def delete_subtree(self,
  55. subtree_path: MetadataPath):
  56. self.mtree.remove_child_at(subtree_path)