core.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. def rxname(self):
  57. return self.name_.lower().replace("?", "\?").replace(".", "\.").replace("")
  58. @classmethod
  59. def from_file(cls, file):
  60. file = Path(file)
  61. if file.ext.lower() not in cls._valid_file_exts:
  62. raise InvalidFileExt("Format de fichier d'entrée non valide ({})".format(file.name))
  63. obj = cls(AccessObject.path_to_name(file))
  64. obj.sourcefile = file
  65. obj._sourcecode = file.text()
  66. obj._sourcecode.replace("\r\n", "\n")
  67. return obj
  68. @property
  69. def sourcecode(self):
  70. if not self._sourcecode:
  71. self._sourcecode = self.sourcefile.text()
  72. return self._sourcecode
  73. @staticmethod
  74. def path_to_name(path):
  75. name_ = path.name.stripext()
  76. for ascii_code, char in {92: "\\", 47: "/", 58: ":", 42: "*", 63:"?", 34:"\"", 60:"<", 62:">", 124:"|" }.items():
  77. name_ = name_.replace("[{}]".format(ascii_code), char)
  78. return name_
  79. class TableObject(AccessObject):
  80. type_ = "Table"
  81. _valid_file_exts = (".xml", ".lnkd")
  82. _order = 10
  83. class QueryObject(AccessObject):
  84. type_ = "Query"
  85. _order = 30
  86. class FormObject(AccessObject):
  87. type_ = "Form"
  88. _order = 40
  89. class ReportObject(AccessObject):
  90. type_ = "Report"
  91. _order = 50
  92. class MacroObject(AccessObject):
  93. type_ = "Macro"
  94. _order = 60
  95. class ModuleObject(AccessObject):
  96. type_ = "Module"
  97. _order = 70
  98. @classmethod
  99. def from_file(cls, file):
  100. obj = super(ModuleObject, cls).from_file(file)
  101. rx = re.compile(r"Sub|Function ([^(]+)\(")
  102. obj.functions = [fname for fname in rx.findall(file.text()) if fname]
  103. return obj
  104. class RelationObject(AccessObject):
  105. type_ = "Relation"
  106. _valid_file_exts = (".txt")
  107. _order = 20
  108. class Analyse():
  109. objects = []
  110. glossary = {}
  111. @classmethod
  112. def report(cls, current, total, msg=""):
  113. pass
  114. @classmethod
  115. def ended(cls):
  116. pass
  117. @classmethod
  118. def dump_to(cls, filepath):
  119. with open(filepath, 'wb') as f:
  120. pickle.dump(cls.objects, f)
  121. @classmethod
  122. def load_from(cls, filepath):
  123. cls.objects = []
  124. with open(filepath, 'rb') as f:
  125. cls.objects = pickle.load(f)
  126. cls.build_glossary()
  127. @classmethod
  128. def build_glossary(cls):
  129. cls.glossary.clear()
  130. for obj in cls.objects:
  131. if not obj.name_.lower() in cls.glossary:
  132. cls.glossary[obj.name_.lower()] = []
  133. cls.glossary[obj.name_.lower()].append(obj)
  134. if type(obj) is ModuleObject:
  135. for fname in obj.functions:
  136. if not fname.lower() in cls.glossary:
  137. cls.glossary[fname.lower()] = []
  138. cls.glossary[fname.lower()].append(obj)
  139. @classmethod
  140. def load_objects(cls, source_dir):
  141. source_dir = Path(source_dir)
  142. cls.objects = []
  143. sourcemap = {
  144. "tables": TableObject,
  145. "relations": RelationObject,
  146. "queries": QueryObject,
  147. "forms": FormObject,
  148. "reports": ReportObject,
  149. "scripts": MacroObject,
  150. "modules": ModuleObject,
  151. }
  152. for dirname, accobj in sourcemap.items():
  153. for file in Path(source_dir / dirname).files():
  154. try:
  155. obj = accobj.from_file(file)
  156. cls.objects.append(obj)
  157. except InvalidFileExt:
  158. print("Ignored unrecognized file: {}".format(file))
  159. cls.objects.sort(key=lambda x: (x._order, x.name_))
  160. cls.build_glossary()
  161. @classmethod
  162. def parse_source(cls, subject):
  163. # On cherche le nom de chaque autre objet, ainsi que le nom des fonctions issues des modules
  164. look_for = {re.escape(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], []))
  165. names = "|".join(list(look_for))
  166. seps = "|".join(("\t", " ", "\[", "\]", "&", "\(", "\)", "\.", "!", "'", "\"", r"\\015", r"\\012")) # Note: Les separateurs possibles incluent \015 et \012 qui sont les hexadecimaux pour \n et \r
  167. rstr = """(?:^|{seps})({names})(?:$|{seps})""".format(seps=seps, names=names)
  168. rx = re.compile(rstr, MULTILINE | IGNORECASE)
  169. # Indexe la position des lignes
  170. line_matches = list(re.finditer('.*\n', subject.sourcecode))
  171. for match in rx.finditer(subject.sourcecode):
  172. line_number, line = next((i + 1, line) for i, line in enumerate(line_matches) if line.end() > match.start(1))
  173. quote = line.group(0).replace("\r", "").replace("\n", "").strip()
  174. objname = match.group(1)
  175. warnings = []
  176. if objname == subject.name_:
  177. obj = subject
  178. warnings.append(WarnRefItself())
  179. else:
  180. obj = cls.glossary[objname.lower()][0]
  181. if len(cls.glossary[objname.lower()]) > 1:
  182. warnings.append(WarnDuplicate())
  183. if type(subject) is ModuleObject:
  184. if re.match(r"^[^\"]*(?:\"(?:[^\"]*?)\")*[^\"]*'.*({})".format(objname), quote):
  185. warnings.append(WarnComment())
  186. if type(subject) in (FormObject, ReportObject):
  187. if re.match(r"Caption =\".*{}.*\"".format(objname), quote):
  188. warnings.append(WarnCaption())
  189. subject.mentions.append(Mention(line_number, objname, quote, obj, warnings))
  190. @classmethod
  191. def parse_all(cls):
  192. # Mise à jour des dépendances:
  193. # # parcourt les objets, et recherche dans le code source de chacun des mentions du nom des autres objets.
  194. for index, subject in enumerate(cls.objects):
  195. cls.report(index, len(cls.objects), "* {}: {}".format(subject.type_, subject.name_))
  196. cls.parse_source(subject)
  197. @classmethod
  198. def build_trees(cls):
  199. total = len(cls.objects)
  200. for index, subject in enumerate(cls.objects):
  201. cls.report(index, total * 2)
  202. subject.deps = []
  203. for mention in subject.mentions:
  204. if not mention.obj in subject.deps and not mention.obj is subject:
  205. subject.deps.append(mention.obj)
  206. for index, subject in enumerate(cls.objects):
  207. cls.report(total + index, total * 2)
  208. subject.refs = []
  209. for obj in cls.objects:
  210. if obj is subject:
  211. continue
  212. if subject in obj.deps:
  213. subject.refs.append(obj)
  214. @classmethod
  215. def run(cls, source_dir):
  216. # Liste les objets à partir de l'arborescence du repertoire des sources
  217. cls.report(0, 100, "Chargement des données")
  218. cls.load_objects(source_dir)
  219. cls.report(0, 100, "> {} objets trouvés".format(len(cls.objects)))
  220. cls.report(0, 100, "Analyse du code source".format(len(cls.objects)))
  221. cls.parse_all()
  222. cls.report(0, 100, "Construction de l'arbre des dépendances".format(len(cls.objects)))
  223. cls.build_trees()
  224. cls.report(100, 100, "Analyse terminée")
  225. cls.ended()
  226. return cls.objects
  227. @classmethod
  228. def duplicates(cls):
  229. return {k: v for k, v in cls.index.items() if len(v) > 1}
  230. if __name__ == "__main__":
  231. source_dir = here / r"test\source"
  232. resultfile = here / r"test\analyse.txt"
  233. resultfile.remove_p()
  234. def print_(i, total, msg=""):
  235. if msg:
  236. print("({}/{}) {}".format(i, total, msg))
  237. Analyse.report = print_
  238. Analyse.run(source_dir)
  239. with open(resultfile, "w+", encoding='utf-8') as f:
  240. for obj in Analyse.objects:
  241. msg = "# '{}' [{}]".format(obj.name_, obj.type_)
  242. if obj.deps:
  243. msg += "\n\tMentionne: {}".format(", ".join(["'{}' [{}]".format(dep.name_, dep.type_) for dep in obj.deps]))
  244. else:
  245. msg += "\n\t (ne mentionne aucun autre objet)"
  246. if obj.refs:
  247. msg += "\n\tEst mentionné par: {}".format(", ".join(["'{}' [{}]".format(ref.name_, ref.type_) for ref in obj.refs]))
  248. else:
  249. msg += "\n\t (n'est mentionné nul part ailleurs)"
  250. if obj.mentions:
  251. msg += "\n\t Détail:"
  252. for mention in obj.mentions:
  253. msg += "\n\t\t'{}'\t\tLine: {}\t>>\t{}".format(mention.objname, mention.line, mention.quote)
  254. if mention.warnings:
  255. msg += "\n\t\t\t! Avertissements: {}".format("|".join([w.text for w in mention.warnings]))
  256. msg += "\n"
  257. f.write(msg)
  258. print("# Terminé")