misc.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2013-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. """
  12. This module is for the miscellaneous routines which do not fit somewhere else.
  13. """
  14. import glob
  15. import os
  16. import pprint
  17. import py_compile
  18. import sys
  19. from PyInstaller import log as logging
  20. from PyInstaller.compat import BYTECODE_MAGIC, is_win
  21. logger = logging.getLogger(__name__)
  22. def dlls_in_subdirs(directory):
  23. """Returns a list *.dll, *.so, *.dylib in given directories and subdirectories."""
  24. filelist = []
  25. for root, dirs, files in os.walk(directory):
  26. filelist.extend(dlls_in_dir(root))
  27. return filelist
  28. def dlls_in_dir(directory):
  29. """Returns a list of *.dll, *.so, *.dylib in given directory."""
  30. return files_in_dir(directory, ["*.so", "*.dll", "*.dylib"])
  31. def files_in_dir(directory, file_patterns=[]):
  32. """Returns a list of files which match a pattern in given directory."""
  33. files = []
  34. for file_pattern in file_patterns:
  35. files.extend(glob.glob(os.path.join(directory, file_pattern)))
  36. return files
  37. def get_unicode_modules():
  38. """
  39. Try importing codecs and encodings to include unicode support
  40. in created binary.
  41. """
  42. modules = []
  43. try:
  44. # `codecs` depends on `encodings` and this is then included.
  45. import codecs
  46. modules.append('codecs')
  47. except ImportError:
  48. logger.error("Cannot detect modules 'codecs'.")
  49. return modules
  50. def get_path_to_toplevel_modules(filename):
  51. """
  52. Return the path to top-level directory that contains Python modules.
  53. It will look in parent directories for __init__.py files. The first parent
  54. directory without __init__.py is the top-level directory.
  55. Returned directory might be used to extend the PYTHONPATH.
  56. """
  57. curr_dir = os.path.dirname(os.path.abspath(filename))
  58. pattern = '__init__.py'
  59. # Try max. 10 levels up.
  60. try:
  61. for i in range(10):
  62. files = set(os.listdir(curr_dir))
  63. # 'curr_dir' is still not top-leve go to parent dir.
  64. if pattern in files:
  65. curr_dir = os.path.dirname(curr_dir)
  66. # Top-level dir found - return it.
  67. else:
  68. return curr_dir
  69. except IOError:
  70. pass
  71. # No top-level directory found or any error.
  72. return None
  73. def mtime(fnm):
  74. try:
  75. # TODO: explain why this doesn't use os.path.getmtime() ?
  76. # - It is probably not used because it returns float and not int.
  77. return os.stat(fnm)[8]
  78. except:
  79. return 0
  80. def compile_py_files(toc, workpath):
  81. """
  82. Given a TOC or equivalent list of tuples, generates all the required
  83. pyc/pyo files, writing in a local directory if required, and returns the
  84. list of tuples with the updated pathnames.
  85. In the old system using ImpTracker, the generated TOC of "pure" modules
  86. already contains paths to nm.pyc or nm.pyo and it is only necessary
  87. to check that these files are not older than the source.
  88. In the new system using ModuleGraph, the path given is to nm.py
  89. and we do not know if nm.pyc/.pyo exists. The following logic works
  90. with both (so if at some time modulegraph starts returning filenames
  91. of .pyc, it will cope).
  92. """
  93. # For those modules that need to be rebuilt, use the build directory
  94. # PyInstaller creates during the build process.
  95. basepath = os.path.join(workpath, "localpycos")
  96. # Copy everything from toc to this new TOC, possibly unchanged.
  97. new_toc = []
  98. for (nm, fnm, typ) in toc:
  99. # Keep unrelevant items unchanged.
  100. if typ != 'PYMODULE':
  101. new_toc.append((nm, fnm, typ))
  102. continue
  103. if fnm in ('-', None):
  104. # If fmn represents a namespace then skip
  105. continue
  106. if fnm.endswith('.py') :
  107. # we are given a source path, determine the object path if any
  108. src_fnm = fnm
  109. # assume we want pyo only when now running -O or -OO
  110. obj_fnm = src_fnm + ('o' if sys.flags.optimize else 'c')
  111. if not os.path.exists(obj_fnm) :
  112. # alas that one is not there so assume the other choice
  113. obj_fnm = src_fnm + ('c' if sys.flags.optimize else 'o')
  114. else:
  115. # fnm is not "name.py" so assume we are given name.pyc/.pyo
  116. obj_fnm = fnm # take that namae to be the desired object
  117. src_fnm = fnm[:-1] # drop the 'c' or 'o' to make a source name
  118. # We need to perform a build ourselves if obj_fnm doesn't exist,
  119. # or if src_fnm is newer than obj_fnm, or if obj_fnm was created
  120. # by a different Python version.
  121. # TODO: explain why this does read()[:4] (reading all the file)
  122. # instead of just read(4)? Yes for many a .pyc file, it is all
  123. # in one sector so there's no difference in I/O but still it
  124. # seems inelegant to copy it all then subscript 4 bytes.
  125. needs_compile = mtime(src_fnm) > mtime(obj_fnm)
  126. if not needs_compile:
  127. with open(obj_fnm, 'rb') as fh:
  128. needs_compile = fh.read()[:4] != BYTECODE_MAGIC
  129. if needs_compile:
  130. try:
  131. # TODO: there should be no need to repeat the compile,
  132. # because ModuleGraph does a compile and stores the result
  133. # in the .code member of the graph node. Should be possible
  134. # to get the node and write the code to obj_fnm
  135. py_compile.compile(src_fnm, obj_fnm)
  136. logger.debug("compiled %s", src_fnm)
  137. except IOError:
  138. # If we're compiling on a system directory, probably we don't
  139. # have write permissions; thus we compile to a local directory
  140. # and change the TOC entry accordingly.
  141. ext = os.path.splitext(obj_fnm)[1]
  142. if "__init__" not in obj_fnm:
  143. # If it's a normal module, use last part of the qualified
  144. # name as module name and the first as leading path
  145. leading, mod_name = nm.split(".")[:-1], nm.split(".")[-1]
  146. else:
  147. # In case of a __init__ module, use all the qualified name
  148. # as leading path and use "__init__" as the module name
  149. leading, mod_name = nm.split("."), "__init__"
  150. leading = os.path.join(basepath, *leading)
  151. if not os.path.exists(leading):
  152. os.makedirs(leading)
  153. obj_fnm = os.path.join(leading, mod_name + ext)
  154. # TODO see above regarding read()[:4] versus read(4)
  155. needs_compile = mtime(src_fnm) > mtime(obj_fnm)
  156. if not needs_compile:
  157. with open(obj_fnm, 'rb') as fh:
  158. needs_compile = fh.read()[:4] != BYTECODE_MAGIC
  159. if needs_compile:
  160. # TODO see above todo regarding using node.code
  161. py_compile.compile(src_fnm, obj_fnm)
  162. logger.debug("compiled %s", src_fnm)
  163. # if we get to here, obj_fnm is the path to the compiled module nm.py
  164. new_toc.append((nm, obj_fnm, typ))
  165. return new_toc
  166. def save_py_data_struct(filename, data):
  167. """
  168. Save data into text file as Python data structure.
  169. :param filename:
  170. :param data:
  171. :return:
  172. """
  173. dirname = os.path.dirname(filename)
  174. if not os.path.exists(dirname):
  175. os.makedirs(dirname)
  176. with open(filename, 'w', encoding='utf-8') as f:
  177. pprint.pprint(data, f)
  178. def load_py_data_struct(filename):
  179. """
  180. Load data saved as python code and interpret that code.
  181. :param filename:
  182. :return:
  183. """
  184. with open(filename, 'r', encoding='utf-8') as f:
  185. # Binding redirects are stored as a named tuple, so bring the namedtuple
  186. # class into scope for parsing the TOC.
  187. from PyInstaller.depend.bindepend import BindingRedirect # noqa: F401
  188. if is_win:
  189. # import versioninfo so that VSVersionInfo can parse correctly
  190. from PyInstaller.utils.win32 import versioninfo # noqa: F401
  191. return eval(f.read())
  192. def absnormpath(apath):
  193. return os.path.abspath(os.path.normpath(apath))
  194. def module_parent_packages(full_modname):
  195. """
  196. Return list of parent package names.
  197. 'aaa.bb.c.dddd' -> ['aaa', 'aaa.bb', 'aaa.bb.c']
  198. :param full_modname: Full name of a module.
  199. :return: List of parent module names.
  200. """
  201. prefix = ''
  202. parents = []
  203. # Ignore the last component in module name and get really just
  204. # parent, grand parent, grandgrand parent, etc.
  205. for pkg in full_modname.split('.')[0:-1]:
  206. # Ensure first item does not start with dot '.'
  207. prefix += '.' + pkg if prefix else pkg
  208. parents.append(prefix)
  209. return parents
  210. def is_file_qt_plugin(filename):
  211. """
  212. Check if the given file is a Qt plugin file.
  213. :param filename: Full path to file to check.
  214. :return: True if given file is a Qt plugin file, False if not.
  215. """
  216. # Check the file contents; scan for QTMETADATA string
  217. # The scan is based on the brute-force Windows codepath of
  218. # findPatternUnloaded() from qtbase/src/corelib/plugin/qlibrary.cpp
  219. # in Qt5.
  220. with open(filename, 'rb') as fp:
  221. fp.seek(0, os.SEEK_END)
  222. end_pos = fp.tell()
  223. SEARCH_CHUNK_SIZE = 8192
  224. QTMETADATA_MAGIC = b'QTMETADATA '
  225. magic_offset = -1
  226. while end_pos >= len(QTMETADATA_MAGIC):
  227. start_pos = max(end_pos - SEARCH_CHUNK_SIZE, 0)
  228. chunk_size = end_pos - start_pos
  229. # Is the remaining chunk large enough to hold the pattern?
  230. if chunk_size < len(QTMETADATA_MAGIC):
  231. break
  232. # Read and scan the chunk
  233. fp.seek(start_pos, os.SEEK_SET)
  234. buf = fp.read(chunk_size)
  235. pos = buf.rfind(QTMETADATA_MAGIC)
  236. if pos != -1:
  237. magic_offset = start_pos + pos
  238. break
  239. # Adjust search location for next chunk; ensure proper
  240. # overlap
  241. end_pos = start_pos + len(QTMETADATA_MAGIC) - 1
  242. if magic_offset == -1:
  243. return False
  244. return True