configuration.py 9.6 KB

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