datastruct.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2021, 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 extend(self, other):
  78. # TODO: look if this can be done more efficient with out the loop, e.g. by not using a list as base at all.
  79. for entry in other:
  80. self.append(entry)
  81. def __sub__(self, other):
  82. other = TOC(other)
  83. filenames = self.filenames - other.filenames
  84. result = TOC()
  85. for entry in self:
  86. unique = unique_name(entry)
  87. if unique in filenames:
  88. # Directly use list.append() instead of TOC.append() to avoid unnecessary uniqueness checks.
  89. # Hence the use of super(TOC, result).
  90. super(TOC, result).append(entry)
  91. return result
  92. def __rsub__(self, other):
  93. result = TOC(other)
  94. return result.__sub__(self)
  95. class Target(object):
  96. invcnum = 0
  97. def __init__(self):
  98. from PyInstaller.config import CONF
  99. # Get a (per class) unique number to avoid conflicts between toc objects
  100. self.invcnum = self.__class__.invcnum
  101. self.__class__.invcnum += 1
  102. self.tocfilename = os.path.join(CONF['workpath'], '%s-%02d.toc' % (self.__class__.__name__, self.invcnum))
  103. self.tocbasename = os.path.basename(self.tocfilename)
  104. self.dependencies = TOC()
  105. def __postinit__(self):
  106. """
  107. Check if the target need to be rebuild and if so, re-assemble.
  108. `__postinit__` is to be called at the end of `__init__` of every subclass of Target. `__init__` is meant to
  109. setup the parameters and `__postinit__` is checking if rebuild is required and in case calls `assemble()`
  110. """
  111. logger.info("checking %s", self.__class__.__name__)
  112. data = None
  113. last_build = misc.mtime(self.tocfilename)
  114. if last_build == 0:
  115. logger.info("Building %s because %s is non existent", self.__class__.__name__, self.tocbasename)
  116. else:
  117. try:
  118. data = misc.load_py_data_struct(self.tocfilename)
  119. except Exception:
  120. logger.info("Building because %s is bad", self.tocbasename)
  121. else:
  122. # create a dict for easier access
  123. data = dict(zip((g[0] for g in self._GUTS), data))
  124. # assemble if previous data was not found or is outdated
  125. if not data or self._check_guts(data, last_build):
  126. self.assemble()
  127. self._save_guts()
  128. _GUTS = []
  129. def _check_guts(self, data, last_build):
  130. """
  131. Returns True if rebuild/assemble is required.
  132. """
  133. if len(data) != len(self._GUTS):
  134. logger.info("Building because %s is bad", self.tocbasename)
  135. return True
  136. for attr, func in self._GUTS:
  137. if func is None:
  138. # no check for this value
  139. continue
  140. if func(attr, data[attr], getattr(self, attr), last_build):
  141. return True
  142. return False
  143. def _save_guts(self):
  144. """
  145. Save the input parameters and the work-product of this run to maybe avoid regenerating it later.
  146. """
  147. data = tuple(getattr(self, g[0]) for g in self._GUTS)
  148. misc.save_py_data_struct(self.tocfilename, data)
  149. class Tree(Target, TOC):
  150. """
  151. This class is a way of creating a TOC (Table of Contents) that describes some or all of the files within a
  152. directory.
  153. """
  154. def __init__(self, root=None, prefix=None, excludes=None, typecode='DATA'):
  155. """
  156. root
  157. The root of the tree (on the build system).
  158. prefix
  159. Optional prefix to the names of the target system.
  160. excludes
  161. A list of names to exclude. Two forms are allowed:
  162. name
  163. Files with this basename will be excluded (do not include the path).
  164. *.ext
  165. Any file with the given extension will be excluded.
  166. typecode
  167. The typecode to be used for all files found in this tree. See the TOC class for for information about
  168. the typcodes.
  169. """
  170. Target.__init__(self)
  171. TOC.__init__(self)
  172. self.root = root
  173. self.prefix = prefix
  174. self.excludes = excludes
  175. self.typecode = typecode
  176. if excludes is None:
  177. self.excludes = []
  178. self.__postinit__()
  179. _GUTS = ( # input parameters
  180. ('root', _check_guts_eq),
  181. ('prefix', _check_guts_eq),
  182. ('excludes', _check_guts_eq),
  183. ('typecode', _check_guts_eq),
  184. ('data', None), # tested below
  185. # no calculated/analysed values
  186. )
  187. def _check_guts(self, data, last_build):
  188. if Target._check_guts(self, data, last_build):
  189. return True
  190. # Walk the collected directories as check if they have been changed - which means files have been added or
  191. # removed. There is no need to check for the files, since `Tree` is only about the directory contents (which is
  192. # the list of files).
  193. stack = [data['root']]
  194. while stack:
  195. d = stack.pop()
  196. if misc.mtime(d) > last_build:
  197. logger.info("Building %s because directory %s changed", self.tocbasename, d)
  198. return True
  199. for nm in os.listdir(d):
  200. path = os.path.join(d, nm)
  201. if os.path.isdir(path):
  202. stack.append(path)
  203. self[:] = data['data'] # collected files
  204. return False
  205. def _save_guts(self):
  206. # Use the attribute `data` to save the list
  207. self.data = self
  208. super()._save_guts()
  209. del self.data
  210. def assemble(self):
  211. logger.info("Building Tree %s", self.tocbasename)
  212. stack = [(self.root, self.prefix)]
  213. excludes = set()
  214. xexcludes = set()
  215. for name in self.excludes:
  216. if name.startswith('*'):
  217. xexcludes.add(name[1:])
  218. else:
  219. excludes.add(name)
  220. result = []
  221. while stack:
  222. dir, prefix = stack.pop()
  223. for filename in os.listdir(dir):
  224. if filename in excludes:
  225. continue
  226. ext = os.path.splitext(filename)[1]
  227. if ext in xexcludes:
  228. continue
  229. fullfilename = os.path.join(dir, filename)
  230. if prefix:
  231. resfilename = os.path.join(prefix, filename)
  232. else:
  233. resfilename = filename
  234. if os.path.isdir(fullfilename):
  235. stack.append((fullfilename, resfilename))
  236. else:
  237. result.append((resfilename, fullfilename, self.typecode))
  238. self[:] = result