configuration.py 13 KB

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