configuration.py 8.8 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 on the 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 = [key for key, value in (
  115. (kinds.USER, options.user_file),
  116. (kinds.GLOBAL, options.global_file),
  117. (kinds.SITE, options.site_file),
  118. ) if value]
  119. if not file_options:
  120. if not need_value:
  121. return None
  122. # Default to user, unless there's a site file.
  123. elif any(
  124. os.path.exists(site_config_file)
  125. for site_config_file in get_configuration_files()[kinds.SITE]
  126. ):
  127. return kinds.SITE
  128. else:
  129. return kinds.USER
  130. elif len(file_options) == 1:
  131. return file_options[0]
  132. raise PipError(
  133. "Need exactly one file to operate upon "
  134. "(--user, --site, --global) to perform."
  135. )
  136. def list_values(self, options: Values, args: List[str]) -> None:
  137. self._get_n_args(args, "list", n=0)
  138. for key, value in sorted(self.configuration.items()):
  139. write_output("%s=%r", key, value)
  140. def get_name(self, options: Values, args: List[str]) -> None:
  141. key = self._get_n_args(args, "get [name]", n=1)
  142. value = self.configuration.get_value(key)
  143. write_output("%s", value)
  144. def set_name_value(self, options: Values, args: List[str]) -> None:
  145. key, value = self._get_n_args(args, "set [name] [value]", n=2)
  146. self.configuration.set_value(key, value)
  147. self._save_configuration()
  148. def unset_name(self, options: Values, args: List[str]) -> None:
  149. key = self._get_n_args(args, "unset [name]", n=1)
  150. self.configuration.unset_value(key)
  151. self._save_configuration()
  152. def list_config_values(self, options: Values, args: List[str]) -> None:
  153. """List config key-value pairs across different config files"""
  154. self._get_n_args(args, "debug", n=0)
  155. self.print_env_var_values()
  156. # Iterate over config files and print if they exist, and the
  157. # key-value pairs present in them if they do
  158. for variant, files in sorted(self.configuration.iter_config_files()):
  159. write_output("%s:", variant)
  160. for fname in files:
  161. with indent_log():
  162. file_exists = os.path.exists(fname)
  163. write_output("%s, exists: %r",
  164. fname, file_exists)
  165. if file_exists:
  166. self.print_config_file_values(variant)
  167. def print_config_file_values(self, variant: Kind) -> None:
  168. """Get key-value pairs from the file of a variant"""
  169. for name, value in self.configuration.\
  170. get_values_in_config(variant).items():
  171. with indent_log():
  172. write_output("%s: %s", name, value)
  173. def print_env_var_values(self) -> None:
  174. """Get key-values pairs present as environment variables"""
  175. write_output("%s:", 'env_var')
  176. with indent_log():
  177. for key, value in sorted(self.configuration.get_environ_vars()):
  178. env_var = f'PIP_{key.upper()}'
  179. write_output("%s=%r", env_var, value)
  180. def open_in_editor(self, options: Values, args: List[str]) -> None:
  181. editor = self._determine_editor(options)
  182. fname = self.configuration.get_file_to_edit()
  183. if fname is None:
  184. raise PipError("Could not determine appropriate file.")
  185. try:
  186. subprocess.check_call([editor, fname])
  187. except subprocess.CalledProcessError as e:
  188. raise PipError(
  189. "Editor Subprocess exited with exit code {}"
  190. .format(e.returncode)
  191. )
  192. def _get_n_args(self, args: List[str], example: str, n: int) -> Any:
  193. """Helper to make sure the command got the right number of arguments
  194. """
  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.")