core.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. '''
  2. @author: olivier.massot
  3. '''
  4. import re
  5. from _regex_core import MULTILINE
  6. from path import Path
  7. # TODO: gérer les cas où des objets de types différents portent le même nom. Ex: une table et un formulaire... Note: une requete et une table ne peuvent pas porter le même nom.
  8. # TODO: ignorer les commentaires dans les modules
  9. # TODO: ignorer les labels dans les formulaires et états
  10. # TODO: Gérer les références circulaires
  11. # TODO: Stocker un aperçu du contexte de la ou des références dans le code source, pour contrôle ultérieur
  12. # TODO: Permettre de supprimer / ajouter des réferences
  13. # TODO: Verifier que la recherche puisse être Case sensitive?
  14. def recurse(acc_obj):
  15. deptree = []
  16. for dep in acc_obj.deps:
  17. deptree.append(dep)
  18. if dep.deps:
  19. deptree += recurse(dep)
  20. return deptree
  21. class InvalidFileExt(IOError):
  22. pass
  23. class Mention():
  24. def __init__(self, line, objname, quote, obj):
  25. self.line = line
  26. self.objname = objname
  27. self.quote = quote
  28. self.obj = obj
  29. class AccessObject():
  30. type_ = "<unknown>"
  31. _valid_file_exts = (".bas")
  32. def __init__(self, name_):
  33. self.name_ = name_
  34. self.functions = []
  35. self.sourcefile = ""
  36. self._sourcecode = ""
  37. self.mentions = []
  38. self.deps = []
  39. self.refs = []
  40. def __repr__(self):
  41. return "<{}: {}>".format(self.type_, self.name_)
  42. @classmethod
  43. def from_file(cls, file):
  44. file = Path(file)
  45. if file.ext not in cls._valid_file_exts:
  46. raise InvalidFileExt("Format de fichier d'entrée non valide ({})".format(file.name))
  47. obj = cls(AccessObject.path_to_name(file))
  48. obj.sourcefile = file
  49. obj._sourcecode = file.text()
  50. obj._sourcecode.replace("\r\n", "\n")
  51. return obj
  52. @property
  53. def sourcecode(self):
  54. if not self._sourcecode:
  55. self._sourcecode = self.sourcefile.text()
  56. return self._sourcecode
  57. SUBSTR = {92: "\\", 47: "/", 58: ":", 42: "*", 63:"?", 34:"\"", 60:"<", 62:">", 124:"|" }
  58. @staticmethod
  59. def path_to_name(path):
  60. name_ = path.name.stripext()
  61. for ascii_code, char in AccessObject.SUBSTR.items():
  62. name_ = name_.replace("[{}]".format(ascii_code), char)
  63. return name_
  64. class TableObject(AccessObject):
  65. type_ = "Table"
  66. _valid_file_exts = (".xml", ".lnkd")
  67. class QueryObject(AccessObject):
  68. type_ = "Query"
  69. class FormObject(AccessObject):
  70. type_ = "Form"
  71. class ReportObject(AccessObject):
  72. type_ = "Report"
  73. class MacroObject(AccessObject):
  74. type_ = "Macro"
  75. class ModuleObject(AccessObject):
  76. type_ = "Module"
  77. @classmethod
  78. def from_file(cls, file):
  79. obj = super(ModuleObject, cls).from_file(file)
  80. rx = re.compile(r"Sub|Function ([^(]+)\(")
  81. obj.functions = [fname for fname in rx.findall(file.text()) if fname]
  82. return obj
  83. class RelationObject(AccessObject):
  84. type_ = "Relation"
  85. _valid_file_exts = (".txt")
  86. class Analyse():
  87. objects = []
  88. index = {}
  89. @classmethod
  90. def report(cls, current, total, msg=""):
  91. pass
  92. @classmethod
  93. def ended(cls):
  94. pass
  95. @classmethod
  96. def load_objects(cls, source_dir):
  97. source_dir = Path(source_dir)
  98. cls.objects = []
  99. cls.duplicated_names = []
  100. sourcemap = {
  101. "forms": FormObject,
  102. "reports": ReportObject,
  103. "relations": RelationObject,
  104. "scripts": MacroObject,
  105. "queries": QueryObject,
  106. "tables": TableObject,
  107. "modules": ModuleObject,
  108. }
  109. for dirname, accobj in sourcemap.items():
  110. for file in Path(source_dir / dirname).files():
  111. try:
  112. obj = accobj.from_file(file)
  113. cls.objects.append(obj)
  114. if type(obj) is not ModuleObject:
  115. if not obj.name_ in cls.index:
  116. cls.index[obj.name_] = []
  117. cls.index[obj.name_].append(obj)
  118. else:
  119. for fname in obj.functions:
  120. if not fname in cls.index:
  121. cls.index[fname] = []
  122. cls.index[fname].append(obj)
  123. except InvalidFileExt:
  124. print("Ignored unrecognized file: {}".format(file))
  125. @classmethod
  126. def parse_source(cls, subject):
  127. # On cherche le nom de chaque autre objet, ainsi que le nom des fonctions issues des modules
  128. look_for = [obj.name_ for obj in cls.objects if obj is not subject] + list(sum([obj.functions for obj in cls.objects if obj is not subject], []))
  129. names = "|".join(list(set(look_for)))
  130. rx = re.compile("""(.*(?:^|\t| |\[|\]|&|\(|\)|\.|!|"|')({})(?:$|\t| |\[|\]|&|\(|\)|\.|!|"|').*)""".format(names), MULTILINE)
  131. # Indexe la position des lignes
  132. line_ends = [m.end() for m in re.finditer('.*\n', subject.sourcecode)]
  133. for match in rx.finditer(subject.sourcecode):
  134. line = next(i for i in range(len(line_ends)) if line_ends[i] > match.start(1)) + 1
  135. quote = match.group(1).strip()
  136. objname = match.group(2)
  137. if len(cls.index[objname]) == 1:
  138. obj = cls.index[objname][0]
  139. else:
  140. print("!!! Duplicate")
  141. subject.mentions.append(Mention(line, objname, quote, obj))
  142. @classmethod
  143. def parse_all(cls):
  144. # Mise à jour des dépendances:
  145. # # parcourt les objets, et recherche dans le code source de chacun des mentions du nom des autres objets.
  146. for index, subject in enumerate(cls.objects):
  147. cls.report(index, len(cls.objects), "* {}: {}".format(subject.type_, subject.name_))
  148. cls.parse_source(subject)
  149. @classmethod
  150. def build_trees(cls):
  151. total = len(cls.objects)
  152. for index, subject in enumerate(cls.objects):
  153. cls.report(index, total * 2)
  154. for mention in subject.mentions:
  155. if not mention.obj in subject.deps:
  156. subject.deps.append(mention.obj)
  157. for index, subject in enumerate(cls.objects):
  158. cls.report(total + index, total * 2)
  159. for obj in cls.objects:
  160. if obj is subject:
  161. continue
  162. if subject in obj.deps:
  163. subject.refs.append(obj)
  164. @classmethod
  165. def run(cls, source_dir):
  166. # Liste les objets à partir de l'arborescence du repertoire des sources
  167. cls.report(0, 100, "Chargement des données")
  168. cls.load_objects(source_dir)
  169. cls.report(0, 100, "> {} objets trouvés".format(len(cls.objects)))
  170. cls.report(0, 100, "Analyse du code source".format(len(cls.objects)))
  171. cls.parse_all()
  172. cls.report(0, 100, "Construction de l'arbre des dépendances".format(len(cls.objects)))
  173. cls.build_trees()
  174. cls.report(100, 100, "Analyse terminée")
  175. cls.ended()
  176. return cls.objects
  177. @classmethod
  178. def duplicates(cls):
  179. return {k: v for k, v in cls.items() if len(v) > 1}
  180. if __name__ == "__main__":
  181. here = Path(__file__).parent.abspath()
  182. source_dir = here / r"test\source"
  183. resultfile = here / r"test\analyse.txt"
  184. resultfile.remove_p()
  185. def print_(i, total, msg=""):
  186. if msg:
  187. print("({}/{}) {}".format(i, total, msg))
  188. Analyse.report = print_
  189. Analyse.run(source_dir)
  190. with open(resultfile, "w+", encoding='utf-8') as f:
  191. for obj in Analyse.objects:
  192. msg = "# '{}' [{}]".format(obj.name_, obj.type_)
  193. if obj.deps:
  194. msg += "\n\tMentionne: {}".format(", ".join(["'{}' [{}]".format(dep.name_, dep.type_) for dep in obj.deps]))
  195. else:
  196. msg += "\n\t (ne mentionne aucun autre objet)"
  197. if obj.refs:
  198. msg += "\n\tEst mentionné par: {}".format(", ".join(["'{}' [{}]".format(ref.name_, ref.type_) for ref in obj.refs]))
  199. else:
  200. msg += "\n\t (n'est mentionné nul part ailleurs)"
  201. if obj.mentions:
  202. msg += "\n\t Détail:"
  203. for mention in obj.mentions:
  204. msg += "\n\t\t'{}'\t\tLine: {}\t>>\t{}".format(mention.objname, mention.line, mention.quote)
  205. msg += "\n"
  206. f.write(msg)
  207. print("# Terminé")