datastruct.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2022, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. import os
  12. from PyInstaller import log as logging
  13. from PyInstaller.building.utils import _check_guts_eq
  14. from PyInstaller.utils import misc
  15. logger = logging.getLogger(__name__)
  16. def unique_name(entry):
  17. """
  18. Return the filename used to enforce uniqueness for the given TOC entry.
  19. Parameters
  20. ----------
  21. entry : tuple
  22. Returns
  23. -------
  24. unique_name: str
  25. """
  26. name, path, typecode = entry
  27. if typecode in ('BINARY', 'DATA'):
  28. name = os.path.normcase(name)
  29. return name
  30. class TOC(list):
  31. # TODO: simplify the representation and use directly Modulegraph objects.
  32. """
  33. TOC (Table of Contents) class is a list of tuples of the form (name, path, typecode).
  34. typecode name path description
  35. --------------------------------------------------------------------------------------
  36. EXTENSION Python internal name. Full path name in build. Extension module.
  37. PYSOURCE Python internal name. Full path name in build. Script.
  38. PYMODULE Python internal name. Full path name in build. Pure Python module (including __init__ modules).
  39. PYZ Runtime name. Full path name in build. A .pyz archive (ZlibArchive data structure).
  40. PKG Runtime name. Full path name in build. A .pkg archive (Carchive data structure).
  41. BINARY Runtime name. Full path name in build. Shared library.
  42. DATA Runtime name. Full path name in build. Arbitrary files.
  43. OPTION The option. Unused. Python runtime option (frozen into executable).
  44. A TOC contains various types of files. A TOC contains no duplicates and preserves order.
  45. PyInstaller uses TOC data type to collect necessary files bundle them into an executable.
  46. """
  47. def __init__(self, initlist=None):
  48. super().__init__()
  49. self.filenames = set()
  50. if initlist:
  51. for entry in initlist:
  52. self.append(entry)
  53. def append(self, entry):
  54. if not isinstance(entry, tuple):
  55. logger.info("TOC found a %s, not a tuple", entry)
  56. raise TypeError("Expected tuple, not %s." % type(entry).__name__)
  57. unique = unique_name(entry)
  58. if unique not in self.filenames:
  59. self.filenames.add(unique)
  60. super().append(entry)
  61. def insert(self, pos, entry):
  62. if not isinstance(entry, tuple):
  63. logger.info("TOC found a %s, not a tuple", entry)
  64. raise TypeError("Expected tuple, not %s." % type(entry).__name__)
  65. unique = unique_name(entry)
  66. if unique not in self.filenames:
  67. self.filenames.add(unique)
  68. super().insert(pos, entry)
  69. def __add__(self, other):
  70. result = TOC(self)
  71. result.extend(other)
  72. return result
  73. def __radd__(self, other):
  74. result = TOC(other)
  75. result.extend(self)
  76. return result
  77. def __iadd__(self, other):
  78. for entry in other:
  79. self.append(entry)
  80. return self
  81. def extend(self, other):
  82. # TODO: look if this can be done more efficient with out the loop, e.g. by not using a list as base at all.
  83. for entry in other:
  84. self.append(entry)
  85. def __sub__(self, other):
  86. # Construct new TOC with entries not contained in the other TOC
  87. other = TOC(other)
  88. return TOC([entry for entry in self if unique_name(entry) not in other.filenames])
  89. def __rsub__(self, other):
  90. result = TOC(other)
  91. return result.__sub__(self)
  92. def __setitem__(self, key, value):
  93. if isinstance(key, slice):
  94. if key == slice(None, None, None):
  95. # special case: set the entire list
  96. self.filenames = set()
  97. self.clear()
  98. self.extend(value)
  99. return
  100. else:
  101. raise KeyError("TOC.__setitem__ doesn't handle slices")
  102. else:
  103. old_value = self[key]
  104. old_name = unique_name(old_value)
  105. self.filenames.remove(old_name)
  106. new_name = unique_name(value)
  107. if new_name not in self.filenames:
  108. self.filenames.add(new_name)
  109. super(TOC, self).__setitem__(key, value)
  110. class Target:
  111. invcnum = 0
  112. def __init__(self):
  113. from PyInstaller.config import CONF
  114. # Get a (per class) unique number to avoid conflicts between toc objects
  115. self.invcnum = self.__class__.invcnum
  116. self.__class__.invcnum += 1
  117. self.tocfilename = os.path.join(CONF['workpath'], '%s-%02d.toc' % (self.__class__.__name__, self.invcnum))
  118. self.tocbasename = os.path.basename(self.tocfilename)
  119. self.dependencies = TOC()
  120. def __postinit__(self):
  121. """
  122. Check if the target need to be rebuild and if so, re-assemble.
  123. `__postinit__` is to be called at the end of `__init__` of every subclass of Target. `__init__` is meant to
  124. setup the parameters and `__postinit__` is checking if rebuild is required and in case calls `assemble()`
  125. """
  126. logger.info("checking %s", self.__class__.__name__)
  127. data = None
  128. last_build = misc.mtime(self.tocfilename)
  129. if last_build == 0:
  130. logger.info("Building %s because %s is non existent", self.__class__.__name__, self.tocbasename)
  131. else:
  132. try:
  133. data = misc.load_py_data_struct(self.tocfilename)
  134. except Exception:
  135. logger.info("Building because %s is bad", self.tocbasename)
  136. else:
  137. # create a dict for easier access
  138. data = dict(zip((g[0] for g in self._GUTS), data))
  139. # assemble if previous data was not found or is outdated
  140. if not data or self._check_guts(data, last_build):
  141. self.assemble()
  142. self._save_guts()
  143. _GUTS = []
  144. def _check_guts(self, data, last_build):
  145. """
  146. Returns True if rebuild/assemble is required.
  147. """
  148. if len(data) != len(self._GUTS):
  149. logger.info("Building because %s is bad", self.tocbasename)
  150. return True
  151. for attr, func in self._GUTS:
  152. if func is None:
  153. # no check for this value
  154. continue
  155. if func(attr, data[attr], getattr(self, attr), last_build):
  156. return True
  157. return False
  158. def _save_guts(self):
  159. """
  160. Save the input parameters and the work-product of this run to maybe avoid regenerating it later.
  161. """
  162. data = tuple(getattr(self, g[0]) for g in self._GUTS)
  163. misc.save_py_data_struct(self.tocfilename, data)
  164. class Tree(Target, TOC):
  165. """
  166. This class is a way of creating a TOC (Table of Contents) that describes some or all of the files within a
  167. directory.
  168. """
  169. def __init__(self, root=None, prefix=None, excludes=None, typecode='DATA'):
  170. """
  171. root
  172. The root of the tree (on the build system).
  173. prefix
  174. Optional prefix to the names of the target system.
  175. excludes
  176. A list of names to exclude. Two forms are allowed:
  177. name
  178. Files with this basename will be excluded (do not include the path).
  179. *.ext
  180. Any file with the given extension will be excluded.
  181. typecode
  182. The typecode to be used for all files found in this tree. See the TOC class for for information about
  183. the typcodes.
  184. """
  185. Target.__init__(self)
  186. TOC.__init__(self)
  187. self.root = root
  188. self.prefix = prefix
  189. self.excludes = excludes
  190. self.typecode = typecode
  191. if excludes is None:
  192. self.excludes = []
  193. self.__postinit__()
  194. _GUTS = ( # input parameters
  195. ('root', _check_guts_eq),
  196. ('prefix', _check_guts_eq),
  197. ('excludes', _check_guts_eq),
  198. ('typecode', _check_guts_eq),
  199. ('data', None), # tested below
  200. # no calculated/analysed values
  201. )
  202. def _check_guts(self, data, last_build):
  203. if Target._check_guts(self, data, last_build):
  204. return True
  205. # Walk the collected directories as check if they have been changed - which means files have been added or
  206. # removed. There is no need to check for the files, since `Tree` is only about the directory contents (which is
  207. # the list of files).
  208. stack = [data['root']]
  209. while stack:
  210. d = stack.pop()
  211. if misc.mtime(d) > last_build:
  212. logger.info("Building %s because directory %s changed", self.tocbasename, d)
  213. return True
  214. for nm in os.listdir(d):
  215. path = os.path.join(d, nm)
  216. if os.path.isdir(path):
  217. stack.append(path)
  218. self[:] = data['data'] # collected files
  219. return False
  220. def _save_guts(self):
  221. # Use the attribute `data` to save the list
  222. self.data = self
  223. super()._save_guts()
  224. del self.data
  225. def assemble(self):
  226. logger.info("Building Tree %s", self.tocbasename)
  227. stack = [(self.root, self.prefix)]
  228. excludes = set()
  229. xexcludes = set()
  230. for name in self.excludes:
  231. if name.startswith('*'):
  232. xexcludes.add(name[1:])
  233. else:
  234. excludes.add(name)
  235. result = []
  236. while stack:
  237. dir, prefix = stack.pop()
  238. for filename in os.listdir(dir):
  239. if filename in excludes:
  240. continue
  241. ext = os.path.splitext(filename)[1]
  242. if ext in xexcludes:
  243. continue
  244. fullfilename = os.path.join(dir, filename)
  245. if prefix:
  246. resfilename = os.path.join(prefix, filename)
  247. else:
  248. resfilename = filename
  249. if os.path.isdir(fullfilename):
  250. stack.append((fullfilename, resfilename))
  251. else:
  252. result.append((resfilename, fullfilename, self.typecode))
  253. self[:] = result