copymodules.py 6.3 KB

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