No Description
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.

components.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #-*- coding: utf-8 -*-
  2. import itertools
  3. import warnings
  4. import copy
  5. import hashlib
  6. from lodel.utils.mlstring import MlString
  7. from lodel.leapi.datahandlers.field_data_handler import FieldDataHandler
  8. from lodel.editorial_model.exceptions import *
  9. ## @brief Abstract class to represent editorial model components
  10. # @see EmClass EmField
  11. class EmComponent(object):
  12. ## @brief Instanciate an EmComponent
  13. # @param uid str : uniq identifier
  14. # @param display_name MlString|str|dict : component display_name
  15. # @param help_text MlString|str|dict : help_text
  16. def __init__(self, uid, display_name = None, help_text = None, group = None):
  17. if self.__class__ == EmComponent:
  18. raise NotImplementedError('EmComponent is an abstract class')
  19. self.uid = uid
  20. self.display_name = None if display_name is None else MlString(display_name)
  21. self.help_text = None if help_text is None else MlString(help_text)
  22. self.group = group
  23. def __str__(self):
  24. if self.display_name is None:
  25. return str(self.uid)
  26. return str(self.display_name)
  27. def d_hash(self):
  28. m = hashlib.md5()
  29. for data in (
  30. self.uid,
  31. 'NODISPNAME' if self.display_name is None else str(self.display_name.d_hash()),
  32. 'NOHELP' if self.help_text is None else str(self.help_text.d_hash()),
  33. 'NOGROUP' if self.group is None else str(self.group.d_hash()),
  34. ):
  35. m.update(bytes(data, 'utf-8'))
  36. return int.from_bytes(m.digest(), byteorder='big')
  37. ## @brief Handles editorial model objects classes
  38. #
  39. # @note The inheritance system allow child classes to overwrite parents EmField. But it's maybe not a good idea
  40. class EmClass(EmComponent):
  41. ## @brief Instanciate a new EmClass
  42. # @param uid str : uniq identifier
  43. # @param display_name MlString|str|dict : component display_name
  44. # @param abstract bool : set the class as asbtract if True
  45. # @param pure_abstract bool : if True the EmClass will not be represented in leapi dyncode
  46. # @param parents list: parent EmClass list or uid list
  47. # @param help_text MlString|str|dict : help_text
  48. def __init__(self, uid, display_name = None, help_text = None, abstract = False, parents = None, group = None, pure_abstract = False):
  49. super().__init__(uid, display_name, help_text, group)
  50. self.abstract = bool(abstract)
  51. self.pure_abstract = bool(pure_abstract)
  52. if self.pure_abstract:
  53. self.abtract = True
  54. if parents is not None:
  55. if not isinstance(parents, list):
  56. parents = [parents]
  57. for parent in parents:
  58. if not isinstance(parent, EmClass):
  59. raise ValueError("<class EmClass> expected in parents list, but %s found" % type(parent))
  60. else:
  61. parents = list()
  62. self.parents = parents
  63. ## @brief Stores EmFields instances indexed by field uid
  64. self.__fields = dict()
  65. ## @brief Property that represent a dict of all fields (the EmField defined in this class and all its parents)
  66. @property
  67. def __all_fields(self):
  68. res = dict()
  69. for pfields in [ p.__all_fields for p in self.parents]:
  70. res.update(pfields)
  71. res.update(self.__fields)
  72. return res
  73. ## @brief Return the list of all dependencies
  74. #
  75. # Reccursive parents listing
  76. @property
  77. def parents_recc(self):
  78. if len(self.parents) == 0:
  79. return set()
  80. res = set(self.parents)
  81. for parent in self.parents:
  82. res |= parent.parents_recc
  83. return res
  84. ## @brief EmField getter
  85. # @param uid None | str : If None returns an iterator on EmField instances else return an EmField instance
  86. # @param no_parents bool : If True returns only fields defined is this class and not the one defined in parents classes
  87. # @return A list on EmFields instances (if uid is None) else return an EmField instance
  88. def fields(self, uid = None, no_parents = False):
  89. fields = self.__fields if no_parents else self.__all_fields
  90. try:
  91. return list(fields.values()) if uid is None else fields[uid]
  92. except KeyError:
  93. raise EditorialModelError("No such EmField '%s'" % uid)
  94. ## @brief Add a field to the EmClass
  95. # @param emfield EmField : an EmField instance
  96. # @warning do not add an EmField allready in another class !
  97. # @throw EditorialModelException if an EmField with same uid allready in this EmClass (overwritting allowed from parents)
  98. # @todo End the override checks (needs methods in data_handlers)
  99. def add_field(self, emfield):
  100. if emfield.uid in self.__fields:
  101. raise EditorialModelError("Duplicated uid '%s' for EmField in this class ( %s )" % (emfield.uid, self))
  102. # Incomplete field override check
  103. if emfield.uid in self.__all_fields:
  104. parent_field = self.__all_fields[emfield.uid]
  105. if not emfield.data_handler_instance.can_override(parent_field.data_handler_instance):
  106. raise AttributeError("'%s' field override a parent field, but data_handles are not compatible" % emfield.uid)
  107. self.__fields[emfield.uid] = emfield
  108. emfield._emclass = self
  109. return emfield
  110. ## @brief Create a new EmField and add it to the EmClass
  111. # @param data_handler str : A DataHandler name
  112. # @param uid str : the EmField uniq id
  113. # @param **field_kwargs : EmField constructor parameters ( see @ref EmField.__init__() )
  114. def new_field(self, uid, data_handler, **field_kwargs):
  115. return self.add_field(EmField(uid, data_handler, **field_kwargs))
  116. def d_hash(self):
  117. m = hashlib.md5()
  118. payload = str(super().d_hash()) + ("1" if self.abstract else "0")
  119. for p in sorted(self.parents):
  120. payload += str(p.d_hash())
  121. for fuid in sorted(self.__fields.keys()):
  122. payload += str(self.__fields[fuid].d_hash())
  123. m.update(bytes(payload, 'utf-8'))
  124. return int.from_bytes(m.digest(), byteorder='big')
  125. def __str__(self):
  126. return "<class EmClass %s>" % self.uid
  127. def __repr__(self):
  128. if not self.abstract:
  129. abstract = ''
  130. elif self.pure_abstract:
  131. abstract = 'PureAbstract'
  132. else:
  133. abstract = 'Abstract'
  134. return "<class %s EmClass uid=%s>" % (abstract, repr(self.uid) )
  135. ## @brief Handles editorial model classes fields
  136. class EmField(EmComponent):
  137. ## @brief Instanciate a new EmField
  138. # @param uid str : uniq identifier
  139. # @param display_name MlString|str|dict : field display_name
  140. # @param data_handler str : A DataHandler name
  141. # @param help_text MlString|str|dict : help text
  142. # @param group EmGroup :
  143. # @param **handler_kwargs : data handler arguments
  144. def __init__(self, uid, data_handler, display_name = None, help_text = None, group = None, **handler_kwargs):
  145. super().__init__(uid, display_name, help_text, group)
  146. self.data_handler_name = data_handler
  147. self.data_handler_cls = FieldDataHandler.from_name(data_handler)
  148. #if 'data_handler_kwargs' in handler_kwargs:
  149. # handler_kwargs = handler_kwargs['data_handler_kwargs']
  150. self.data_handler_options = handler_kwargs
  151. self.data_handler_instance = self.data_handler_cls(**handler_kwargs)
  152. ## @brief Stores the emclass that contains this field (set by EmClass.add_field() method)
  153. self._emclass = None
  154. ## @warning Not complete !
  155. # @todo Complete the hash when data handlers becomes available
  156. def d_hash(self):
  157. return int.from_bytes(hashlib.md5(
  158. bytes(
  159. "%s%s%s" % ( super().d_hash(),
  160. self.data_handler_name,
  161. self.data_handler_options),
  162. 'utf-8')
  163. ).digest(), byteorder='big')
  164. ## @brief Handles functionnal group of EmComponents
  165. class EmGroup(object):
  166. ## @brief Create a new EmGroup
  167. # @note you should NEVER call the constructor yourself. Use Model.add_group instead
  168. # @param uid str : Uniq identifier
  169. # @param depends list : A list of EmGroup dependencies
  170. # @param display_name MlString|str :
  171. # @param help_text MlString|str :
  172. def __init__(self, uid, depends = None, display_name = None, help_text = None):
  173. self.uid = uid
  174. ## @brief Stores the list of groups that depends on this EmGroup indexed by uid
  175. self.required_by = dict()
  176. ## @brief Stores the list of dependencies (EmGroup) indexed by uid
  177. self.require = dict()
  178. ## @brief Stores the list of EmComponent instances contained in this group
  179. self.__components = set()
  180. self.display_name = None if display_name is None else MlString(display_name)
  181. self.help_text = None if help_text is None else MlString(help_text)
  182. if depends is not None:
  183. for grp in depends:
  184. if not isinstance(grp, EmGroup):
  185. raise ValueError("EmGroup expected in depends argument but %s found" % grp)
  186. self.add_dependencie(grp)
  187. ## @brief Returns EmGroup dependencie
  188. # @param recursive bool : if True return all dependencies and their dependencies
  189. # @return a dict of EmGroup identified by uid
  190. def dependencies(self, recursive = False):
  191. res = copy.copy(self.require)
  192. if not recursive:
  193. return res
  194. to_scan = list(res.values())
  195. while len(to_scan) > 0:
  196. cur_dep = to_scan.pop()
  197. for new_dep in cur_dep.require.values():
  198. if new_dep not in res:
  199. to_scan.append(new_dep)
  200. res[new_dep.uid] = new_dep
  201. return res
  202. ## @brief Add components in a group
  203. # @param components list : EmComponent instance list
  204. def add_components(self, components):
  205. for component in components:
  206. if isinstance(component, EmField):
  207. if component._emclass is None:
  208. warnings.warn("Adding an orphan EmField to an EmGroup")
  209. elif not isinstance(component, EmClass):
  210. raise EditorialModelError("Expecting components to be a list of EmComponent, but %s found in the list" % type(component))
  211. self.__components |= set(components)
  212. ## @brief Add a dependencie
  213. # @param em_group EmGroup|iterable : an EmGroup instance or list of instance
  214. def add_dependencie(self, grp):
  215. try:
  216. for group in grp:
  217. self.add_dependencie(group)
  218. return
  219. except TypeError: pass
  220. if grp.uid in self.require:
  221. return
  222. if self.__circular_dependencie(grp):
  223. raise EditorialModelError("Circular dependencie detected, cannot add dependencie")
  224. self.require[grp.uid] = grp
  225. grp.required_by[self.uid] = self
  226. ## @brief Search for circular dependencie
  227. # @return True if circular dep found else False
  228. def __circular_dependencie(self, new_dep):
  229. return self.uid in new_dep.dependencies(True)
  230. ## @brief Fancy string representation of an EmGroup
  231. # @return a string
  232. def __str__(self):
  233. if self.display_name is None:
  234. return self.uid
  235. else:
  236. return self.display_name.get()
  237. def d_hash(self):
  238. payload = "%s%s%s" % (
  239. self.uid,
  240. 'NODNAME' if self.display_name is None else self.display_name.d_hash(),
  241. 'NOHELP' if self.help_text is None else self.help_text.d_hash()
  242. )
  243. for recurs in (False, True):
  244. deps = self.dependencies(recurs)
  245. for dep_uid in sorted(deps.keys()):
  246. payload += str(deps[dep_uid].d_hash())
  247. for req_by_uid in self.required_by:
  248. payload += req_by_uid
  249. return int.from_bytes(
  250. bytes(payload, 'utf-8'),
  251. byteorder = 'big'
  252. )
  253. ## @brief Complete string representation of an EmGroup
  254. # @return a string
  255. def __repr__(self):
  256. return "<class EmGroup '%s' depends : [%s]>" % (self.uid, ', '.join([duid for duid in self.dependencies(False)]) )