configuration.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. """Configuration management setup
  2. Some terminology:
  3. - name
  4. As written in config files.
  5. - value
  6. Value associated with a name
  7. - key
  8. Name combined with it's section (section.name)
  9. - variant
  10. A single word describing where the configuration key-value pair came from
  11. """
  12. from __future__ import annotations
  13. import configparser
  14. import locale
  15. import os
  16. import sys
  17. from collections.abc import Iterable
  18. from typing import Any, NewType
  19. from pip._internal.exceptions import (
  20. ConfigurationError,
  21. ConfigurationFileCouldNotBeLoaded,
  22. )
  23. from pip._internal.utils import appdirs
  24. from pip._internal.utils.compat import WINDOWS
  25. from pip._internal.utils.logging import getLogger
  26. from pip._internal.utils.misc import ensure_dir, enum
  27. RawConfigParser = configparser.RawConfigParser # Shorthand
  28. Kind = NewType("Kind", str)
  29. CONFIG_BASENAME = "pip.ini" if WINDOWS else "pip.conf"
  30. ENV_NAMES_IGNORED = "version", "help"
  31. # The kinds of configurations there are.
  32. kinds = enum(
  33. USER="user", # User Specific
  34. GLOBAL="global", # System Wide
  35. SITE="site", # [Virtual] Environment Specific
  36. ENV="env", # from PIP_CONFIG_FILE
  37. ENV_VAR="env-var", # from Environment Variables
  38. )
  39. OVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR
  40. VALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE
  41. logger = getLogger(__name__)
  42. # NOTE: Maybe use the optionx attribute to normalize keynames.
  43. def _normalize_name(name: str) -> str:
  44. """Make a name consistent regardless of source (environment or file)"""
  45. name = name.lower().replace("_", "-")
  46. name = name.removeprefix("--") # only prefer long opts
  47. return name
  48. def _disassemble_key(name: str) -> list[str]:
  49. if "." not in name:
  50. error_message = (
  51. "Key does not contain dot separated section and key. "
  52. f"Perhaps you wanted to use 'global.{name}' instead?"
  53. )
  54. raise ConfigurationError(error_message)
  55. return name.split(".", 1)
  56. def get_configuration_files() -> dict[Kind, list[str]]:
  57. global_config_files = [
  58. os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs("pip")
  59. ]
  60. site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME)
  61. legacy_config_file = os.path.join(
  62. os.path.expanduser("~"),
  63. "pip" if WINDOWS else ".pip",
  64. CONFIG_BASENAME,
  65. )
  66. new_config_file = os.path.join(appdirs.user_config_dir("pip"), CONFIG_BASENAME)
  67. return {
  68. kinds.GLOBAL: global_config_files,
  69. kinds.SITE: [site_config_file],
  70. kinds.USER: [legacy_config_file, new_config_file],
  71. }
  72. class Configuration:
  73. """Handles management of configuration.
  74. Provides an interface to accessing and managing configuration files.
  75. This class converts provides an API that takes "section.key-name" style
  76. keys and stores the value associated with it as "key-name" under the
  77. section "section".
  78. This allows for a clean interface wherein the both the section and the
  79. key-name are preserved in an easy to manage form in the configuration files
  80. and the data stored is also nice.
  81. """
  82. def __init__(self, isolated: bool, load_only: Kind | None = None) -> None:
  83. super().__init__()
  84. if load_only is not None and load_only not in VALID_LOAD_ONLY:
  85. raise ConfigurationError(
  86. "Got invalid value for load_only - should be one of {}".format(
  87. ", ".join(map(repr, VALID_LOAD_ONLY))
  88. )
  89. )
  90. self.isolated = isolated
  91. self.load_only = load_only
  92. # Because we keep track of where we got the data from
  93. self._parsers: dict[Kind, list[tuple[str, RawConfigParser]]] = {
  94. variant: [] for variant in OVERRIDE_ORDER
  95. }
  96. self._config: dict[Kind, dict[str, dict[str, Any]]] = {
  97. variant: {} for variant in OVERRIDE_ORDER
  98. }
  99. self._modified_parsers: list[tuple[str, RawConfigParser]] = []
  100. def load(self) -> None:
  101. """Loads configuration from configuration files and environment"""
  102. self._load_config_files()
  103. if not self.isolated:
  104. self._load_environment_vars()
  105. def get_file_to_edit(self) -> str | None:
  106. """Returns the file with highest priority in configuration"""
  107. assert self.load_only is not None, "Need to be specified a file to be editing"
  108. try:
  109. return self._get_parser_to_modify()[0]
  110. except IndexError:
  111. return None
  112. def items(self) -> Iterable[tuple[str, Any]]:
  113. """Returns key-value pairs like dict.items() representing the loaded
  114. configuration
  115. """
  116. return self._dictionary.items()
  117. def get_value(self, key: str) -> Any:
  118. """Get a value from the configuration."""
  119. orig_key = key
  120. key = _normalize_name(key)
  121. try:
  122. clean_config: dict[str, Any] = {}
  123. for file_values in self._dictionary.values():
  124. clean_config.update(file_values)
  125. return clean_config[key]
  126. except KeyError:
  127. # disassembling triggers a more useful error message than simply
  128. # "No such key" in the case that the key isn't in the form command.option
  129. _disassemble_key(key)
  130. raise ConfigurationError(f"No such key - {orig_key}")
  131. def set_value(self, key: str, value: Any) -> None:
  132. """Modify a value in the configuration."""
  133. key = _normalize_name(key)
  134. self._ensure_have_load_only()
  135. assert self.load_only
  136. fname, parser = self._get_parser_to_modify()
  137. if parser is not None:
  138. section, name = _disassemble_key(key)
  139. # Modify the parser and the configuration
  140. if not parser.has_section(section):
  141. parser.add_section(section)
  142. parser.set(section, name, value)
  143. self._config[self.load_only].setdefault(fname, {})
  144. self._config[self.load_only][fname][key] = value
  145. self._mark_as_modified(fname, parser)
  146. def unset_value(self, key: str) -> None:
  147. """Unset a value in the configuration."""
  148. orig_key = key
  149. key = _normalize_name(key)
  150. self._ensure_have_load_only()
  151. assert self.load_only
  152. fname, parser = self._get_parser_to_modify()
  153. if (
  154. key not in self._config[self.load_only][fname]
  155. and key not in self._config[self.load_only]
  156. ):
  157. raise ConfigurationError(f"No such key - {orig_key}")
  158. if parser is not None:
  159. section, name = _disassemble_key(key)
  160. if not (
  161. parser.has_section(section) and parser.remove_option(section, name)
  162. ):
  163. # The option was not removed.
  164. raise ConfigurationError(
  165. "Fatal Internal error [id=1]. Please report as a bug."
  166. )
  167. # The section may be empty after the option was removed.
  168. if not parser.items(section):
  169. parser.remove_section(section)
  170. self._mark_as_modified(fname, parser)
  171. try:
  172. del self._config[self.load_only][fname][key]
  173. except KeyError:
  174. del self._config[self.load_only][key]
  175. def save(self) -> None:
  176. """Save the current in-memory state."""
  177. self._ensure_have_load_only()
  178. for fname, parser in self._modified_parsers:
  179. logger.info("Writing to %s", fname)
  180. # Ensure directory exists.
  181. ensure_dir(os.path.dirname(fname))
  182. # Ensure directory's permission(need to be writeable)
  183. try:
  184. with open(fname, "w") as f:
  185. parser.write(f)
  186. except OSError as error:
  187. raise ConfigurationError(
  188. f"An error occurred while writing to the configuration file "
  189. f"{fname}: {error}"
  190. )
  191. #
  192. # Private routines
  193. #
  194. def _ensure_have_load_only(self) -> None:
  195. if self.load_only is None:
  196. raise ConfigurationError("Needed a specific file to be modifying.")
  197. logger.debug("Will be working with %s variant only", self.load_only)
  198. @property
  199. def _dictionary(self) -> dict[str, dict[str, Any]]:
  200. """A dictionary representing the loaded configuration."""
  201. # NOTE: Dictionaries are not populated if not loaded. So, conditionals
  202. # are not needed here.
  203. retval = {}
  204. for variant in OVERRIDE_ORDER:
  205. retval.update(self._config[variant])
  206. return retval
  207. def _load_config_files(self) -> None:
  208. """Loads configuration from configuration files"""
  209. config_files = dict(self.iter_config_files())
  210. if config_files[kinds.ENV][0:1] == [os.devnull]:
  211. logger.debug(
  212. "Skipping loading configuration files due to "
  213. "environment's PIP_CONFIG_FILE being os.devnull"
  214. )
  215. return
  216. for variant, files in config_files.items():
  217. for fname in files:
  218. # If there's specific variant set in `load_only`, load only
  219. # that variant, not the others.
  220. if self.load_only is not None and variant != self.load_only:
  221. logger.debug("Skipping file '%s' (variant: %s)", fname, variant)
  222. continue
  223. parser = self._load_file(variant, fname)
  224. # Keeping track of the parsers used
  225. self._parsers[variant].append((fname, parser))
  226. def _load_file(self, variant: Kind, fname: str) -> RawConfigParser:
  227. logger.verbose("For variant '%s', will try loading '%s'", variant, fname)
  228. parser = self._construct_parser(fname)
  229. for section in parser.sections():
  230. items = parser.items(section)
  231. self._config[variant].setdefault(fname, {})
  232. self._config[variant][fname].update(self._normalized_keys(section, items))
  233. return parser
  234. def _construct_parser(self, fname: str) -> RawConfigParser:
  235. parser = configparser.RawConfigParser()
  236. # If there is no such file, don't bother reading it but create the
  237. # parser anyway, to hold the data.
  238. # Doing this is useful when modifying and saving files, where we don't
  239. # need to construct a parser.
  240. if os.path.exists(fname):
  241. locale_encoding = locale.getpreferredencoding(False)
  242. try:
  243. parser.read(fname, encoding=locale_encoding)
  244. except UnicodeDecodeError:
  245. # See https://github.com/pypa/pip/issues/4963
  246. raise ConfigurationFileCouldNotBeLoaded(
  247. reason=f"contains invalid {locale_encoding} characters",
  248. fname=fname,
  249. )
  250. except configparser.Error as error:
  251. # See https://github.com/pypa/pip/issues/4893
  252. raise ConfigurationFileCouldNotBeLoaded(error=error)
  253. return parser
  254. def _load_environment_vars(self) -> None:
  255. """Loads configuration from environment variables"""
  256. self._config[kinds.ENV_VAR].setdefault(":env:", {})
  257. self._config[kinds.ENV_VAR][":env:"].update(
  258. self._normalized_keys(":env:", self.get_environ_vars())
  259. )
  260. def _normalized_keys(
  261. self, section: str, items: Iterable[tuple[str, Any]]
  262. ) -> dict[str, Any]:
  263. """Normalizes items to construct a dictionary with normalized keys.
  264. This routine is where the names become keys and are made the same
  265. regardless of source - configuration files or environment.
  266. """
  267. normalized = {}
  268. for name, val in items:
  269. key = section + "." + _normalize_name(name)
  270. normalized[key] = val
  271. return normalized
  272. def get_environ_vars(self) -> Iterable[tuple[str, str]]:
  273. """Returns a generator with all environmental vars with prefix PIP_"""
  274. for key, val in os.environ.items():
  275. if key.startswith("PIP_"):
  276. name = key[4:].lower()
  277. if name not in ENV_NAMES_IGNORED:
  278. yield name, val
  279. # XXX: This is patched in the tests.
  280. def iter_config_files(self) -> Iterable[tuple[Kind, list[str]]]:
  281. """Yields variant and configuration files associated with it.
  282. This should be treated like items of a dictionary. The order
  283. here doesn't affect what gets overridden. That is controlled
  284. by OVERRIDE_ORDER. However this does control the order they are
  285. displayed to the user. It's probably most ergonomic to display
  286. things in the same order as OVERRIDE_ORDER
  287. """
  288. # SMELL: Move the conditions out of this function
  289. env_config_file = os.environ.get("PIP_CONFIG_FILE", None)
  290. config_files = get_configuration_files()
  291. yield kinds.GLOBAL, config_files[kinds.GLOBAL]
  292. # per-user config is not loaded when env_config_file exists
  293. should_load_user_config = not self.isolated and not (
  294. env_config_file and os.path.exists(env_config_file)
  295. )
  296. if should_load_user_config:
  297. # The legacy config file is overridden by the new config file
  298. yield kinds.USER, config_files[kinds.USER]
  299. # virtualenv config
  300. yield kinds.SITE, config_files[kinds.SITE]
  301. if env_config_file is not None:
  302. yield kinds.ENV, [env_config_file]
  303. else:
  304. yield kinds.ENV, []
  305. def get_values_in_config(self, variant: Kind) -> dict[str, Any]:
  306. """Get values present in a config file"""
  307. return self._config[variant]
  308. def _get_parser_to_modify(self) -> tuple[str, RawConfigParser]:
  309. # Determine which parser to modify
  310. assert self.load_only
  311. parsers = self._parsers[self.load_only]
  312. if not parsers:
  313. # This should not happen if everything works correctly.
  314. raise ConfigurationError(
  315. "Fatal Internal error [id=2]. Please report as a bug."
  316. )
  317. # Use the highest priority parser.
  318. return parsers[-1]
  319. # XXX: This is patched in the tests.
  320. def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None:
  321. file_parser_tuple = (fname, parser)
  322. if file_parser_tuple not in self._modified_parsers:
  323. self._modified_parsers.append(file_parser_tuple)
  324. def __repr__(self) -> str:
  325. return f"{self.__class__.__name__}({self._dictionary!r})"