core.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. '''
  2. @author: olivier.massot
  3. '''
  4. import pickle
  5. import re
  6. from _regex_core import MULTILINE
  7. from path import Path
  8. here = Path(__file__).parent.abspath()
  9. def recurse(acc_obj):
  10. deptree = []
  11. for dep in acc_obj.deps:
  12. deptree.append(dep)
  13. if dep.deps:
  14. deptree += recurse(dep)
  15. return deptree
  16. class InvalidFileExt(IOError):
  17. pass
  18. class Warn():
  19. text = ""
  20. class WarnDuplicate(Warning):
  21. text = "Plusieurs objets portant ce nom ont été trouvés, vérifiez qu'il s'agit bien de l'objet ci-contre"
  22. class WarnComment(Warning):
  23. text = "La mention semble se trouver dans un commentaire"
  24. class WarnCaption(Warning):
  25. text = "Cette mention semble être dans un label"
  26. class WarnRefItself(Warning):
  27. text = "L'objet semble se mentionner lui-même"
  28. class Mention():
  29. def __init__(self, line, objname, quote, obj=None, warnings=[]):
  30. self.line = line
  31. self.objname = objname
  32. self.quote = quote
  33. self._obj_index = None
  34. self.warnings = warnings
  35. self.obj = obj
  36. @property
  37. def obj(self):
  38. return Analyse.objects[self._obj_index]
  39. @obj.setter
  40. def obj(self, value):
  41. self._obj_index = Analyse.objects.index(value)
  42. class AccessObject():
  43. type_ = "<unknown>"
  44. _valid_file_exts = (".bas")
  45. _order = 0
  46. def __init__(self, name_):
  47. self.name_ = name_
  48. self.functions = []
  49. self.sourcefile = ""
  50. self._sourcecode = ""
  51. self.mentions = []
  52. self.deps = []
  53. self.refs = []
  54. def __repr__(self):
  55. return "<{}: {}>".format(self.type_, self.name_)
  56. @classmethod
  57. def from_file(cls, file):
  58. file = Path(file)
  59. if file.ext.lower() not in cls._valid_file_exts:
  60. raise InvalidFileExt("Format de fichier d'entrée non valide ({})".format(file.name))
  61. obj = cls(AccessObject.path_to_name(file))
  62. obj.sourcefile = file
  63. obj._sourcecode = file.text()
  64. obj._sourcecode.replace("\r\n", "\n")
  65. return obj
  66. @property
  67. def sourcecode(self):
  68. if not self._sourcecode:
  69. self._sourcecode = self.sourcefile.text()
  70. return self._sourcecode
  71. @staticmethod
  72. def path_to_name(path):
  73. name_ = path.name.stripext()
  74. for ascii_code, char in {92: "\\", 47: "/", 58: ":", 42: "*", 63:"?", 34:"\"", 60:"<", 62:">", 124:"|" }.items():
  75. name_ = name_.replace("[{}]".format(ascii_code), char)
  76. return name_
  77. class TableObject(AccessObject):
  78. type_ = "Table"
  79. _valid_file_exts = (".xml", ".lnkd")
  80. _order = 10
  81. class QueryObject(AccessObject):
  82. type_ = "Query"
  83. _order = 30
  84. class FormObject(AccessObject):
  85. type_ = "Form"
  86. _order = 40
  87. class ReportObject(AccessObject):
  88. type_ = "Report"
  89. _order = 50
  90. class MacroObject(AccessObject):
  91. type_ = "Macro"
  92. _order = 60
  93. class ModuleObject(AccessObject):
  94. type_ = "Module"
  95. _order = 70
  96. @classmethod
  97. def from_file(cls, file):
  98. obj = super(ModuleObject, cls).from_file(file)
  99. rx = re.compile(r"Sub|Function ([^(]+)\(")
  100. obj.functions = [fname for fname in rx.findall(file.text()) if fname]
  101. return obj
  102. class RelationObject(AccessObject):
  103. type_ = "Relation"
  104. _valid_file_exts = (".txt")
  105. _order = 20
  106. class Analyse():
  107. objects = []
  108. index = {}
  109. @classmethod
  110. def report(cls, current, total, msg=""):
  111. pass
  112. @classmethod
  113. def ended(cls):
  114. pass
  115. @classmethod
  116. def dump_to(cls, filepath):
  117. with open(filepath, 'wb') as f:
  118. pickle.dump(cls.objects, f)
  119. @classmethod
  120. def load_from(cls, filepath):
  121. cls.objects = []
  122. with open(filepath, 'rb') as f:
  123. cls.objects = pickle.load(f)
  124. cls.update_index()
  125. @classmethod
  126. def update_index(cls):
  127. cls.index = {}
  128. for obj in cls.objects:
  129. if not obj.name_ in cls.index:
  130. cls.index[obj.name_] = []
  131. cls.index[obj.name_].append(obj)
  132. if type(obj) is ModuleObject:
  133. for fname in obj.functions:
  134. if not fname in cls.index:
  135. cls.index[fname] = []
  136. cls.index[fname].append(obj)
  137. @classmethod
  138. def load_objects(cls, source_dir):
  139. source_dir = Path(source_dir)
  140. cls.objects = []
  141. cls.index = {}
  142. sourcemap = {
  143. "tables": TableObject,
  144. "relations": RelationObject,
  145. "queries": QueryObject,
  146. "forms": FormObject,
  147. "reports": ReportObject,
  148. "scripts": MacroObject,
  149. "modules": ModuleObject,
  150. }
  151. for dirname, accobj in sourcemap.items():
  152. for file in Path(source_dir / dirname).files():
  153. try:
  154. obj = accobj.from_file(file)
  155. cls.objects.append(obj)
  156. except InvalidFileExt:
  157. print("Ignored unrecognized file: {}".format(file))
  158. cls.objects.sort(key=lambda x: (x._order, x.name_))
  159. cls.update_index()
  160. @classmethod
  161. def parse_source(cls, subject):
  162. # On cherche le nom de chaque autre objet, ainsi que le nom des fonctions issues des modules
  163. look_for = [obj.name_ for obj in cls.objects if obj is not subject and type(object) is not ModuleObject] + list(sum([obj.functions for obj in cls.objects if obj is not subject], []))
  164. names = "|".join(list(set(look_for)))
  165. rx = re.compile("""(.*(?:^|\t| |\[|\]|&|\(|\)|\.|!|"|')({})(?:$|\t| |\[|\]|&|\(|\)|\.|!|"|').*)""".format(names), MULTILINE)
  166. # Indexe la position des lignes
  167. line_ends = [m.end() for m in re.finditer('.*\n', subject.sourcecode)]
  168. for match in rx.finditer(subject.sourcecode):
  169. line = next(i for i in range(len(line_ends)) if line_ends[i] > match.start(1)) + 1
  170. quote = match.group(1).replace("\r", "").replace("\n", "").strip()
  171. objname = match.group(2)
  172. warnings = []
  173. if objname == subject.name_:
  174. obj = subject
  175. warnings.append(WarnRefItself())
  176. else:
  177. obj = cls.index[objname][0]
  178. if len(cls.index[objname]) > 1:
  179. warnings.append(WarnDuplicate())
  180. if type(subject) is ModuleObject:
  181. if re.match(r"^[^\"]*(?:\"(?:[^\"]*?)\")*[^\"]*'.*({})".format(objname), quote):
  182. warnings.append(WarnComment())
  183. if type(subject) in (FormObject, ReportObject):
  184. if re.match(r"Caption =\".*{}.*\"".format(objname), quote):
  185. warnings.append(WarnCaption())
  186. subject.mentions.append(Mention(line, objname, quote, obj, warnings))
  187. @classmethod
  188. def parse_all(cls):
  189. # Mise à jour des dépendances:
  190. # # parcourt les objets, et recherche dans le code source de chacun des mentions du nom des autres objets.
  191. for index, subject in enumerate(cls.objects):
  192. cls.report(index, len(cls.objects), "* {}: {}".format(subject.type_, subject.name_))
  193. cls.parse_source(subject)
  194. @classmethod
  195. def build_trees(cls):
  196. total = len(cls.objects)
  197. for index, subject in enumerate(cls.objects):
  198. cls.report(index, total * 2)
  199. subject.deps = []
  200. for mention in subject.mentions:
  201. if not mention.obj in subject.deps and not mention.obj is subject:
  202. subject.deps.append(mention.obj)
  203. for index, subject in enumerate(cls.objects):
  204. cls.report(total + index, total * 2)
  205. subject.refs = []
  206. for obj in cls.objects:
  207. if obj is subject:
  208. continue
  209. if subject in obj.deps:
  210. subject.refs.append(obj)
  211. @classmethod
  212. def run(cls, source_dir):
  213. # Liste les objets à partir de l'arborescence du repertoire des sources
  214. cls.report(0, 100, "Chargement des données")
  215. cls.load_objects(source_dir)
  216. cls.report(0, 100, "> {} objets trouvés".format(len(cls.objects)))
  217. cls.report(0, 100, "Analyse du code source".format(len(cls.objects)))
  218. cls.parse_all()
  219. cls.report(0, 100, "Construction de l'arbre des dépendances".format(len(cls.objects)))
  220. cls.build_trees()
  221. cls.report(100, 100, "Analyse terminée")
  222. cls.ended()
  223. return cls.objects
  224. @classmethod
  225. def duplicates(cls):
  226. return {k: v for k, v in cls.index.items() if len(v) > 1}
  227. if __name__ == "__main__":
  228. source_dir = here / r"test\source"
  229. resultfile = here / r"test\analyse.txt"
  230. resultfile.remove_p()
  231. def print_(i, total, msg=""):
  232. if msg:
  233. print("({}/{}) {}".format(i, total, msg))
  234. Analyse.report = print_
  235. Analyse.run(source_dir)
  236. with open(resultfile, "w+", encoding='utf-8') as f:
  237. for obj in Analyse.objects:
  238. msg = "# '{}' [{}]".format(obj.name_, obj.type_)
  239. if obj.deps:
  240. msg += "\n\tMentionne: {}".format(", ".join(["'{}' [{}]".format(dep.name_, dep.type_) for dep in obj.deps]))
  241. else:
  242. msg += "\n\t (ne mentionne aucun autre objet)"
  243. if obj.refs:
  244. msg += "\n\tEst mentionné par: {}".format(", ".join(["'{}' [{}]".format(ref.name_, ref.type_) for ref in obj.refs]))
  245. else:
  246. msg += "\n\t (n'est mentionné nul part ailleurs)"
  247. if obj.mentions:
  248. msg += "\n\t Détail:"
  249. for mention in obj.mentions:
  250. msg += "\n\t\t'{}'\t\tLine: {}\t>>\t{}".format(mention.objname, mention.line, mention.quote)
  251. if mention.warnings:
  252. msg += "\n\t\t\t! Avertissements: {}".format("|".join([w.text for w in mention.warnings]))
  253. msg += "\n"
  254. f.write(msg)
  255. print("# Terminé")