misc.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2013-2023, 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 codecs
  18. import re
  19. import tokenize
  20. import io
  21. import pathlib
  22. from PyInstaller import log as logging
  23. from PyInstaller.compat import is_win
  24. logger = logging.getLogger(__name__)
  25. def dlls_in_subdirs(directory):
  26. """
  27. Returns a list *.dll, *.so, *.dylib in the given directory and its subdirectories.
  28. """
  29. filelist = []
  30. for root, dirs, files in os.walk(directory):
  31. filelist.extend(dlls_in_dir(root))
  32. return filelist
  33. def dlls_in_dir(directory):
  34. """
  35. Returns a list of *.dll, *.so, *.dylib in the given directory.
  36. """
  37. return files_in_dir(directory, ["*.so", "*.dll", "*.dylib"])
  38. def files_in_dir(directory, file_patterns=None):
  39. """
  40. Returns a list of files in the given directory that match the given pattern.
  41. """
  42. file_patterns = file_patterns or []
  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_path_to_toplevel_modules(filename):
  48. """
  49. Return the path to top-level directory that contains Python modules.
  50. It will look in parent directories for __init__.py files. The first parent directory without __init__.py is the
  51. top-level directory.
  52. Returned directory might be used to extend the PYTHONPATH.
  53. """
  54. curr_dir = os.path.dirname(os.path.abspath(filename))
  55. pattern = '__init__.py'
  56. # Try max. 10 levels up.
  57. try:
  58. for i in range(10):
  59. files = set(os.listdir(curr_dir))
  60. # 'curr_dir' is still not top-level; go to parent dir.
  61. if pattern in files:
  62. curr_dir = os.path.dirname(curr_dir)
  63. # Top-level dir found; return it.
  64. else:
  65. return curr_dir
  66. except IOError:
  67. pass
  68. # No top-level directory found, or error was encountered.
  69. return None
  70. def mtime(fnm):
  71. try:
  72. # TODO: explain why this does not use os.path.getmtime() ?
  73. # - It is probably not used because it returns float and not int.
  74. return os.stat(fnm)[8]
  75. except Exception:
  76. return 0
  77. def save_py_data_struct(filename, data):
  78. """
  79. Save data into text file as Python data structure.
  80. :param filename:
  81. :param data:
  82. :return:
  83. """
  84. dirname = os.path.dirname(filename)
  85. if not os.path.exists(dirname):
  86. os.makedirs(dirname)
  87. with open(filename, 'w', encoding='utf-8') as f:
  88. pprint.pprint(data, f)
  89. def load_py_data_struct(filename):
  90. """
  91. Load data saved as python code and interpret that code.
  92. :param filename:
  93. :return:
  94. """
  95. with open(filename, 'r', encoding='utf-8') as f:
  96. if is_win:
  97. # import versioninfo so that VSVersionInfo can parse correctly.
  98. from PyInstaller.utils.win32 import versioninfo # noqa: F401
  99. return eval(f.read())
  100. def absnormpath(apath):
  101. return os.path.abspath(os.path.normpath(apath))
  102. def module_parent_packages(full_modname):
  103. """
  104. Return list of parent package names.
  105. 'aaa.bb.c.dddd' -> ['aaa', 'aaa.bb', 'aaa.bb.c']
  106. :param full_modname: Full name of a module.
  107. :return: List of parent module names.
  108. """
  109. prefix = ''
  110. parents = []
  111. # Ignore the last component in module name and get really just parent, grandparent, great grandparent, etc.
  112. for pkg in full_modname.split('.')[0:-1]:
  113. # Ensure that first item does not start with dot '.'
  114. prefix += '.' + pkg if prefix else pkg
  115. parents.append(prefix)
  116. return parents
  117. def is_file_qt_plugin(filename):
  118. """
  119. Check if the given file is a Qt plugin file.
  120. :param filename: Full path to file to check.
  121. :return: True if given file is a Qt plugin file, False if not.
  122. """
  123. # Check the file contents; scan for QTMETADATA string. The scan is based on the brute-force Windows codepath of
  124. # findPatternUnloaded() from qtbase/src/corelib/plugin/qlibrary.cpp in Qt5.
  125. with open(filename, 'rb') as fp:
  126. fp.seek(0, os.SEEK_END)
  127. end_pos = fp.tell()
  128. SEARCH_CHUNK_SIZE = 8192
  129. QTMETADATA_MAGIC = b'QTMETADATA '
  130. magic_offset = -1
  131. while end_pos >= len(QTMETADATA_MAGIC):
  132. start_pos = max(end_pos - SEARCH_CHUNK_SIZE, 0)
  133. chunk_size = end_pos - start_pos
  134. # Is the remaining chunk large enough to hold the pattern?
  135. if chunk_size < len(QTMETADATA_MAGIC):
  136. break
  137. # Read and scan the chunk
  138. fp.seek(start_pos, os.SEEK_SET)
  139. buf = fp.read(chunk_size)
  140. pos = buf.rfind(QTMETADATA_MAGIC)
  141. if pos != -1:
  142. magic_offset = start_pos + pos
  143. break
  144. # Adjust search location for next chunk; ensure proper overlap.
  145. end_pos = start_pos + len(QTMETADATA_MAGIC) - 1
  146. if magic_offset == -1:
  147. return False
  148. return True
  149. BOM_MARKERS_TO_DECODERS = {
  150. codecs.BOM_UTF32_LE: codecs.utf_32_le_decode,
  151. codecs.BOM_UTF32_BE: codecs.utf_32_be_decode,
  152. codecs.BOM_UTF32: codecs.utf_32_decode,
  153. codecs.BOM_UTF16_LE: codecs.utf_16_le_decode,
  154. codecs.BOM_UTF16_BE: codecs.utf_16_be_decode,
  155. codecs.BOM_UTF16: codecs.utf_16_decode,
  156. codecs.BOM_UTF8: codecs.utf_8_decode,
  157. }
  158. BOM_RE = re.compile(rb"\A(%s)?(.*)" % b"|".join(map(re.escape, BOM_MARKERS_TO_DECODERS)), re.DOTALL)
  159. def decode(raw: bytes):
  160. """
  161. Decode bytes to string, respecting and removing any byte-order marks if present, or respecting but not removing any
  162. PEP263 encoding comments (# encoding: cp1252).
  163. """
  164. bom, raw = BOM_RE.match(raw).groups()
  165. if bom:
  166. return BOM_MARKERS_TO_DECODERS[bom](raw)[0]
  167. encoding, _ = tokenize.detect_encoding(io.BytesIO(raw).readline)
  168. return raw.decode(encoding)
  169. def is_iterable(arg):
  170. """
  171. Check if the passed argument is an iterable."
  172. """
  173. try:
  174. iter(arg)
  175. except TypeError:
  176. return False
  177. return True
  178. def path_to_parent_archive(filename):
  179. """
  180. Check if the given file path points to a file inside an existing archive file. Returns first path from the set of
  181. parent paths that points to an existing file, or `None` if no such path exists (i.e., file is an actual stand-alone
  182. file).
  183. """
  184. for parent in pathlib.Path(filename).parents:
  185. if parent.is_file():
  186. return parent
  187. return None