core.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. '''
  2. @author: olivier.massot
  3. '''
  4. import pickle
  5. import re
  6. from _regex_core import MULTILINE, IGNORECASE, VERBOSE
  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. glossary = {}
  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.build_glossary()
  125. @classmethod
  126. def build_glossary(cls):
  127. cls.glossary.clear()
  128. for obj in cls.objects:
  129. if not obj.name_.lower() in cls.glossary:
  130. cls.glossary[obj.name_.lower()] = []
  131. cls.glossary[obj.name_.lower()].append(obj)
  132. if type(obj) is ModuleObject:
  133. for fname in obj.functions:
  134. if not fname.lower() in cls.glossary:
  135. cls.glossary[fname.lower()] = []
  136. cls.glossary[fname.lower()].append(obj)
  137. @classmethod
  138. def load_objects(cls, source_dir):
  139. source_dir = Path(source_dir)
  140. cls.objects = []
  141. sourcemap = {
  142. "tables": TableObject,
  143. "relations": RelationObject,
  144. "queries": QueryObject,
  145. "forms": FormObject,
  146. "reports": ReportObject,
  147. "scripts": MacroObject,
  148. "modules": ModuleObject,
  149. }
  150. for dirname, accobj in sourcemap.items():
  151. for file in Path(source_dir / dirname).files():
  152. try:
  153. obj = accobj.from_file(file)
  154. cls.objects.append(obj)
  155. except InvalidFileExt:
  156. print("Ignored unrecognized file: {}".format(file))
  157. cls.objects.sort(key=lambda x: (x._order, x.name_))
  158. cls.build_glossary()
  159. @classmethod
  160. def parse_source(cls, subject):
  161. # On cherche le nom de chaque autre objet, ainsi que le nom des fonctions issues des modules
  162. look_for = {obj.name_ for obj in cls.objects if obj is not subject and type(object) is not ModuleObject} | set(sum([obj.functions for obj in cls.objects if obj is not subject], []))
  163. names = "|".join(list(look_for))
  164. seps = "|".join(("\t", " ", "\[", "\]", "&", "\(", "\)", "\.", "!", "'", "\"", r"\\015", r"\\012")) # Note: Les separateurs possibles incluent \015 et \012 qui sont les hexadecimaux pour \n et \r
  165. rstr = """(?:^|{seps})({names})(?:$|{seps})""".format(seps=seps, names=names)
  166. rx = re.compile(rstr, MULTILINE | IGNORECASE | VERBOSE)
  167. # Indexe la position des lignes
  168. line_matches = list(re.finditer('.*\n', subject.sourcecode))
  169. for match in rx.finditer(subject.sourcecode):
  170. line_number, line = next((i + 1, line) for i, line in enumerate(line_matches) if line.end() > match.start(1))
  171. quote = line.group(0).replace("\r", "").replace("\n", "").strip()
  172. objname = match.group(1)
  173. warnings = []
  174. if objname == subject.name_:
  175. obj = subject
  176. warnings.append(WarnRefItself())
  177. else:
  178. obj = cls.glossary[objname.lower()][0]
  179. if len(cls.glossary[objname.lower()]) > 1:
  180. warnings.append(WarnDuplicate())
  181. if type(subject) is ModuleObject:
  182. if re.match(r"^[^\"]*(?:\"(?:[^\"]*?)\")*[^\"]*'.*({})".format(objname), quote):
  183. warnings.append(WarnComment())
  184. if type(subject) in (FormObject, ReportObject):
  185. if re.match(r"Caption =\".*{}.*\"".format(objname), quote):
  186. warnings.append(WarnCaption())
  187. subject.mentions.append(Mention(line_number, objname, quote, obj, warnings))
  188. @classmethod
  189. def parse_all(cls):
  190. # Mise à jour des dépendances:
  191. # # parcourt les objets, et recherche dans le code source de chacun des mentions du nom des autres objets.
  192. for index, subject in enumerate(cls.objects):
  193. cls.report(index, len(cls.objects), "* {}: {}".format(subject.type_, subject.name_))
  194. cls.parse_source(subject)
  195. @classmethod
  196. def build_trees(cls):
  197. total = len(cls.objects)
  198. for index, subject in enumerate(cls.objects):
  199. cls.report(index, total * 2)
  200. subject.deps = []
  201. for mention in subject.mentions:
  202. if not mention.obj in subject.deps and not mention.obj is subject:
  203. subject.deps.append(mention.obj)
  204. for index, subject in enumerate(cls.objects):
  205. cls.report(total + index, total * 2)
  206. subject.refs = []
  207. for obj in cls.objects:
  208. if obj is subject:
  209. continue
  210. if subject in obj.deps:
  211. subject.refs.append(obj)
  212. @classmethod
  213. def run(cls, source_dir):
  214. # Liste les objets à partir de l'arborescence du repertoire des sources
  215. cls.report(0, 100, "Chargement des données")
  216. cls.load_objects(source_dir)
  217. cls.report(0, 100, "> {} objets trouvés".format(len(cls.objects)))
  218. cls.report(0, 100, "Analyse du code source".format(len(cls.objects)))
  219. cls.parse_all()
  220. cls.report(0, 100, "Construction de l'arbre des dépendances".format(len(cls.objects)))
  221. cls.build_trees()
  222. cls.report(100, 100, "Analyse terminée")
  223. cls.ended()
  224. return cls.objects
  225. @classmethod
  226. def duplicates(cls):
  227. return {k: v for k, v in cls.index.items() if len(v) > 1}
  228. if __name__ == "__main__":
  229. source_dir = here / r"test\source"
  230. resultfile = here / r"test\analyse.txt"
  231. resultfile.remove_p()
  232. def print_(i, total, msg=""):
  233. if msg:
  234. print("({}/{}) {}".format(i, total, msg))
  235. Analyse.report = print_
  236. Analyse.run(source_dir)
  237. with open(resultfile, "w+", encoding='utf-8') as f:
  238. for obj in Analyse.objects:
  239. msg = "# '{}' [{}]".format(obj.name_, obj.type_)
  240. if obj.deps:
  241. msg += "\n\tMentionne: {}".format(", ".join(["'{}' [{}]".format(dep.name_, dep.type_) for dep in obj.deps]))
  242. else:
  243. msg += "\n\t (ne mentionne aucun autre objet)"
  244. if obj.refs:
  245. msg += "\n\tEst mentionné par: {}".format(", ".join(["'{}' [{}]".format(ref.name_, ref.type_) for ref in obj.refs]))
  246. else:
  247. msg += "\n\t (n'est mentionné nul part ailleurs)"
  248. if obj.mentions:
  249. msg += "\n\t Détail:"
  250. for mention in obj.mentions:
  251. msg += "\n\t\t'{}'\t\tLine: {}\t>>\t{}".format(mention.objname, mention.line, mention.quote)
  252. if mention.warnings:
  253. msg += "\n\t\t\t! Avertissements: {}".format("|".join([w.text for w in mention.warnings]))
  254. msg += "\n"
  255. f.write(msg)
  256. print("# Terminé")