Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

serializer.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. import builtins
  2. import collections.abc
  3. import datetime
  4. import decimal
  5. import enum
  6. import functools
  7. import math
  8. import os
  9. import pathlib
  10. import re
  11. import types
  12. import uuid
  13. from django.conf import SettingsReference
  14. from django.db import models
  15. from django.db.migrations.operations.base import Operation
  16. from django.db.migrations.utils import COMPILED_REGEX_TYPE, RegexObject
  17. from django.utils.functional import LazyObject, Promise
  18. from django.utils.version import get_docs_version
  19. class BaseSerializer:
  20. def __init__(self, value):
  21. self.value = value
  22. def serialize(self):
  23. raise NotImplementedError(
  24. "Subclasses of BaseSerializer must implement the serialize() method."
  25. )
  26. class BaseSequenceSerializer(BaseSerializer):
  27. def _format(self):
  28. raise NotImplementedError(
  29. "Subclasses of BaseSequenceSerializer must implement the _format() method."
  30. )
  31. def serialize(self):
  32. imports = set()
  33. strings = []
  34. for item in self.value:
  35. item_string, item_imports = serializer_factory(item).serialize()
  36. imports.update(item_imports)
  37. strings.append(item_string)
  38. value = self._format()
  39. return value % (", ".join(strings)), imports
  40. class BaseSimpleSerializer(BaseSerializer):
  41. def serialize(self):
  42. return repr(self.value), set()
  43. class ChoicesSerializer(BaseSerializer):
  44. def serialize(self):
  45. return serializer_factory(self.value.value).serialize()
  46. class DateTimeSerializer(BaseSerializer):
  47. """For datetime.*, except datetime.datetime."""
  48. def serialize(self):
  49. return repr(self.value), {"import datetime"}
  50. class DatetimeDatetimeSerializer(BaseSerializer):
  51. """For datetime.datetime."""
  52. def serialize(self):
  53. if self.value.tzinfo is not None and self.value.tzinfo != datetime.timezone.utc:
  54. self.value = self.value.astimezone(datetime.timezone.utc)
  55. imports = ["import datetime"]
  56. return repr(self.value), set(imports)
  57. class DecimalSerializer(BaseSerializer):
  58. def serialize(self):
  59. return repr(self.value), {"from decimal import Decimal"}
  60. class DeconstructableSerializer(BaseSerializer):
  61. @staticmethod
  62. def serialize_deconstructed(path, args, kwargs):
  63. name, imports = DeconstructableSerializer._serialize_path(path)
  64. strings = []
  65. for arg in args:
  66. arg_string, arg_imports = serializer_factory(arg).serialize()
  67. strings.append(arg_string)
  68. imports.update(arg_imports)
  69. for kw, arg in sorted(kwargs.items()):
  70. arg_string, arg_imports = serializer_factory(arg).serialize()
  71. imports.update(arg_imports)
  72. strings.append("%s=%s" % (kw, arg_string))
  73. return "%s(%s)" % (name, ", ".join(strings)), imports
  74. @staticmethod
  75. def _serialize_path(path):
  76. module, name = path.rsplit(".", 1)
  77. if module == "django.db.models":
  78. imports = {"from django.db import models"}
  79. name = "models.%s" % name
  80. else:
  81. imports = {"import %s" % module}
  82. name = path
  83. return name, imports
  84. def serialize(self):
  85. return self.serialize_deconstructed(*self.value.deconstruct())
  86. class DictionarySerializer(BaseSerializer):
  87. def serialize(self):
  88. imports = set()
  89. strings = []
  90. for k, v in sorted(self.value.items()):
  91. k_string, k_imports = serializer_factory(k).serialize()
  92. v_string, v_imports = serializer_factory(v).serialize()
  93. imports.update(k_imports)
  94. imports.update(v_imports)
  95. strings.append((k_string, v_string))
  96. return "{%s}" % (", ".join("%s: %s" % (k, v) for k, v in strings)), imports
  97. class EnumSerializer(BaseSerializer):
  98. def serialize(self):
  99. enum_class = self.value.__class__
  100. module = enum_class.__module__
  101. return (
  102. "%s.%s[%r]" % (module, enum_class.__qualname__, self.value.name),
  103. {"import %s" % module},
  104. )
  105. class FloatSerializer(BaseSimpleSerializer):
  106. def serialize(self):
  107. if math.isnan(self.value) or math.isinf(self.value):
  108. return 'float("{}")'.format(self.value), set()
  109. return super().serialize()
  110. class FrozensetSerializer(BaseSequenceSerializer):
  111. def _format(self):
  112. return "frozenset([%s])"
  113. class FunctionTypeSerializer(BaseSerializer):
  114. def serialize(self):
  115. if getattr(self.value, "__self__", None) and isinstance(
  116. self.value.__self__, type
  117. ):
  118. klass = self.value.__self__
  119. module = klass.__module__
  120. return "%s.%s.%s" % (module, klass.__name__, self.value.__name__), {
  121. "import %s" % module
  122. }
  123. # Further error checking
  124. if self.value.__name__ == "<lambda>":
  125. raise ValueError("Cannot serialize function: lambda")
  126. if self.value.__module__ is None:
  127. raise ValueError("Cannot serialize function %r: No module" % self.value)
  128. module_name = self.value.__module__
  129. if "<" not in self.value.__qualname__: # Qualname can include <locals>
  130. return "%s.%s" % (module_name, self.value.__qualname__), {
  131. "import %s" % self.value.__module__
  132. }
  133. raise ValueError(
  134. "Could not find function %s in %s.\n" % (self.value.__name__, module_name)
  135. )
  136. class FunctoolsPartialSerializer(BaseSerializer):
  137. def serialize(self):
  138. # Serialize functools.partial() arguments
  139. func_string, func_imports = serializer_factory(self.value.func).serialize()
  140. args_string, args_imports = serializer_factory(self.value.args).serialize()
  141. keywords_string, keywords_imports = serializer_factory(
  142. self.value.keywords
  143. ).serialize()
  144. # Add any imports needed by arguments
  145. imports = {"import functools", *func_imports, *args_imports, *keywords_imports}
  146. return (
  147. "functools.%s(%s, *%s, **%s)"
  148. % (
  149. self.value.__class__.__name__,
  150. func_string,
  151. args_string,
  152. keywords_string,
  153. ),
  154. imports,
  155. )
  156. class IterableSerializer(BaseSerializer):
  157. def serialize(self):
  158. imports = set()
  159. strings = []
  160. for item in self.value:
  161. item_string, item_imports = serializer_factory(item).serialize()
  162. imports.update(item_imports)
  163. strings.append(item_string)
  164. # When len(strings)==0, the empty iterable should be serialized as
  165. # "()", not "(,)" because (,) is invalid Python syntax.
  166. value = "(%s)" if len(strings) != 1 else "(%s,)"
  167. return value % (", ".join(strings)), imports
  168. class ModelFieldSerializer(DeconstructableSerializer):
  169. def serialize(self):
  170. attr_name, path, args, kwargs = self.value.deconstruct()
  171. return self.serialize_deconstructed(path, args, kwargs)
  172. class ModelManagerSerializer(DeconstructableSerializer):
  173. def serialize(self):
  174. as_manager, manager_path, qs_path, args, kwargs = self.value.deconstruct()
  175. if as_manager:
  176. name, imports = self._serialize_path(qs_path)
  177. return "%s.as_manager()" % name, imports
  178. else:
  179. return self.serialize_deconstructed(manager_path, args, kwargs)
  180. class OperationSerializer(BaseSerializer):
  181. def serialize(self):
  182. from django.db.migrations.writer import OperationWriter
  183. string, imports = OperationWriter(self.value, indentation=0).serialize()
  184. # Nested operation, trailing comma is handled in upper OperationWriter._write()
  185. return string.rstrip(","), imports
  186. class PathLikeSerializer(BaseSerializer):
  187. def serialize(self):
  188. return repr(os.fspath(self.value)), {}
  189. class PathSerializer(BaseSerializer):
  190. def serialize(self):
  191. # Convert concrete paths to pure paths to avoid issues with migrations
  192. # generated on one platform being used on a different platform.
  193. prefix = "Pure" if isinstance(self.value, pathlib.Path) else ""
  194. return "pathlib.%s%r" % (prefix, self.value), {"import pathlib"}
  195. class RegexSerializer(BaseSerializer):
  196. def serialize(self):
  197. regex_pattern, pattern_imports = serializer_factory(
  198. self.value.pattern
  199. ).serialize()
  200. # Turn off default implicit flags (e.g. re.U) because regexes with the
  201. # same implicit and explicit flags aren't equal.
  202. flags = self.value.flags ^ re.compile("").flags
  203. regex_flags, flag_imports = serializer_factory(flags).serialize()
  204. imports = {"import re", *pattern_imports, *flag_imports}
  205. args = [regex_pattern]
  206. if flags:
  207. args.append(regex_flags)
  208. return "re.compile(%s)" % ", ".join(args), imports
  209. class SequenceSerializer(BaseSequenceSerializer):
  210. def _format(self):
  211. return "[%s]"
  212. class SetSerializer(BaseSequenceSerializer):
  213. def _format(self):
  214. # Serialize as a set literal except when value is empty because {}
  215. # is an empty dict.
  216. return "{%s}" if self.value else "set(%s)"
  217. class SettingsReferenceSerializer(BaseSerializer):
  218. def serialize(self):
  219. return "settings.%s" % self.value.setting_name, {
  220. "from django.conf import settings"
  221. }
  222. class TupleSerializer(BaseSequenceSerializer):
  223. def _format(self):
  224. # When len(value)==0, the empty tuple should be serialized as "()",
  225. # not "(,)" because (,) is invalid Python syntax.
  226. return "(%s)" if len(self.value) != 1 else "(%s,)"
  227. class TypeSerializer(BaseSerializer):
  228. def serialize(self):
  229. special_cases = [
  230. (models.Model, "models.Model", ["from django.db import models"]),
  231. (type(None), "type(None)", []),
  232. ]
  233. for case, string, imports in special_cases:
  234. if case is self.value:
  235. return string, set(imports)
  236. if hasattr(self.value, "__module__"):
  237. module = self.value.__module__
  238. if module == builtins.__name__:
  239. return self.value.__name__, set()
  240. else:
  241. return "%s.%s" % (module, self.value.__qualname__), {
  242. "import %s" % module
  243. }
  244. class UUIDSerializer(BaseSerializer):
  245. def serialize(self):
  246. return "uuid.%s" % repr(self.value), {"import uuid"}
  247. class Serializer:
  248. _registry = {
  249. # Some of these are order-dependent.
  250. frozenset: FrozensetSerializer,
  251. list: SequenceSerializer,
  252. set: SetSerializer,
  253. tuple: TupleSerializer,
  254. dict: DictionarySerializer,
  255. models.Choices: ChoicesSerializer,
  256. enum.Enum: EnumSerializer,
  257. datetime.datetime: DatetimeDatetimeSerializer,
  258. (datetime.date, datetime.timedelta, datetime.time): DateTimeSerializer,
  259. SettingsReference: SettingsReferenceSerializer,
  260. float: FloatSerializer,
  261. (bool, int, type(None), bytes, str, range): BaseSimpleSerializer,
  262. decimal.Decimal: DecimalSerializer,
  263. (functools.partial, functools.partialmethod): FunctoolsPartialSerializer,
  264. (
  265. types.FunctionType,
  266. types.BuiltinFunctionType,
  267. types.MethodType,
  268. ): FunctionTypeSerializer,
  269. collections.abc.Iterable: IterableSerializer,
  270. (COMPILED_REGEX_TYPE, RegexObject): RegexSerializer,
  271. uuid.UUID: UUIDSerializer,
  272. pathlib.PurePath: PathSerializer,
  273. os.PathLike: PathLikeSerializer,
  274. }
  275. @classmethod
  276. def register(cls, type_, serializer):
  277. if not issubclass(serializer, BaseSerializer):
  278. raise ValueError(
  279. "'%s' must inherit from 'BaseSerializer'." % serializer.__name__
  280. )
  281. cls._registry[type_] = serializer
  282. @classmethod
  283. def unregister(cls, type_):
  284. cls._registry.pop(type_)
  285. def serializer_factory(value):
  286. if isinstance(value, Promise):
  287. value = str(value)
  288. elif isinstance(value, LazyObject):
  289. # The unwrapped value is returned as the first item of the arguments
  290. # tuple.
  291. value = value.__reduce__()[1][0]
  292. if isinstance(value, models.Field):
  293. return ModelFieldSerializer(value)
  294. if isinstance(value, models.manager.BaseManager):
  295. return ModelManagerSerializer(value)
  296. if isinstance(value, Operation):
  297. return OperationSerializer(value)
  298. if isinstance(value, type):
  299. return TypeSerializer(value)
  300. # Anything that knows how to deconstruct itself.
  301. if hasattr(value, "deconstruct"):
  302. return DeconstructableSerializer(value)
  303. for type_, serializer_cls in Serializer._registry.items():
  304. if isinstance(value, type_):
  305. return serializer_cls(value)
  306. raise ValueError(
  307. "Cannot serialize: %r\nThere are some values Django cannot serialize into "
  308. "migration files.\nFor more, see https://docs.djangoproject.com/en/%s/"
  309. "topics/migrations/#migration-serializing" % (value, get_docs_version())
  310. )