reference.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import json
  2. import logging
  3. from typing import Optional
  4. from dataladmetadatamodel import (
  5. check_serialized_version,
  6. version_string
  7. )
  8. logger = logging.getLogger("datalad.metadatamodel.mapper")
  9. none_class_name = "*None*"
  10. none_location = "*None*"
  11. class Reference:
  12. def __init__(self,
  13. class_name: str,
  14. location: Optional[str] = None):
  15. assert isinstance(location, str) or location is None, \
  16. f"location is not a string: {location}"
  17. self.class_name = class_name
  18. self.location = location
  19. def __str__(self):
  20. return self.__repr__()
  21. def __repr__(self):
  22. return (
  23. f"Reference(class_name='{self.class_name}', "
  24. f"location={repr(self.location)})")
  25. def __eq__(self, other):
  26. return (
  27. self.class_name == other.class_name
  28. and self.location == other.location
  29. )
  30. def assign_from(self, other: "Reference"):
  31. self.class_name = other.class_name
  32. self.location = other.location
  33. def is_none_reference(self) -> bool:
  34. return self.location == none_location
  35. def to_json_str(self):
  36. return json.dumps(self.to_json_obj())
  37. def to_json_obj(self):
  38. return {
  39. "@": dict(
  40. type="Reference",
  41. version=version_string),
  42. **dict(
  43. class_name=self.class_name,
  44. location=self.location)
  45. }
  46. @classmethod
  47. def from_json_str(cls, json_str: str) -> "Reference":
  48. return cls.from_json_obj(json.loads(json_str))
  49. @classmethod
  50. def from_json_obj(cls, obj) -> "Reference":
  51. assert obj["@"]["type"] == "Reference"
  52. check_serialized_version(obj)
  53. if "mapper_family" in obj or "realm" in obj:
  54. logger.info(f"old reference object found: {obj}")
  55. return cls(
  56. obj["class_name"],
  57. obj["location"]
  58. )
  59. @classmethod
  60. def get_none_reference(cls, referred_class_name: str) -> "Reference":
  61. return cls(referred_class_name, none_location)
  62. @staticmethod
  63. def is_remote(realm: str):
  64. return any(
  65. map(
  66. lambda pattern: realm.startswith(pattern),
  67. [
  68. "git@",
  69. "git:",
  70. "http:",
  71. "https:",
  72. "ssh:"]))
  73. @staticmethod
  74. def is_local(realm: str):
  75. return not Reference.is_remote(realm)