copymodules.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import os
  2. import shutil
  3. import sys
  4. import tempfile
  5. import zipfile, zipimport
  6. pjoin = os.path.join
  7. PY2 = sys.version_info[0] == 2
  8. running_python = '.'.join(str(x) for x in sys.version_info[:2])
  9. class ExtensionModuleMismatch(ImportError):
  10. pass
  11. extensionmod_errmsg = """Found an extension module that will not be usable on %s:
  12. %s
  13. Put Windows packages in pynsist_pkgs/ to avoid this."""
  14. def check_ext_mod(path, target_python):
  15. """If path is an extension module, check that it matches target platform.
  16. It should be for Windows and we should be running on the same version
  17. of Python that we're targeting. Raises ExtensionModuleMismatch if not.
  18. Does nothing if path is not an extension module.
  19. """
  20. if path.endswith('.so'):
  21. raise ExtensionModuleMismatch(extensionmod_errmsg % ('Windows', path))
  22. elif path.endswith('.pyd') and not target_python.startswith(running_python):
  23. # TODO: From Python 3.2, extension modules can restrict themselves
  24. # to a stable ABI. Can we detect this?
  25. raise ExtensionModuleMismatch(extensionmod_errmsg % ('Python '+target_python, path))
  26. def check_package_for_ext_mods(path, target_python):
  27. """Walk the directory path, calling :func:`check_ext_mod` on each file.
  28. """
  29. for dirpath, dirnames, filenames in os.walk(path):
  30. for filename in filenames:
  31. check_ext_mod(os.path.join(path, dirpath, filename), target_python)
  32. def copy_zipmodule(loader, modname, target):
  33. """Copy a module or package out of a zip file to the target directory."""
  34. file = loader.get_filename(modname)
  35. assert file.startswith(loader.archive)
  36. path_in_zip = file[len(loader.archive+'/'):]
  37. zf = zipfile.ZipFile(loader.archive)
  38. # If the packages are in a subdirectory, extracting them recreates the
  39. # directory structure from the zip file. So extract to a temp dir first,
  40. # and then copy the modules to target.
  41. tempdir = tempfile.mkdtemp()
  42. if loader.is_package(modname):
  43. # Extract everything in a folder
  44. pkgdir, basename = path_in_zip.rsplit('/', 1)
  45. assert basename.startswith('__init__')
  46. pkgfiles = [f for f in zf.namelist() if f.startswith(pkgdir)]
  47. zf.extractall(tempdir, pkgfiles)
  48. shutil.copytree(pjoin(tempdir, pkgdir), pjoin(target, modname))
  49. else:
  50. # Extract a single file
  51. zf.extract(path_in_zip, tempdir)
  52. shutil.copy2(pjoin(tempdir, path_in_zip), target)
  53. shutil.rmtree(tempdir)
  54. if not PY2:
  55. import importlib
  56. import importlib.abc
  57. import importlib.machinery
  58. class ModuleCopier:
  59. """Finds and copies importable Python modules and packages.
  60. This is the Python >3.3 version and uses the `importlib` package to
  61. locate modules.
  62. """
  63. def __init__(self, py_version, path=None):
  64. self.py_version = py_version
  65. self.path = path if (path is not None) else ([''] + sys.path)
  66. def copy(self, modname, target):
  67. """Copy the importable module 'modname' to the directory 'target'.
  68. modname should be a top-level import, i.e. without any dots.
  69. Packages are always copied whole.
  70. This can currently copy regular filesystem files and directories,
  71. and extract modules and packages from appropriately structured zip
  72. files.
  73. """
  74. loader = importlib.find_loader(modname, self.path)
  75. if loader is None:
  76. raise ImportError('Could not find %s' % modname)
  77. pkg = loader.is_package(modname)
  78. if isinstance(loader, importlib.machinery.ExtensionFileLoader):
  79. check_ext_mod(loader.path, self.py_version)
  80. shutil.copy2(loader.path, target)
  81. elif isinstance(loader, importlib.abc.FileLoader):
  82. file = loader.get_filename(modname)
  83. if pkg:
  84. pkgdir, basename = os.path.split(file)
  85. assert basename.startswith('__init__')
  86. check_package_for_ext_mods(pkgdir, self.py_version)
  87. dest = os.path.join(target, modname)
  88. shutil.copytree(pkgdir, dest,
  89. ignore=shutil.ignore_patterns('*.pyc'))
  90. else:
  91. shutil.copy2(file, target)
  92. elif isinstance(loader, zipimport.zipimporter):
  93. copy_zipmodule(loader, modname, target)
  94. else:
  95. import imp
  96. class ModuleCopier:
  97. """Finds and copies importable Python modules and packages.
  98. This is the Python 2.7 version and uses the `imp` package to locate
  99. modules.
  100. """
  101. def __init__(self, py_version, path=None):
  102. self.py_version = py_version
  103. self.path = path if (path is not None) else ([''] + sys.path)
  104. self.zip_paths = [p for p in self.path if zipfile.is_zipfile(p)]
  105. def copy(self, modname, target):
  106. """Copy the importable module 'modname' to the directory 'target'.
  107. modname should be a top-level import, i.e. without any dots.
  108. Packages are always copied whole.
  109. This can currently copy regular filesystem files and directories,
  110. and extract modules and packages from appropriately structured zip
  111. files.
  112. """
  113. try:
  114. info = imp.find_module(modname, self.path)
  115. except ImportError:
  116. # Search all ZIP files in self.path for the module name
  117. # NOTE: `imp.find_module(...)` will *not* find modules in ZIP
  118. # files, so we have to check each file for ourselves
  119. for zpath in self.zip_paths:
  120. loader = zipimport.zipimporter(zpath)
  121. if loader.find_module(modname) is None:
  122. continue
  123. copy_zipmodule(loader, modname, target)
  124. return
  125. # Not found in zip files either - re-raise exception
  126. raise
  127. path = info[1]
  128. modtype = info[2][2]
  129. if modtype == imp.C_EXTENSION:
  130. check_ext_mod(path, self.py_version)
  131. if modtype in (imp.PY_SOURCE, imp.C_EXTENSION):
  132. shutil.copy2(path, target)
  133. elif modtype == imp.PKG_DIRECTORY:
  134. check_package_for_ext_mods(path, self.py_version)
  135. dest = os.path.join(target, modname)
  136. shutil.copytree(path, dest,
  137. ignore=shutil.ignore_patterns('*.pyc'))
  138. def copy_modules(modnames, target, py_version, path=None):
  139. """Copy the specified importable modules to the target directory.
  140. By default, it finds modules in sys.path - this can be overridden by passing
  141. the path parameter.
  142. """
  143. mc = ModuleCopier(py_version, path)
  144. files_in_target_noext = [os.path.splitext(f)[0] for f in os.listdir(target)]
  145. for modname in modnames:
  146. if modname in files_in_target_noext:
  147. # Already there, no need to copy it.
  148. continue
  149. mc.copy(modname, target)
  150. if not modnames:
  151. # NSIS abhors an empty folder, so give it a file to find.
  152. with open(os.path.join(target, 'placeholder'), 'w') as f:
  153. f.write('This file only exists so NSIS finds something in this directory.')