collision_resolvers.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. # -*- coding: utf-8 -*-
  2. import inspect
  3. import sys
  4. from abc import abstractmethod, ABCMeta
  5. from typing import ( # NOQA
  6. Dict,
  7. List,
  8. Optional,
  9. Tuple,
  10. )
  11. from django.utils.module_loading import import_string
  12. from six import add_metaclass
  13. @add_metaclass(ABCMeta)
  14. class BaseCR:
  15. """
  16. Abstract base collision resolver. All collision resolvers needs to inherit from this class.
  17. To write custom collision resolver you need to overwrite resolve_collisions function.
  18. It receives Dict[str, List[str]], where key is model name and values are full model names
  19. (full model name means: module + model_name).
  20. You should return Dict[str, str], where key is model name and value is full model name.
  21. """
  22. @classmethod
  23. def get_app_name_and_model(cls, full_model_path): # type: (str) -> Tuple[str, str]
  24. model_class = import_string(full_model_path)
  25. return model_class._meta.app_config.name, model_class.__name__
  26. @abstractmethod
  27. def resolve_collisions(self, namespace): # type: (Dict[str, List[str]]) -> Dict[str, str]
  28. pass
  29. class LegacyCR(BaseCR):
  30. """ Default collision resolver. Model from last application in alphabetical order is selected. """
  31. def resolve_collisions(self, namespace):
  32. result = {}
  33. for name, models in namespace.items():
  34. result[name] = models[-1]
  35. return result
  36. @add_metaclass(ABCMeta)
  37. class AppsOrderCR(LegacyCR):
  38. APP_PRIORITIES = None # type: List[str]
  39. def resolve_collisions(self, namespace):
  40. assert self.APP_PRIORITIES is not None, "You must define APP_PRIORITIES in your resolver class!"
  41. result = {}
  42. for name, models in namespace.items():
  43. if len(models) > 0:
  44. sorted_models = self._sort_models_depending_on_priorities(models)
  45. result[name] = sorted_models[0][1]
  46. return result
  47. def _sort_models_depending_on_priorities(self, models): # type: (List[str]) -> List[Tuple[int, str]]
  48. models_with_priorities = []
  49. for model in models:
  50. try:
  51. app_name, _ = self.get_app_name_and_model(model)
  52. position = self.APP_PRIORITIES.index(app_name)
  53. except (ImportError, ValueError):
  54. position = sys.maxsize
  55. models_with_priorities.append((position, model))
  56. return sorted(models_with_priorities)
  57. class InstalledAppsOrderCR(AppsOrderCR):
  58. """
  59. Collision resolver which selects first model from INSTALLED_APPS.
  60. You can set your own app priorities list by subclassing him and overwriting APP_PRIORITIES field.
  61. This collision resolver will select model from first app on this list.
  62. If both app's are absent on this list, resolver will choose model from first app in alphabetical order.
  63. """
  64. @property
  65. def APP_PRIORITIES(self):
  66. from django.conf import settings
  67. return getattr(settings, 'INSTALLED_APPS', [])
  68. @add_metaclass(ABCMeta)
  69. class PathBasedCR(LegacyCR):
  70. """
  71. Abstract resolver which transforms full model name into alias.
  72. To use him you need to overwrite transform_import function
  73. which should have one parameter. It will be full model name.
  74. It should return valid alias as str instance.
  75. """
  76. @abstractmethod
  77. def transform_import(self, module_path): # type: (str) -> str
  78. pass
  79. def resolve_collisions(self, namespace):
  80. base_imports = super(PathBasedCR, self).resolve_collisions(namespace)
  81. for name, models in namespace.items():
  82. if len(models) <= 1:
  83. continue
  84. for model in models:
  85. new_name = self.transform_import(model)
  86. assert isinstance(new_name, str), "result of transform_import must be str!"
  87. base_imports[new_name] = model
  88. return base_imports
  89. class FullPathCR(PathBasedCR):
  90. """
  91. Collision resolver which transform full model name to alias by changing dots to underscores.
  92. He also removes 'models' part of alias, because all models are in models.py files.
  93. Model from last application in alphabetical order is selected.
  94. """
  95. def transform_import(self, module_path):
  96. module, model = module_path.rsplit('.models', 1)
  97. module_path = module + model
  98. return module_path.replace('.', '_')
  99. @add_metaclass(ABCMeta)
  100. class AppNameCR(PathBasedCR):
  101. """
  102. Abstract collision resolver which transform pair (app name, model_name) to alias by changing dots to underscores.
  103. You must define MODIFICATION_STRING which should be string to format with two keyword arguments:
  104. app_name and model_name. For example: "{app_name}_{model_name}".
  105. Model from last application in alphabetical order is selected.
  106. """
  107. MODIFICATION_STRING = None # type: Optional[str]
  108. def transform_import(self, module_path):
  109. assert self.MODIFICATION_STRING is not None, "You must define MODIFICATION_STRING in your resolver class!"
  110. app_name, model_name = self.get_app_name_and_model(module_path)
  111. app_name = app_name.replace('.', '_')
  112. return self.MODIFICATION_STRING.format(app_name=app_name, model_name=model_name)
  113. class AppNamePrefixCR(AppNameCR):
  114. """
  115. Collision resolver which transform pair (app name, model_name) to alias "{app_name}_{model_name}".
  116. Model from last application in alphabetical order is selected.
  117. Result is different than FullPathCR, when model has app_label other than current app.
  118. """
  119. MODIFICATION_STRING = "{app_name}_{model_name}"
  120. class AppNameSuffixCR(AppNameCR):
  121. """
  122. Collision resolver which transform pair (app name, model_name) to alias "{model_name}_{app_name}"
  123. Model from last application in alphabetical order is selected.
  124. """
  125. MODIFICATION_STRING = "{model_name}_{app_name}"
  126. class AppNamePrefixCustomOrderCR(AppNamePrefixCR, InstalledAppsOrderCR):
  127. """
  128. Collision resolver which is mixin of AppNamePrefixCR and InstalledAppsOrderCR.
  129. In case of collisions he sets aliases like AppNamePrefixCR, but sets default model using InstalledAppsOrderCR.
  130. """
  131. pass
  132. class AppNameSuffixCustomOrderCR(AppNameSuffixCR, InstalledAppsOrderCR):
  133. """
  134. Collision resolver which is mixin of AppNameSuffixCR and InstalledAppsOrderCR.
  135. In case of collisions he sets aliases like AppNameSuffixCR, but sets default model using InstalledAppsOrderCR.
  136. """
  137. pass
  138. class FullPathCustomOrderCR(FullPathCR, InstalledAppsOrderCR):
  139. """
  140. Collision resolver which is mixin of FullPathCR and InstalledAppsOrderCR.
  141. In case of collisions he sets aliases like FullPathCR, but sets default model using InstalledAppsOrderCR.
  142. """
  143. pass
  144. @add_metaclass(ABCMeta)
  145. class AppLabelCR(PathBasedCR):
  146. """
  147. Abstract collision resolver which transform pair (app_label, model_name) to alias.
  148. You must define MODIFICATION_STRING which should be string to format with two keyword arguments:
  149. app_label and model_name. For example: "{app_label}_{model_name}".
  150. This is different from AppNameCR when the app is nested with several level of namespace:
  151. Gives sites_Site instead of django_contrib_sites_Site
  152. Model from last application in alphabetical order is selected.
  153. """
  154. MODIFICATION_STRING = None # type: Optional[str]
  155. def transform_import(self, module_path):
  156. assert self.MODIFICATION_STRING is not None, "You must define MODIFICATION_STRING in your resolver class!"
  157. model_class = import_string(module_path)
  158. app_label, model_name = model_class._meta.app_label, model_class.__name__
  159. return self.MODIFICATION_STRING.format(app_label=app_label, model_name=model_name)
  160. class AppLabelPrefixCR(AppLabelCR):
  161. """
  162. Collision resolver which transform pair (app_label, model_name) to alias "{app_label}_{model_name}".
  163. Model from last application in alphabetical order is selected.
  164. """
  165. MODIFICATION_STRING = "{app_label}_{model_name}"
  166. class AppLabelSuffixCR(AppLabelCR):
  167. """
  168. Collision resolver which transform pair (app_label, model_name) to alias "{model_name}_{app_label}".
  169. Model from last application in alphabetical order is selected.
  170. """
  171. MODIFICATION_STRING = "{model_name}_{app_label}"
  172. class CollisionResolvingRunner:
  173. def __init__(self):
  174. pass
  175. def run_collision_resolver(self, models_to_import):
  176. # type: (Dict[str, List[str]]) -> Dict[str, List[Tuple[str, str]]]
  177. dictionary_of_names = self._get_dictionary_of_names(models_to_import) # type: Dict[str, str]
  178. return self._get_dictionary_of_modules(dictionary_of_names)
  179. @classmethod
  180. def _get_dictionary_of_names(cls, models_to_import): # type: (Dict[str, List[str]]) -> (Dict[str, str])
  181. from django.conf import settings
  182. collision_resolver_class = import_string(getattr(
  183. settings, 'SHELL_PLUS_MODEL_IMPORTS_RESOLVER',
  184. 'django_extensions.collision_resolvers.LegacyCR'
  185. ))
  186. cls._assert_is_collision_resolver_class_correct(collision_resolver_class)
  187. result = collision_resolver_class().resolve_collisions(models_to_import)
  188. cls._assert_is_collision_resolver_result_correct(result)
  189. return result
  190. @classmethod
  191. def _assert_is_collision_resolver_result_correct(cls, result):
  192. assert isinstance(result, dict), "Result of resolve_collisions function must be a dict!"
  193. for key, value in result.items():
  194. assert isinstance(key, str), "key in collision resolver result should be str not %s" % key
  195. assert isinstance(value, str), "value in collision resolver result should be str not %s" % value
  196. @classmethod
  197. def _assert_is_collision_resolver_class_correct(cls, collision_resolver_class):
  198. assert inspect.isclass(collision_resolver_class) and issubclass(
  199. collision_resolver_class, BaseCR), "SHELL_PLUS_MODEL_IMPORTS_RESOLVER " \
  200. "must be subclass of BaseCR!"
  201. assert len(inspect.getfullargspec(collision_resolver_class.resolve_collisions).args) == 2, \
  202. "resolve_collisions function must take one argument!"
  203. @classmethod
  204. def _get_dictionary_of_modules(cls, dictionary_of_names):
  205. # type: (Dict[str, str]) -> Dict[str, List[Tuple[str, str]]]
  206. dictionary_of_modules = {} # type: Dict[str, List[Tuple[str, str]]]
  207. for alias, model in dictionary_of_names.items():
  208. module_path, model_name = model.rsplit('.', 1)
  209. dictionary_of_modules.setdefault(module_path, [])
  210. dictionary_of_modules[module_path].append((model_name, alias))
  211. return dictionary_of_modules