datastruct.py 10 KB

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