copymodules.py 6.1 KB

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