misc.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 contains miscellaneous functions that do not fit anywhere else.
  13. """
  14. import glob
  15. import os
  16. import pprint
  17. import py_compile
  18. import sys
  19. import codecs
  20. import re
  21. import tokenize
  22. import io
  23. from PyInstaller import log as logging
  24. from PyInstaller.compat import BYTECODE_MAGIC, is_win
  25. logger = logging.getLogger(__name__)
  26. def dlls_in_subdirs(directory):
  27. """
  28. Returns a list *.dll, *.so, *.dylib in the given directory and its subdirectories.
  29. """
  30. filelist = []
  31. for root, dirs, files in os.walk(directory):
  32. filelist.extend(dlls_in_dir(root))
  33. return filelist
  34. def dlls_in_dir(directory):
  35. """
  36. Returns a list of *.dll, *.so, *.dylib in the given directory.
  37. """
  38. return files_in_dir(directory, ["*.so", "*.dll", "*.dylib"])
  39. def files_in_dir(directory, file_patterns=[]):
  40. """
  41. Returns a list of files in the given directory that match the given pattern.
  42. """
  43. files = []
  44. for file_pattern in file_patterns:
  45. files.extend(glob.glob(os.path.join(directory, file_pattern)))
  46. return files
  47. def get_unicode_modules():
  48. """
  49. Try importing modules required for unicode support in the frozen application.
  50. """
  51. modules = []
  52. try:
  53. # `codecs` depends on `encodings`, so the latter are included automatically.
  54. import codecs # noqa: F401
  55. modules.append('codecs')
  56. except ImportError:
  57. logger.error("Cannot detect modules 'codecs'.")
  58. return modules
  59. def get_path_to_toplevel_modules(filename):
  60. """
  61. Return the path to top-level directory that contains Python modules.
  62. It will look in parent directories for __init__.py files. The first parent directory without __init__.py is the
  63. top-level directory.
  64. Returned directory might be used to extend the PYTHONPATH.
  65. """
  66. curr_dir = os.path.dirname(os.path.abspath(filename))
  67. pattern = '__init__.py'
  68. # Try max. 10 levels up.
  69. try:
  70. for i in range(10):
  71. files = set(os.listdir(curr_dir))
  72. # 'curr_dir' is still not top-level; go to parent dir.
  73. if pattern in files:
  74. curr_dir = os.path.dirname(curr_dir)
  75. # Top-level dir found; return it.
  76. else:
  77. return curr_dir
  78. except IOError:
  79. pass
  80. # No top-level directory found, or error was encountered.
  81. return None
  82. def mtime(fnm):
  83. try:
  84. # TODO: explain why this does not use os.path.getmtime() ?
  85. # - It is probably not used because it returns float and not int.
  86. return os.stat(fnm)[8]
  87. except Exception:
  88. return 0
  89. def compile_py_files(toc, workpath):
  90. """
  91. Given a TOC or equivalent list of tuples, generates all the required pyc/pyo files, writing in a local directory
  92. if required, and returns the list of tuples with the updated pathnames.
  93. In the old system using ImpTracker, the generated TOC of "pure" modules already contains paths to nm.pyc or
  94. nm.pyo and it is only necessary to check that these files are not older than the source. In the new system using
  95. ModuleGraph, the path given is to nm.py and we do not know if nm.pyc/.pyo exists. The following logic works with
  96. both (so if at some time modulegraph starts returning filenames of .pyc, it will cope).
  97. """
  98. # For those modules that need to be rebuilt, use the build directory PyInstaller creates during the build process.
  99. basepath = os.path.join(workpath, "localpycos")
  100. # Copy everything from toc to this new TOC, possibly unchanged.
  101. new_toc = []
  102. for (nm, fnm, typ) in toc:
  103. # Keep irrelevant items unchanged.
  104. if typ != 'PYMODULE':
  105. new_toc.append((nm, fnm, typ))
  106. continue
  107. if fnm in ('-', None):
  108. # If fmn represents a namespace then skip
  109. continue
  110. if fnm.endswith('.py'):
  111. # We are given a source path, determine the object path, if any.
  112. src_fnm = fnm
  113. # Assume we want pyo only when now running -O or -OO
  114. obj_fnm = src_fnm + ('o' if sys.flags.optimize else 'c')
  115. if not os.path.exists(obj_fnm):
  116. # Alas that one is not there so assume the other choice.
  117. obj_fnm = src_fnm + ('c' if sys.flags.optimize else 'o')
  118. else:
  119. # fnm is not "name.py", so assume we are given name.pyc/.pyo
  120. obj_fnm = fnm # take that name to be the desired object
  121. src_fnm = fnm[:-1] # drop the 'c' or 'o' to make a source name
  122. # We need to perform a build ourselves if obj_fnm does not exist, or if src_fnm is newer than obj_fnm, or if
  123. # obj_fnm was created by a different Python version.
  124. # TODO: explain why this does read()[:4] (reading all the file) instead of just read(4)? Yes for many a .pyc
  125. # file, it is all in one sector so there is no difference in I/O, but still it seems inelegant to copy it
  126. # all then subscript 4 bytes.
  127. needs_compile = mtime(src_fnm) > mtime(obj_fnm)
  128. if not needs_compile:
  129. with open(obj_fnm, 'rb') as fh:
  130. needs_compile = fh.read()[:4] != BYTECODE_MAGIC
  131. if needs_compile:
  132. try:
  133. # TODO: there should be no need to repeat the compile, because ModuleGraph does a compile and stores the
  134. # result in the .code member of the graph node. Should be possible to get the node and write the
  135. # code to obj_fnm.
  136. py_compile.compile(src_fnm, obj_fnm)
  137. logger.debug("compiled %s", src_fnm)
  138. except IOError:
  139. # If we are compiling in a system directory, we probably do not have write permissions; thus we compile
  140. # to a local directory and change the TOC entry accordingly.
  141. ext = os.path.splitext(obj_fnm)[1]
  142. if "__init__" not in obj_fnm:
  143. # If it is a normal module, use the last part of the qualified name as the module name and the first
  144. # part as the leading path.
  145. leading, mod_name = nm.split(".")[:-1], nm.split(".")[-1]
  146. else:
  147. # In case of an __init__ module, use all the qualified name as the leading path and use "__init__"
  148. # 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 TODO 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 class into scope for parsing the TOC.
  186. from PyInstaller.depend.bindepend import BindingRedirect # noqa: F401
  187. if is_win:
  188. # import versioninfo so that VSVersionInfo can parse correctly.
  189. from PyInstaller.utils.win32 import versioninfo # noqa: F401
  190. return eval(f.read())
  191. def absnormpath(apath):
  192. return os.path.abspath(os.path.normpath(apath))
  193. def module_parent_packages(full_modname):
  194. """
  195. Return list of parent package names.
  196. 'aaa.bb.c.dddd' -> ['aaa', 'aaa.bb', 'aaa.bb.c']
  197. :param full_modname: Full name of a module.
  198. :return: List of parent module names.
  199. """
  200. prefix = ''
  201. parents = []
  202. # Ignore the last component in module name and get really just parent, grandparent, great grandparent, etc.
  203. for pkg in full_modname.split('.')[0:-1]:
  204. # Ensure that first item does not start with dot '.'
  205. prefix += '.' + pkg if prefix else pkg
  206. parents.append(prefix)
  207. return parents
  208. def is_file_qt_plugin(filename):
  209. """
  210. Check if the given file is a Qt plugin file.
  211. :param filename: Full path to file to check.
  212. :return: True if given file is a Qt plugin file, False if not.
  213. """
  214. # Check the file contents; scan for QTMETADATA string. The scan is based on the brute-force Windows codepath of
  215. # findPatternUnloaded() from qtbase/src/corelib/plugin/qlibrary.cpp in Qt5.
  216. with open(filename, 'rb') as fp:
  217. fp.seek(0, os.SEEK_END)
  218. end_pos = fp.tell()
  219. SEARCH_CHUNK_SIZE = 8192
  220. QTMETADATA_MAGIC = b'QTMETADATA '
  221. magic_offset = -1
  222. while end_pos >= len(QTMETADATA_MAGIC):
  223. start_pos = max(end_pos - SEARCH_CHUNK_SIZE, 0)
  224. chunk_size = end_pos - start_pos
  225. # Is the remaining chunk large enough to hold the pattern?
  226. if chunk_size < len(QTMETADATA_MAGIC):
  227. break
  228. # Read and scan the chunk
  229. fp.seek(start_pos, os.SEEK_SET)
  230. buf = fp.read(chunk_size)
  231. pos = buf.rfind(QTMETADATA_MAGIC)
  232. if pos != -1:
  233. magic_offset = start_pos + pos
  234. break
  235. # Adjust search location for next chunk; ensure proper overlap.
  236. end_pos = start_pos + len(QTMETADATA_MAGIC) - 1
  237. if magic_offset == -1:
  238. return False
  239. return True
  240. BOM_MARKERS_TO_DECODERS = {
  241. codecs.BOM_UTF32_LE: codecs.utf_32_le_decode,
  242. codecs.BOM_UTF32_BE: codecs.utf_32_be_decode,
  243. codecs.BOM_UTF32: codecs.utf_32_decode,
  244. codecs.BOM_UTF16_LE: codecs.utf_16_le_decode,
  245. codecs.BOM_UTF16_BE: codecs.utf_16_be_decode,
  246. codecs.BOM_UTF16: codecs.utf_16_decode,
  247. codecs.BOM_UTF8: codecs.utf_8_decode,
  248. }
  249. BOM_RE = re.compile(rb"\A(%s)?(.*)" % b"|".join(map(re.escape, BOM_MARKERS_TO_DECODERS)), re.DOTALL)
  250. def decode(raw: bytes):
  251. """
  252. Decode bytes to string, respecting and removing any byte-order marks if present, or respecting but not removing any
  253. PEP263 encoding comments (# encoding: cp1252).
  254. """
  255. bom, raw = BOM_RE.match(raw).groups()
  256. if bom:
  257. return BOM_MARKERS_TO_DECODERS[bom](raw)[0]
  258. encoding, _ = tokenize.detect_encoding(io.BytesIO(raw).readline)
  259. return raw.decode(encoding)