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.

180 lines
6.2 KiB

  1. # Copyright (C) 2019-Today: GRAP (<http://www.grap.coop/>)
  2. # @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. import os
  5. import pygount
  6. from pathlib import Path
  7. import logging
  8. from odoo import api, fields, models
  9. from odoo.tools.safe_eval import safe_eval
  10. from odoo.modules.module import get_module_path
  11. _logger = logging.getLogger(__name__)
  12. class IrModuleModule(models.Model):
  13. _inherit = 'ir.module.module'
  14. author_ids = fields.Many2many(
  15. string='Authors', comodel_name='ir.module.author', readonly=True,
  16. relation='ir_module_module_author_rel')
  17. module_type_id = fields.Many2one(
  18. string='Module Type', comodel_name='ir.module.type', readonly=True)
  19. python_code_qty = fields.Integer(
  20. string='Python Code Quantity', readonly=True)
  21. xml_code_qty = fields.Integer(
  22. string='XML Code Quantity', readonly=True)
  23. js_code_qty = fields.Integer(
  24. string='JS Code Quantity', readonly=True)
  25. css_code_qty = fields.Integer(
  26. string='CSS Code Quantity', readonly=True)
  27. # Overloadable Section
  28. @api.model
  29. def _get_analyse_settings(self):
  30. """Return a dictionnary of data analysed
  31. Overload this function if you want to analyse other data
  32. {
  33. 'extension': {
  34. 'data_to_analyse': 'field_name',
  35. },
  36. }, [...]
  37. extension: extension of the file, with the '.'
  38. data_to_analyse : possible value : code, documentation, empty, string
  39. field_name: Odoo field name to store the analysis
  40. """
  41. return {
  42. '.py': {
  43. 'code': 'python_code_qty',
  44. },
  45. '.xml': {
  46. 'code': 'xml_code_qty',
  47. },
  48. '.js': {
  49. 'code': 'js_code_qty',
  50. },
  51. '.css': {
  52. 'code': 'css_code_qty',
  53. },
  54. }
  55. @api.model
  56. def _get_clean_analyse_values(self):
  57. """List of fields to unset when a module is uninstalled"""
  58. return {
  59. 'author_ids': [6, 0, []],
  60. 'module_type_id': False,
  61. 'python_code_qty': False,
  62. 'xml_code_qty': 0,
  63. 'js_code_qty': 0,
  64. 'css_code_qty': 0,
  65. }
  66. # Overload Section
  67. @api.model
  68. def update_list(self):
  69. res = super().update_list()
  70. if self.env.context.get('analyse_installed_modules', False):
  71. self.search([('state', '=', 'installed')]).button_analyse_code()
  72. return res
  73. @api.multi
  74. def write(self, vals):
  75. res = super().write(vals)
  76. if vals.get('state', False) == 'installed':
  77. self.button_analyse_code()
  78. elif vals.get('state', False) == 'uninstalled'\
  79. and 'module_analysis' not in [x.name for x in self]:
  80. self.write(self._get_clean_analyse_values())
  81. return res
  82. # Public Section
  83. @api.multi
  84. def button_analyse_code(self):
  85. IrModuleAuthor = self.env['ir.module.author']
  86. IrModuleTypeRule = self.env['ir.module.type.rule']
  87. rules = IrModuleTypeRule.search([])
  88. cfg = self.env['ir.config_parameter']
  89. val = cfg.get_param('module_analysis.exclude_directories', '')
  90. exclude_directories = [x.strip() for x in val.split(',') if x.strip()]
  91. val = cfg.get_param('module_analysis.exclude_files', '')
  92. exclude_files = [x.strip() for x in val.split(',') if x.strip()]
  93. for module in self:
  94. _logger.info("Analysing Code for module %s ..." % (module.name))
  95. # Update Authors, based on manifest key
  96. authors = []
  97. if module.author and module.author[0] == '[':
  98. author_txt_list = safe_eval(module.author)
  99. else:
  100. author_txt_list = module.author.split(',')
  101. author_txt_list = [x.strip() for x in author_txt_list]
  102. author_txt_list = [x for x in author_txt_list if x]
  103. for author_txt in author_txt_list:
  104. authors.append(IrModuleAuthor._get_or_create(author_txt))
  105. author_ids = [x.id for x in authors]
  106. module.author_ids = author_ids
  107. # Update Module Type, based on rules
  108. module_type_id = rules._get_module_type_id_from_module(module)
  109. module.module_type_id = module_type_id
  110. # Get Path of module folder and parse the code
  111. module_path = get_module_path(module.name)
  112. # Get Files
  113. analysed_datas = self._get_analyse_data_dict()
  114. file_extensions = analysed_datas.keys()
  115. file_list = self._get_files_to_analyse(
  116. module_path, file_extensions, exclude_directories,
  117. exclude_files)
  118. for file_path, file_ext in file_list:
  119. file_res = pygount.source_analysis(file_path, '')
  120. for k, v in analysed_datas.get(file_ext).items():
  121. v['value'] += getattr(file_res, k)
  122. # Update the module with the datas
  123. values = {}
  124. for file_ext, analyses in analysed_datas.items():
  125. for k, v in analyses.items():
  126. values[v['field']] = v['value']
  127. module.write(values)
  128. # Custom Section
  129. @api.model
  130. def _get_files_to_analyse(
  131. self, path, file_extensions, exclude_directories, exclude_files):
  132. res = []
  133. for root, dirs, files in os.walk(path, followlinks=True):
  134. if set(Path(root).parts) & set(exclude_directories):
  135. continue
  136. for name in files:
  137. if name in exclude_files:
  138. continue
  139. filename, file_extension = os.path.splitext(name)
  140. if file_extension in file_extensions:
  141. res.append((os.path.join(root, name), file_extension))
  142. return res
  143. @api.model
  144. def _get_analyse_data_dict(self):
  145. res_dict = self._get_analyse_settings().copy()
  146. for file_ext, analyse_dict in res_dict.items():
  147. for analyse_type, v in analyse_dict.items():
  148. analyse_dict[analyse_type] = {
  149. 'field': v,
  150. 'value': 0
  151. }
  152. return res_dict