copymodules.py 6.6 KB

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