configuration.py 9.1 KB

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