configuration.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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):
  43. # type: () -> None
  44. self.cmd_opts.add_option(
  45. '--editor',
  46. dest='editor',
  47. action='store',
  48. default=None,
  49. help=(
  50. 'Editor to use to edit the file. Uses VISUAL or EDITOR '
  51. 'environment variables if not provided.'
  52. )
  53. )
  54. self.cmd_opts.add_option(
  55. '--global',
  56. dest='global_file',
  57. action='store_true',
  58. default=False,
  59. help='Use the system-wide configuration file only'
  60. )
  61. self.cmd_opts.add_option(
  62. '--user',
  63. dest='user_file',
  64. action='store_true',
  65. default=False,
  66. help='Use the user configuration file only'
  67. )
  68. self.cmd_opts.add_option(
  69. '--site',
  70. dest='site_file',
  71. action='store_true',
  72. default=False,
  73. help='Use the current environment configuration file only'
  74. )
  75. self.parser.insert_option_group(0, self.cmd_opts)
  76. def run(self, options, args):
  77. # type: (Values, List[str]) -> int
  78. handlers = {
  79. "list": self.list_values,
  80. "edit": self.open_in_editor,
  81. "get": self.get_name,
  82. "set": self.set_name_value,
  83. "unset": self.unset_name,
  84. "debug": self.list_config_values,
  85. }
  86. # Determine action
  87. if not args or args[0] not in handlers:
  88. logger.error(
  89. "Need an action (%s) to perform.",
  90. ", ".join(sorted(handlers)),
  91. )
  92. return ERROR
  93. action = args[0]
  94. # Determine which configuration files are to be loaded
  95. # Depends on whether the command is modifying.
  96. try:
  97. load_only = self._determine_file(
  98. options, need_value=(action in ["get", "set", "unset", "edit"])
  99. )
  100. except PipError as e:
  101. logger.error(e.args[0])
  102. return ERROR
  103. # Load a new configuration
  104. self.configuration = Configuration(
  105. isolated=options.isolated_mode, load_only=load_only
  106. )
  107. self.configuration.load()
  108. # Error handling happens here, not in the action-handlers.
  109. try:
  110. handlers[action](options, args[1:])
  111. except PipError as e:
  112. logger.error(e.args[0])
  113. return ERROR
  114. return SUCCESS
  115. def _determine_file(self, options, need_value):
  116. # type: (Values, bool) -> Optional[Kind]
  117. file_options = [key for key, value in (
  118. (kinds.USER, options.user_file),
  119. (kinds.GLOBAL, options.global_file),
  120. (kinds.SITE, options.site_file),
  121. ) if value]
  122. if not file_options:
  123. if not need_value:
  124. return None
  125. # Default to user, unless there's a site file.
  126. elif any(
  127. os.path.exists(site_config_file)
  128. for site_config_file in get_configuration_files()[kinds.SITE]
  129. ):
  130. return kinds.SITE
  131. else:
  132. return kinds.USER
  133. elif len(file_options) == 1:
  134. return file_options[0]
  135. raise PipError(
  136. "Need exactly one file to operate upon "
  137. "(--user, --site, --global) to perform."
  138. )
  139. def list_values(self, options, args):
  140. # type: (Values, 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, args):
  145. # type: (Values, List[str]) -> None
  146. key = self._get_n_args(args, "get [name]", n=1)
  147. value = self.configuration.get_value(key)
  148. write_output("%s", value)
  149. def set_name_value(self, options, args):
  150. # type: (Values, List[str]) -> None
  151. key, value = self._get_n_args(args, "set [name] [value]", n=2)
  152. self.configuration.set_value(key, value)
  153. self._save_configuration()
  154. def unset_name(self, options, args):
  155. # type: (Values, List[str]) -> None
  156. key = self._get_n_args(args, "unset [name]", n=1)
  157. self.configuration.unset_value(key)
  158. self._save_configuration()
  159. def list_config_values(self, options, args):
  160. # type: (Values, List[str]) -> None
  161. """List config key-value pairs across different config files"""
  162. self._get_n_args(args, "debug", n=0)
  163. self.print_env_var_values()
  164. # Iterate over config files and print if they exist, and the
  165. # key-value pairs present in them if they do
  166. for variant, files in sorted(self.configuration.iter_config_files()):
  167. write_output("%s:", variant)
  168. for fname in files:
  169. with indent_log():
  170. file_exists = os.path.exists(fname)
  171. write_output("%s, exists: %r",
  172. fname, file_exists)
  173. if file_exists:
  174. self.print_config_file_values(variant)
  175. def print_config_file_values(self, variant):
  176. # type: (Kind) -> None
  177. """Get key-value pairs from the file of a variant"""
  178. for name, value in self.configuration.\
  179. get_values_in_config(variant).items():
  180. with indent_log():
  181. write_output("%s: %s", name, value)
  182. def print_env_var_values(self):
  183. # type: () -> None
  184. """Get key-values pairs present as environment variables"""
  185. write_output("%s:", 'env_var')
  186. with indent_log():
  187. for key, value in sorted(self.configuration.get_environ_vars()):
  188. env_var = f'PIP_{key.upper()}'
  189. write_output("%s=%r", env_var, value)
  190. def open_in_editor(self, options, args):
  191. # type: (Values, List[str]) -> None
  192. editor = self._determine_editor(options)
  193. fname = self.configuration.get_file_to_edit()
  194. if fname is None:
  195. raise PipError("Could not determine appropriate file.")
  196. try:
  197. subprocess.check_call([editor, fname])
  198. except subprocess.CalledProcessError as e:
  199. raise PipError(
  200. "Editor Subprocess exited with exit code {}"
  201. .format(e.returncode)
  202. )
  203. def _get_n_args(self, args, example, n):
  204. # type: (List[str], str, int) -> Any
  205. """Helper to make sure the command got the right number of arguments
  206. """
  207. if len(args) != n:
  208. msg = (
  209. 'Got unexpected number of arguments, expected {}. '
  210. '(example: "{} config {}")'
  211. ).format(n, get_prog(), example)
  212. raise PipError(msg)
  213. if n == 1:
  214. return args[0]
  215. else:
  216. return args
  217. def _save_configuration(self):
  218. # type: () -> None
  219. # We successfully ran a modifying command. Need to save the
  220. # configuration.
  221. try:
  222. self.configuration.save()
  223. except Exception:
  224. logger.exception(
  225. "Unable to save configuration. Please report this as a bug."
  226. )
  227. raise PipError("Internal Error.")
  228. def _determine_editor(self, options):
  229. # type: (Values) -> str
  230. if options.editor is not None:
  231. return options.editor
  232. elif "VISUAL" in os.environ:
  233. return os.environ["VISUAL"]
  234. elif "EDITOR" in os.environ:
  235. return os.environ["EDITOR"]
  236. else:
  237. raise PipError("Could not determine editor to use.")