install_lib.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. """distutils.command.install_lib
  2. Implements the Distutils 'install_lib' command
  3. (install all Python modules)."""
  4. import os
  5. import importlib.util
  6. import sys
  7. from distutils.core import Command
  8. from distutils.errors import DistutilsOptionError
  9. # Extension for Python source files.
  10. PYTHON_SOURCE_EXTENSION = ".py"
  11. class install_lib(Command):
  12. description = "install all Python modules (extensions and pure Python)"
  13. # The byte-compilation options are a tad confusing. Here are the
  14. # possible scenarios:
  15. # 1) no compilation at all (--no-compile --no-optimize)
  16. # 2) compile .pyc only (--compile --no-optimize; default)
  17. # 3) compile .pyc and "opt-1" .pyc (--compile --optimize)
  18. # 4) compile "opt-1" .pyc only (--no-compile --optimize)
  19. # 5) compile .pyc and "opt-2" .pyc (--compile --optimize-more)
  20. # 6) compile "opt-2" .pyc only (--no-compile --optimize-more)
  21. #
  22. # The UI for this is two options, 'compile' and 'optimize'.
  23. # 'compile' is strictly boolean, and only decides whether to
  24. # generate .pyc files. 'optimize' is three-way (0, 1, or 2), and
  25. # decides both whether to generate .pyc files and what level of
  26. # optimization to use.
  27. user_options = [
  28. ('install-dir=', 'd', "directory to install to"),
  29. ('build-dir=','b', "build directory (where to install from)"),
  30. ('force', 'f', "force installation (overwrite existing files)"),
  31. ('compile', 'c', "compile .py to .pyc [default]"),
  32. ('no-compile', None, "don't compile .py files"),
  33. ('optimize=', 'O',
  34. "also compile with optimization: -O1 for \"python -O\", "
  35. "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
  36. ('skip-build', None, "skip the build steps"),
  37. ]
  38. boolean_options = ['force', 'compile', 'skip-build']
  39. negative_opt = {'no-compile' : 'compile'}
  40. def initialize_options(self):
  41. # let the 'install' command dictate our installation directory
  42. self.install_dir = None
  43. self.build_dir = None
  44. self.force = 0
  45. self.compile = None
  46. self.optimize = None
  47. self.skip_build = None
  48. def finalize_options(self):
  49. # Get all the information we need to install pure Python modules
  50. # from the umbrella 'install' command -- build (source) directory,
  51. # install (target) directory, and whether to compile .py files.
  52. self.set_undefined_options('install',
  53. ('build_lib', 'build_dir'),
  54. ('install_lib', 'install_dir'),
  55. ('force', 'force'),
  56. ('compile', 'compile'),
  57. ('optimize', 'optimize'),
  58. ('skip_build', 'skip_build'),
  59. )
  60. if self.compile is None:
  61. self.compile = True
  62. if self.optimize is None:
  63. self.optimize = False
  64. if not isinstance(self.optimize, int):
  65. try:
  66. self.optimize = int(self.optimize)
  67. if self.optimize not in (0, 1, 2):
  68. raise AssertionError
  69. except (ValueError, AssertionError):
  70. raise DistutilsOptionError("optimize must be 0, 1, or 2")
  71. def run(self):
  72. # Make sure we have built everything we need first
  73. self.build()
  74. # Install everything: simply dump the entire contents of the build
  75. # directory to the installation directory (that's the beauty of
  76. # having a build directory!)
  77. outfiles = self.install()
  78. # (Optionally) compile .py to .pyc
  79. if outfiles is not None and self.distribution.has_pure_modules():
  80. self.byte_compile(outfiles)
  81. # -- Top-level worker functions ------------------------------------
  82. # (called from 'run()')
  83. def build(self):
  84. if not self.skip_build:
  85. if self.distribution.has_pure_modules():
  86. self.run_command('build_py')
  87. if self.distribution.has_ext_modules():
  88. self.run_command('build_ext')
  89. def install(self):
  90. if os.path.isdir(self.build_dir):
  91. outfiles = self.copy_tree(self.build_dir, self.install_dir)
  92. else:
  93. self.warn("'%s' does not exist -- no Python modules to install" %
  94. self.build_dir)
  95. return
  96. return outfiles
  97. def byte_compile(self, files):
  98. if sys.dont_write_bytecode:
  99. self.warn('byte-compiling is disabled, skipping.')
  100. return
  101. from distutils.util import byte_compile
  102. # Get the "--root" directory supplied to the "install" command,
  103. # and use it as a prefix to strip off the purported filename
  104. # encoded in bytecode files. This is far from complete, but it
  105. # should at least generate usable bytecode in RPM distributions.
  106. install_root = self.get_finalized_command('install').root
  107. if self.compile:
  108. byte_compile(files, optimize=0,
  109. force=self.force, prefix=install_root,
  110. dry_run=self.dry_run)
  111. if self.optimize > 0:
  112. byte_compile(files, optimize=self.optimize,
  113. force=self.force, prefix=install_root,
  114. verbose=self.verbose, dry_run=self.dry_run)
  115. # -- Utility methods -----------------------------------------------
  116. def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir):
  117. if not has_any:
  118. return []
  119. build_cmd = self.get_finalized_command(build_cmd)
  120. build_files = build_cmd.get_outputs()
  121. build_dir = getattr(build_cmd, cmd_option)
  122. prefix_len = len(build_dir) + len(os.sep)
  123. outputs = []
  124. for file in build_files:
  125. outputs.append(os.path.join(output_dir, file[prefix_len:]))
  126. return outputs
  127. def _bytecode_filenames(self, py_filenames):
  128. bytecode_files = []
  129. for py_file in py_filenames:
  130. # Since build_py handles package data installation, the
  131. # list of outputs can contain more than just .py files.
  132. # Make sure we only report bytecode for the .py files.
  133. ext = os.path.splitext(os.path.normcase(py_file))[1]
  134. if ext != PYTHON_SOURCE_EXTENSION:
  135. continue
  136. if self.compile:
  137. bytecode_files.append(importlib.util.cache_from_source(
  138. py_file, optimization=''))
  139. if self.optimize > 0:
  140. bytecode_files.append(importlib.util.cache_from_source(
  141. py_file, optimization=self.optimize))
  142. return bytecode_files
  143. # -- External interface --------------------------------------------
  144. # (called by outsiders)
  145. def get_outputs(self):
  146. """Return the list of files that would be installed if this command
  147. were actually run. Not affected by the "dry-run" flag or whether
  148. modules have actually been built yet.
  149. """
  150. pure_outputs = \
  151. self._mutate_outputs(self.distribution.has_pure_modules(),
  152. 'build_py', 'build_lib',
  153. self.install_dir)
  154. if self.compile:
  155. bytecode_outputs = self._bytecode_filenames(pure_outputs)
  156. else:
  157. bytecode_outputs = []
  158. ext_outputs = \
  159. self._mutate_outputs(self.distribution.has_ext_modules(),
  160. 'build_ext', 'build_lib',
  161. self.install_dir)
  162. return pure_outputs + bytecode_outputs + ext_outputs
  163. def get_inputs(self):
  164. """Get the list of files that are input to this command, ie. the
  165. files that get installed as they are named in the build tree.
  166. The files in this list correspond one-to-one to the output
  167. filenames returned by 'get_outputs()'.
  168. """
  169. inputs = []
  170. if self.distribution.has_pure_modules():
  171. build_py = self.get_finalized_command('build_py')
  172. inputs.extend(build_py.get_outputs())
  173. if self.distribution.has_ext_modules():
  174. build_ext = self.get_finalized_command('build_ext')
  175. inputs.extend(build_ext.get_outputs())
  176. return inputs