base_command.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """Base Command class, and related routines"""
  2. import functools
  3. import logging
  4. import logging.config
  5. import optparse
  6. import os
  7. import sys
  8. import traceback
  9. from optparse import Values
  10. from typing import Any, Callable, List, Optional, Tuple
  11. from pip._vendor.rich import traceback as rich_traceback
  12. from pip._internal.cli import cmdoptions
  13. from pip._internal.cli.command_context import CommandContextMixIn
  14. from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
  15. from pip._internal.cli.status_codes import (
  16. ERROR,
  17. PREVIOUS_BUILD_DIR_ERROR,
  18. UNKNOWN_ERROR,
  19. VIRTUALENV_NOT_FOUND,
  20. )
  21. from pip._internal.exceptions import (
  22. BadCommand,
  23. CommandError,
  24. DiagnosticPipError,
  25. InstallationError,
  26. NetworkConnectionError,
  27. PreviousBuildDirError,
  28. UninstallationError,
  29. )
  30. from pip._internal.utils.filesystem import check_path_owner
  31. from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging
  32. from pip._internal.utils.misc import get_prog, normalize_path
  33. from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry
  34. from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
  35. from pip._internal.utils.virtualenv import running_under_virtualenv
  36. __all__ = ["Command"]
  37. logger = logging.getLogger(__name__)
  38. class Command(CommandContextMixIn):
  39. usage: str = ""
  40. ignore_require_venv: bool = False
  41. def __init__(self, name: str, summary: str, isolated: bool = False) -> None:
  42. super().__init__()
  43. self.name = name
  44. self.summary = summary
  45. self.parser = ConfigOptionParser(
  46. usage=self.usage,
  47. prog=f"{get_prog()} {name}",
  48. formatter=UpdatingDefaultsHelpFormatter(),
  49. add_help_option=False,
  50. name=name,
  51. description=self.__doc__,
  52. isolated=isolated,
  53. )
  54. self.tempdir_registry: Optional[TempDirRegistry] = None
  55. # Commands should add options to this option group
  56. optgroup_name = f"{self.name.capitalize()} Options"
  57. self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
  58. # Add the general options
  59. gen_opts = cmdoptions.make_option_group(
  60. cmdoptions.general_group,
  61. self.parser,
  62. )
  63. self.parser.add_option_group(gen_opts)
  64. self.add_options()
  65. def add_options(self) -> None:
  66. pass
  67. def handle_pip_version_check(self, options: Values) -> None:
  68. """
  69. This is a no-op so that commands by default do not do the pip version
  70. check.
  71. """
  72. # Make sure we do the pip version check if the index_group options
  73. # are present.
  74. assert not hasattr(options, "no_index")
  75. def run(self, options: Values, args: List[str]) -> int:
  76. raise NotImplementedError
  77. def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]:
  78. # factored out for testability
  79. return self.parser.parse_args(args)
  80. def main(self, args: List[str]) -> int:
  81. try:
  82. with self.main_context():
  83. return self._main(args)
  84. finally:
  85. logging.shutdown()
  86. def _main(self, args: List[str]) -> int:
  87. # We must initialize this before the tempdir manager, otherwise the
  88. # configuration would not be accessible by the time we clean up the
  89. # tempdir manager.
  90. self.tempdir_registry = self.enter_context(tempdir_registry())
  91. # Intentionally set as early as possible so globally-managed temporary
  92. # directories are available to the rest of the code.
  93. self.enter_context(global_tempdir_manager())
  94. options, args = self.parse_args(args)
  95. # Set verbosity so that it can be used elsewhere.
  96. self.verbosity = options.verbose - options.quiet
  97. level_number = setup_logging(
  98. verbosity=self.verbosity,
  99. no_color=options.no_color,
  100. user_log_file=options.log,
  101. )
  102. # TODO: Try to get these passing down from the command?
  103. # without resorting to os.environ to hold these.
  104. # This also affects isolated builds and it should.
  105. if options.no_input:
  106. os.environ["PIP_NO_INPUT"] = "1"
  107. if options.exists_action:
  108. os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
  109. if options.require_venv and not self.ignore_require_venv:
  110. # If a venv is required check if it can really be found
  111. if not running_under_virtualenv():
  112. logger.critical("Could not find an activated virtualenv (required).")
  113. sys.exit(VIRTUALENV_NOT_FOUND)
  114. if options.cache_dir:
  115. options.cache_dir = normalize_path(options.cache_dir)
  116. if not check_path_owner(options.cache_dir):
  117. logger.warning(
  118. "The directory '%s' or its parent directory is not owned "
  119. "or is not writable by the current user. The cache "
  120. "has been disabled. Check the permissions and owner of "
  121. "that directory. If executing pip with sudo, you should "
  122. "use sudo's -H flag.",
  123. options.cache_dir,
  124. )
  125. options.cache_dir = None
  126. if "2020-resolver" in options.features_enabled:
  127. logger.warning(
  128. "--use-feature=2020-resolver no longer has any effect, "
  129. "since it is now the default dependency resolver in pip. "
  130. "This will become an error in pip 21.0."
  131. )
  132. def intercepts_unhandled_exc(
  133. run_func: Callable[..., int]
  134. ) -> Callable[..., int]:
  135. @functools.wraps(run_func)
  136. def exc_logging_wrapper(*args: Any) -> int:
  137. try:
  138. status = run_func(*args)
  139. assert isinstance(status, int)
  140. return status
  141. except DiagnosticPipError as exc:
  142. logger.error("[present-diagnostic] %s", exc)
  143. logger.debug("Exception information:", exc_info=True)
  144. return ERROR
  145. except PreviousBuildDirError as exc:
  146. logger.critical(str(exc))
  147. logger.debug("Exception information:", exc_info=True)
  148. return PREVIOUS_BUILD_DIR_ERROR
  149. except (
  150. InstallationError,
  151. UninstallationError,
  152. BadCommand,
  153. NetworkConnectionError,
  154. ) as exc:
  155. logger.critical(str(exc))
  156. logger.debug("Exception information:", exc_info=True)
  157. return ERROR
  158. except CommandError as exc:
  159. logger.critical("%s", exc)
  160. logger.debug("Exception information:", exc_info=True)
  161. return ERROR
  162. except BrokenStdoutLoggingError:
  163. # Bypass our logger and write any remaining messages to
  164. # stderr because stdout no longer works.
  165. print("ERROR: Pipe to stdout was broken", file=sys.stderr)
  166. if level_number <= logging.DEBUG:
  167. traceback.print_exc(file=sys.stderr)
  168. return ERROR
  169. except KeyboardInterrupt:
  170. logger.critical("Operation cancelled by user")
  171. logger.debug("Exception information:", exc_info=True)
  172. return ERROR
  173. except BaseException:
  174. logger.critical("Exception:", exc_info=True)
  175. return UNKNOWN_ERROR
  176. return exc_logging_wrapper
  177. try:
  178. if not options.debug_mode:
  179. run = intercepts_unhandled_exc(self.run)
  180. else:
  181. run = self.run
  182. rich_traceback.install(show_locals=True)
  183. return run(options, args)
  184. finally:
  185. self.handle_pip_version_check(options)