configuration.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import logging
  2. import os
  3. import subprocess
  4. from optparse import Values
  5. from typing import Any, List, Optional
  6. from pip._internal.cli.base_command import Command
  7. from pip._internal.cli.status_codes import ERROR, SUCCESS
  8. from pip._internal.configuration import (
  9. Configuration,
  10. Kind,
  11. get_configuration_files,
  12. kinds,
  13. )
  14. from pip._internal.exceptions import PipError
  15. from pip._internal.utils.logging import indent_log
  16. from pip._internal.utils.misc import get_prog, write_output
  17. logger = logging.getLogger(__name__)
  18. class ConfigurationCommand(Command):
  19. """
  20. Manage local and global configuration.
  21. Subcommands:
  22. - list: List the active configuration (or from the file specified)
  23. - edit: Edit the configuration file in an editor
  24. - get: Get the value associated with name
  25. - set: Set the name=value
  26. - unset: Unset the value associated with name
  27. - debug: List the configuration files and values defined under them
  28. If none of --user, --global and --site are passed, a virtual
  29. environment configuration file is used if one is active and the file
  30. exists. Otherwise, all modifications happen to the user file by
  31. default.
  32. """
  33. ignore_require_venv = True
  34. usage = """
  35. %prog [<file-option>] list
  36. %prog [<file-option>] [--editor <editor-path>] edit
  37. %prog [<file-option>] get name
  38. %prog [<file-option>] set name value
  39. %prog [<file-option>] unset name
  40. %prog [<file-option>] debug
  41. """
  42. def add_options(self) -> None:
  43. self.cmd_opts.add_option(
  44. "--editor",
  45. dest="editor",
  46. action="store",
  47. default=None,
  48. help=(
  49. "Editor to use to edit the file. Uses VISUAL or EDITOR "
  50. "environment variables if not provided."
  51. ),
  52. )
  53. self.cmd_opts.add_option(
  54. "--global",
  55. dest="global_file",
  56. action="store_true",
  57. default=False,
  58. help="Use the system-wide configuration file only",
  59. )
  60. self.cmd_opts.add_option(
  61. "--user",
  62. dest="user_file",
  63. action="store_true",
  64. default=False,
  65. help="Use the user configuration file only",
  66. )
  67. self.cmd_opts.add_option(
  68. "--site",
  69. dest="site_file",
  70. action="store_true",
  71. default=False,
  72. help="Use the current environment configuration file only",
  73. )
  74. self.parser.insert_option_group(0, self.cmd_opts)
  75. def run(self, options: Values, args: List[str]) -> int:
  76. handlers = {
  77. "list": self.list_values,
  78. "edit": self.open_in_editor,
  79. "get": self.get_name,
  80. "set": self.set_name_value,
  81. "unset": self.unset_name,
  82. "debug": self.list_config_values,
  83. }
  84. # Determine action
  85. if not args or args[0] not in handlers:
  86. logger.error(
  87. "Need an action (%s) to perform.",
  88. ", ".join(sorted(handlers)),
  89. )
  90. return ERROR
  91. action = args[0]
  92. # Determine which configuration files are to be loaded
  93. # Depends on whether the command is modifying.
  94. try:
  95. load_only = self._determine_file(
  96. options, need_value=(action in ["get", "set", "unset", "edit"])
  97. )
  98. except PipError as e:
  99. logger.error(e.args[0])
  100. return ERROR
  101. # Load a new configuration
  102. self.configuration = Configuration(
  103. isolated=options.isolated_mode, load_only=load_only
  104. )
  105. self.configuration.load()
  106. # Error handling happens here, not in the action-handlers.
  107. try:
  108. handlers[action](options, args[1:])
  109. except PipError as e:
  110. logger.error(e.args[0])
  111. return ERROR
  112. return SUCCESS
  113. def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]:
  114. file_options = [
  115. key
  116. for key, value in (
  117. (kinds.USER, options.user_file),
  118. (kinds.GLOBAL, options.global_file),
  119. (kinds.SITE, options.site_file),
  120. )
  121. if value
  122. ]
  123. if not file_options:
  124. if not need_value:
  125. return None
  126. # Default to user, unless there's a site file.
  127. elif any(
  128. os.path.exists(site_config_file)
  129. for site_config_file in get_configuration_files()[kinds.SITE]
  130. ):
  131. return kinds.SITE
  132. else:
  133. return kinds.USER
  134. elif len(file_options) == 1:
  135. return file_options[0]
  136. raise PipError(
  137. "Need exactly one file to operate upon "
  138. "(--user, --site, --global) to perform."
  139. )
  140. def list_values(self, options: Values, args: List[str]) -> None:
  141. self._get_n_args(args, "list", n=0)
  142. for key, value in sorted(self.configuration.items()):
  143. write_output("%s=%r", key, value)
  144. def get_name(self, options: Values, args: List[str]) -> None:
  145. key = self._get_n_args(args, "get [name]", n=1)
  146. value = self.configuration.get_value(key)
  147. write_output("%s", value)
  148. def set_name_value(self, options: Values, args: List[str]) -> None:
  149. key, value = self._get_n_args(args, "set [name] [value]", n=2)
  150. self.configuration.set_value(key, value)
  151. self._save_configuration()
  152. def unset_name(self, options: Values, args: List[str]) -> None:
  153. key = self._get_n_args(args, "unset [name]", n=1)
  154. self.configuration.unset_value(key)
  155. self._save_configuration()
  156. def list_config_values(self, options: Values, args: List[str]) -> None:
  157. """List config key-value pairs across different config files"""
  158. self._get_n_args(args, "debug", n=0)
  159. self.print_env_var_values()
  160. # Iterate over config files and print if they exist, and the
  161. # key-value pairs present in them if they do
  162. for variant, files in sorted(self.configuration.iter_config_files()):
  163. write_output("%s:", variant)
  164. for fname in files:
  165. with indent_log():
  166. file_exists = os.path.exists(fname)
  167. write_output("%s, exists: %r", fname, file_exists)
  168. if file_exists:
  169. self.print_config_file_values(variant)
  170. def print_config_file_values(self, variant: Kind) -> None:
  171. """Get key-value pairs from the file of a variant"""
  172. for name, value in self.configuration.get_values_in_config(variant).items():
  173. with indent_log():
  174. write_output("%s: %s", name, value)
  175. def print_env_var_values(self) -> None:
  176. """Get key-values pairs present as environment variables"""
  177. write_output("%s:", "env_var")
  178. with indent_log():
  179. for key, value in sorted(self.configuration.get_environ_vars()):
  180. env_var = f"PIP_{key.upper()}"
  181. write_output("%s=%r", env_var, value)
  182. def open_in_editor(self, options: Values, args: List[str]) -> None:
  183. editor = self._determine_editor(options)
  184. fname = self.configuration.get_file_to_edit()
  185. if fname is None:
  186. raise PipError("Could not determine appropriate file.")
  187. try:
  188. subprocess.check_call([editor, fname])
  189. except subprocess.CalledProcessError as e:
  190. raise PipError(
  191. "Editor Subprocess exited with exit code {}".format(e.returncode)
  192. )
  193. def _get_n_args(self, args: List[str], example: str, n: int) -> Any:
  194. """Helper to make sure the command got the right number of arguments"""
  195. if len(args) != n:
  196. msg = (
  197. "Got unexpected number of arguments, expected {}. "
  198. '(example: "{} config {}")'
  199. ).format(n, get_prog(), example)
  200. raise PipError(msg)
  201. if n == 1:
  202. return args[0]
  203. else:
  204. return args
  205. def _save_configuration(self) -> None:
  206. # We successfully ran a modifying command. Need to save the
  207. # configuration.
  208. try:
  209. self.configuration.save()
  210. except Exception:
  211. logger.exception(
  212. "Unable to save configuration. Please report this as a bug."
  213. )
  214. raise PipError("Internal Error.")
  215. def _determine_editor(self, options: Values) -> str:
  216. if options.editor is not None:
  217. return options.editor
  218. elif "VISUAL" in os.environ:
  219. return os.environ["VISUAL"]
  220. elif "EDITOR" in os.environ:
  221. return os.environ["EDITOR"]
  222. else:
  223. raise PipError("Could not determine editor to use.")