Path: blob/main/test/lib/python3.9/site-packages/pip/_internal/configuration.py
4799 views
"""Configuration management setup12Some terminology:3- name4As written in config files.5- value6Value associated with a name7- key8Name combined with it's section (section.name)9- variant10A single word describing where the configuration key-value pair came from11"""1213import configparser14import locale15import os16import sys17from typing import Any, Dict, Iterable, List, NewType, Optional, Tuple1819from pip._internal.exceptions import (20ConfigurationError,21ConfigurationFileCouldNotBeLoaded,22)23from pip._internal.utils import appdirs24from pip._internal.utils.compat import WINDOWS25from pip._internal.utils.logging import getLogger26from pip._internal.utils.misc import ensure_dir, enum2728RawConfigParser = configparser.RawConfigParser # Shorthand29Kind = NewType("Kind", str)3031CONFIG_BASENAME = "pip.ini" if WINDOWS else "pip.conf"32ENV_NAMES_IGNORED = "version", "help"3334# The kinds of configurations there are.35kinds = enum(36USER="user", # User Specific37GLOBAL="global", # System Wide38SITE="site", # [Virtual] Environment Specific39ENV="env", # from PIP_CONFIG_FILE40ENV_VAR="env-var", # from Environment Variables41)42OVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR43VALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE4445logger = getLogger(__name__)464748# NOTE: Maybe use the optionx attribute to normalize keynames.49def _normalize_name(name: str) -> str:50"""Make a name consistent regardless of source (environment or file)"""51name = name.lower().replace("_", "-")52if name.startswith("--"):53name = name[2:] # only prefer long opts54return name555657def _disassemble_key(name: str) -> List[str]:58if "." not in name:59error_message = (60"Key does not contain dot separated section and key. "61"Perhaps you wanted to use 'global.{}' instead?"62).format(name)63raise ConfigurationError(error_message)64return name.split(".", 1)656667def get_configuration_files() -> Dict[Kind, List[str]]:68global_config_files = [69os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs("pip")70]7172site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME)73legacy_config_file = os.path.join(74os.path.expanduser("~"),75"pip" if WINDOWS else ".pip",76CONFIG_BASENAME,77)78new_config_file = os.path.join(appdirs.user_config_dir("pip"), CONFIG_BASENAME)79return {80kinds.GLOBAL: global_config_files,81kinds.SITE: [site_config_file],82kinds.USER: [legacy_config_file, new_config_file],83}848586class Configuration:87"""Handles management of configuration.8889Provides an interface to accessing and managing configuration files.9091This class converts provides an API that takes "section.key-name" style92keys and stores the value associated with it as "key-name" under the93section "section".9495This allows for a clean interface wherein the both the section and the96key-name are preserved in an easy to manage form in the configuration files97and the data stored is also nice.98"""99100def __init__(self, isolated: bool, load_only: Optional[Kind] = None) -> None:101super().__init__()102103if load_only is not None and load_only not in VALID_LOAD_ONLY:104raise ConfigurationError(105"Got invalid value for load_only - should be one of {}".format(106", ".join(map(repr, VALID_LOAD_ONLY))107)108)109self.isolated = isolated110self.load_only = load_only111112# Because we keep track of where we got the data from113self._parsers: Dict[Kind, List[Tuple[str, RawConfigParser]]] = {114variant: [] for variant in OVERRIDE_ORDER115}116self._config: Dict[Kind, Dict[str, Any]] = {117variant: {} for variant in OVERRIDE_ORDER118}119self._modified_parsers: List[Tuple[str, RawConfigParser]] = []120121def load(self) -> None:122"""Loads configuration from configuration files and environment"""123self._load_config_files()124if not self.isolated:125self._load_environment_vars()126127def get_file_to_edit(self) -> Optional[str]:128"""Returns the file with highest priority in configuration"""129assert self.load_only is not None, "Need to be specified a file to be editing"130131try:132return self._get_parser_to_modify()[0]133except IndexError:134return None135136def items(self) -> Iterable[Tuple[str, Any]]:137"""Returns key-value pairs like dict.items() representing the loaded138configuration139"""140return self._dictionary.items()141142def get_value(self, key: str) -> Any:143"""Get a value from the configuration."""144orig_key = key145key = _normalize_name(key)146try:147return self._dictionary[key]148except KeyError:149# disassembling triggers a more useful error message than simply150# "No such key" in the case that the key isn't in the form command.option151_disassemble_key(key)152raise ConfigurationError(f"No such key - {orig_key}")153154def set_value(self, key: str, value: Any) -> None:155"""Modify a value in the configuration."""156key = _normalize_name(key)157self._ensure_have_load_only()158159assert self.load_only160fname, parser = self._get_parser_to_modify()161162if parser is not None:163section, name = _disassemble_key(key)164165# Modify the parser and the configuration166if not parser.has_section(section):167parser.add_section(section)168parser.set(section, name, value)169170self._config[self.load_only][key] = value171self._mark_as_modified(fname, parser)172173def unset_value(self, key: str) -> None:174"""Unset a value in the configuration."""175orig_key = key176key = _normalize_name(key)177self._ensure_have_load_only()178179assert self.load_only180if key not in self._config[self.load_only]:181raise ConfigurationError(f"No such key - {orig_key}")182183fname, parser = self._get_parser_to_modify()184185if parser is not None:186section, name = _disassemble_key(key)187if not (188parser.has_section(section) and parser.remove_option(section, name)189):190# The option was not removed.191raise ConfigurationError(192"Fatal Internal error [id=1]. Please report as a bug."193)194195# The section may be empty after the option was removed.196if not parser.items(section):197parser.remove_section(section)198self._mark_as_modified(fname, parser)199200del self._config[self.load_only][key]201202def save(self) -> None:203"""Save the current in-memory state."""204self._ensure_have_load_only()205206for fname, parser in self._modified_parsers:207logger.info("Writing to %s", fname)208209# Ensure directory exists.210ensure_dir(os.path.dirname(fname))211212with open(fname, "w") as f:213parser.write(f)214215#216# Private routines217#218219def _ensure_have_load_only(self) -> None:220if self.load_only is None:221raise ConfigurationError("Needed a specific file to be modifying.")222logger.debug("Will be working with %s variant only", self.load_only)223224@property225def _dictionary(self) -> Dict[str, Any]:226"""A dictionary representing the loaded configuration."""227# NOTE: Dictionaries are not populated if not loaded. So, conditionals228# are not needed here.229retval = {}230231for variant in OVERRIDE_ORDER:232retval.update(self._config[variant])233234return retval235236def _load_config_files(self) -> None:237"""Loads configuration from configuration files"""238config_files = dict(self.iter_config_files())239if config_files[kinds.ENV][0:1] == [os.devnull]:240logger.debug(241"Skipping loading configuration files due to "242"environment's PIP_CONFIG_FILE being os.devnull"243)244return245246for variant, files in config_files.items():247for fname in files:248# If there's specific variant set in `load_only`, load only249# that variant, not the others.250if self.load_only is not None and variant != self.load_only:251logger.debug("Skipping file '%s' (variant: %s)", fname, variant)252continue253254parser = self._load_file(variant, fname)255256# Keeping track of the parsers used257self._parsers[variant].append((fname, parser))258259def _load_file(self, variant: Kind, fname: str) -> RawConfigParser:260logger.verbose("For variant '%s', will try loading '%s'", variant, fname)261parser = self._construct_parser(fname)262263for section in parser.sections():264items = parser.items(section)265self._config[variant].update(self._normalized_keys(section, items))266267return parser268269def _construct_parser(self, fname: str) -> RawConfigParser:270parser = configparser.RawConfigParser()271# If there is no such file, don't bother reading it but create the272# parser anyway, to hold the data.273# Doing this is useful when modifying and saving files, where we don't274# need to construct a parser.275if os.path.exists(fname):276locale_encoding = locale.getpreferredencoding(False)277try:278parser.read(fname, encoding=locale_encoding)279except UnicodeDecodeError:280# See https://github.com/pypa/pip/issues/4963281raise ConfigurationFileCouldNotBeLoaded(282reason=f"contains invalid {locale_encoding} characters",283fname=fname,284)285except configparser.Error as error:286# See https://github.com/pypa/pip/issues/4893287raise ConfigurationFileCouldNotBeLoaded(error=error)288return parser289290def _load_environment_vars(self) -> None:291"""Loads configuration from environment variables"""292self._config[kinds.ENV_VAR].update(293self._normalized_keys(":env:", self.get_environ_vars())294)295296def _normalized_keys(297self, section: str, items: Iterable[Tuple[str, Any]]298) -> Dict[str, Any]:299"""Normalizes items to construct a dictionary with normalized keys.300301This routine is where the names become keys and are made the same302regardless of source - configuration files or environment.303"""304normalized = {}305for name, val in items:306key = section + "." + _normalize_name(name)307normalized[key] = val308return normalized309310def get_environ_vars(self) -> Iterable[Tuple[str, str]]:311"""Returns a generator with all environmental vars with prefix PIP_"""312for key, val in os.environ.items():313if key.startswith("PIP_"):314name = key[4:].lower()315if name not in ENV_NAMES_IGNORED:316yield name, val317318# XXX: This is patched in the tests.319def iter_config_files(self) -> Iterable[Tuple[Kind, List[str]]]:320"""Yields variant and configuration files associated with it.321322This should be treated like items of a dictionary.323"""324# SMELL: Move the conditions out of this function325326# environment variables have the lowest priority327config_file = os.environ.get("PIP_CONFIG_FILE", None)328if config_file is not None:329yield kinds.ENV, [config_file]330else:331yield kinds.ENV, []332333config_files = get_configuration_files()334335# at the base we have any global configuration336yield kinds.GLOBAL, config_files[kinds.GLOBAL]337338# per-user configuration next339should_load_user_config = not self.isolated and not (340config_file and os.path.exists(config_file)341)342if should_load_user_config:343# The legacy config file is overridden by the new config file344yield kinds.USER, config_files[kinds.USER]345346# finally virtualenv configuration first trumping others347yield kinds.SITE, config_files[kinds.SITE]348349def get_values_in_config(self, variant: Kind) -> Dict[str, Any]:350"""Get values present in a config file"""351return self._config[variant]352353def _get_parser_to_modify(self) -> Tuple[str, RawConfigParser]:354# Determine which parser to modify355assert self.load_only356parsers = self._parsers[self.load_only]357if not parsers:358# This should not happen if everything works correctly.359raise ConfigurationError(360"Fatal Internal error [id=2]. Please report as a bug."361)362363# Use the highest priority parser.364return parsers[-1]365366# XXX: This is patched in the tests.367def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None:368file_parser_tuple = (fname, parser)369if file_parser_tuple not in self._modified_parsers:370self._modified_parsers.append(file_parser_tuple)371372def __repr__(self) -> str:373return f"{self.__class__.__name__}({self._dictionary!r})"374375376