Path: blob/master/venv/Lib/site-packages/pip/_internal/configuration.py
811 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"""1213# The following comment should be removed at some point in the future.14# mypy: strict-optional=False1516import locale17import logging18import os19import sys2021from pip._vendor.six.moves import configparser2223from pip._internal.exceptions import (24ConfigurationError,25ConfigurationFileCouldNotBeLoaded,26)27from pip._internal.utils import appdirs28from pip._internal.utils.compat import WINDOWS, expanduser29from pip._internal.utils.misc import ensure_dir, enum30from pip._internal.utils.typing import MYPY_CHECK_RUNNING3132if MYPY_CHECK_RUNNING:33from typing import (34Any, Dict, Iterable, List, NewType, Optional, Tuple35)3637RawConfigParser = configparser.RawConfigParser # Shorthand38Kind = NewType("Kind", str)3940logger = logging.getLogger(__name__)414243# NOTE: Maybe use the optionx attribute to normalize keynames.44def _normalize_name(name):45# type: (str) -> str46"""Make a name consistent regardless of source (environment or file)47"""48name = name.lower().replace('_', '-')49if name.startswith('--'):50name = name[2:] # only prefer long opts51return name525354def _disassemble_key(name):55# type: (str) -> List[str]56if "." not in name:57error_message = (58"Key does not contain dot separated section and key. "59"Perhaps you wanted to use 'global.{}' instead?"60).format(name)61raise ConfigurationError(error_message)62return name.split(".", 1)636465# The kinds of configurations there are.66kinds = enum(67USER="user", # User Specific68GLOBAL="global", # System Wide69SITE="site", # [Virtual] Environment Specific70ENV="env", # from PIP_CONFIG_FILE71ENV_VAR="env-var", # from Environment Variables72)737475CONFIG_BASENAME = 'pip.ini' if WINDOWS else 'pip.conf'767778def get_configuration_files():79# type: () -> Dict[Kind, List[str]]80global_config_files = [81os.path.join(path, CONFIG_BASENAME)82for path in appdirs.site_config_dirs('pip')83]8485site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME)86legacy_config_file = os.path.join(87expanduser('~'),88'pip' if WINDOWS else '.pip',89CONFIG_BASENAME,90)91new_config_file = os.path.join(92appdirs.user_config_dir("pip"), CONFIG_BASENAME93)94return {95kinds.GLOBAL: global_config_files,96kinds.SITE: [site_config_file],97kinds.USER: [legacy_config_file, new_config_file],98}99100101class Configuration(object):102"""Handles management of configuration.103104Provides an interface to accessing and managing configuration files.105106This class converts provides an API that takes "section.key-name" style107keys and stores the value associated with it as "key-name" under the108section "section".109110This allows for a clean interface wherein the both the section and the111key-name are preserved in an easy to manage form in the configuration files112and the data stored is also nice.113"""114115def __init__(self, isolated, load_only=None):116# type: (bool, Kind) -> None117super(Configuration, self).__init__()118119_valid_load_only = [kinds.USER, kinds.GLOBAL, kinds.SITE, None]120if load_only not in _valid_load_only:121raise ConfigurationError(122"Got invalid value for load_only - should be one of {}".format(123", ".join(map(repr, _valid_load_only[:-1]))124)125)126self.isolated = isolated # type: bool127self.load_only = load_only # type: Optional[Kind]128129# The order here determines the override order.130self._override_order = [131kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR132]133134self._ignore_env_names = ["version", "help"]135136# Because we keep track of where we got the data from137self._parsers = {138variant: [] for variant in self._override_order139} # type: Dict[Kind, List[Tuple[str, RawConfigParser]]]140self._config = {141variant: {} for variant in self._override_order142} # type: Dict[Kind, Dict[str, Any]]143self._modified_parsers = [] # type: List[Tuple[str, RawConfigParser]]144145def load(self):146# type: () -> None147"""Loads configuration from configuration files and environment148"""149self._load_config_files()150if not self.isolated:151self._load_environment_vars()152153def get_file_to_edit(self):154# type: () -> Optional[str]155"""Returns the file with highest priority in configuration156"""157assert self.load_only is not None, \158"Need to be specified a file to be editing"159160try:161return self._get_parser_to_modify()[0]162except IndexError:163return None164165def items(self):166# type: () -> Iterable[Tuple[str, Any]]167"""Returns key-value pairs like dict.items() representing the loaded168configuration169"""170return self._dictionary.items()171172def get_value(self, key):173# type: (str) -> Any174"""Get a value from the configuration.175"""176try:177return self._dictionary[key]178except KeyError:179raise ConfigurationError("No such key - {}".format(key))180181def set_value(self, key, value):182# type: (str, Any) -> None183"""Modify a value in the configuration.184"""185self._ensure_have_load_only()186187fname, parser = self._get_parser_to_modify()188189if parser is not None:190section, name = _disassemble_key(key)191192# Modify the parser and the configuration193if not parser.has_section(section):194parser.add_section(section)195parser.set(section, name, value)196197self._config[self.load_only][key] = value198self._mark_as_modified(fname, parser)199200def unset_value(self, key):201# type: (str) -> None202"""Unset a value in the configuration.203"""204self._ensure_have_load_only()205206if key not in self._config[self.load_only]:207raise ConfigurationError("No such key - {}".format(key))208209fname, parser = self._get_parser_to_modify()210211if parser is not None:212section, name = _disassemble_key(key)213214# Remove the key in the parser215modified_something = False216if parser.has_section(section):217# Returns whether the option was removed or not218modified_something = parser.remove_option(section, name)219220if modified_something:221# name removed from parser, section may now be empty222section_iter = iter(parser.items(section))223try:224val = next(section_iter)225except StopIteration:226val = None227228if val is None:229parser.remove_section(section)230231self._mark_as_modified(fname, parser)232else:233raise ConfigurationError(234"Fatal Internal error [id=1]. Please report as a bug."235)236237del self._config[self.load_only][key]238239def save(self):240# type: () -> None241"""Save the current in-memory state.242"""243self._ensure_have_load_only()244245for fname, parser in self._modified_parsers:246logger.info("Writing to %s", fname)247248# Ensure directory exists.249ensure_dir(os.path.dirname(fname))250251with open(fname, "w") as f:252parser.write(f)253254#255# Private routines256#257258def _ensure_have_load_only(self):259# type: () -> None260if self.load_only is None:261raise ConfigurationError("Needed a specific file to be modifying.")262logger.debug("Will be working with %s variant only", self.load_only)263264@property265def _dictionary(self):266# type: () -> Dict[str, Any]267"""A dictionary representing the loaded configuration.268"""269# NOTE: Dictionaries are not populated if not loaded. So, conditionals270# are not needed here.271retval = {}272273for variant in self._override_order:274retval.update(self._config[variant])275276return retval277278def _load_config_files(self):279# type: () -> None280"""Loads configuration from configuration files281"""282config_files = dict(self._iter_config_files())283if config_files[kinds.ENV][0:1] == [os.devnull]:284logger.debug(285"Skipping loading configuration files due to "286"environment's PIP_CONFIG_FILE being os.devnull"287)288return289290for variant, files in config_files.items():291for fname in files:292# If there's specific variant set in `load_only`, load only293# that variant, not the others.294if self.load_only is not None and variant != self.load_only:295logger.debug(296"Skipping file '%s' (variant: %s)", fname, variant297)298continue299300parser = self._load_file(variant, fname)301302# Keeping track of the parsers used303self._parsers[variant].append((fname, parser))304305def _load_file(self, variant, fname):306# type: (Kind, str) -> RawConfigParser307logger.debug("For variant '%s', will try loading '%s'", variant, fname)308parser = self._construct_parser(fname)309310for section in parser.sections():311items = parser.items(section)312self._config[variant].update(self._normalized_keys(section, items))313314return parser315316def _construct_parser(self, fname):317# type: (str) -> RawConfigParser318parser = configparser.RawConfigParser()319# If there is no such file, don't bother reading it but create the320# parser anyway, to hold the data.321# Doing this is useful when modifying and saving files, where we don't322# need to construct a parser.323if os.path.exists(fname):324try:325parser.read(fname)326except UnicodeDecodeError:327# See https://github.com/pypa/pip/issues/4963328raise ConfigurationFileCouldNotBeLoaded(329reason="contains invalid {} characters".format(330locale.getpreferredencoding(False)331),332fname=fname,333)334except configparser.Error as error:335# See https://github.com/pypa/pip/issues/4893336raise ConfigurationFileCouldNotBeLoaded(error=error)337return parser338339def _load_environment_vars(self):340# type: () -> None341"""Loads configuration from environment variables342"""343self._config[kinds.ENV_VAR].update(344self._normalized_keys(":env:", self._get_environ_vars())345)346347def _normalized_keys(self, section, items):348# type: (str, Iterable[Tuple[str, Any]]) -> Dict[str, Any]349"""Normalizes items to construct a dictionary with normalized keys.350351This routine is where the names become keys and are made the same352regardless of source - configuration files or environment.353"""354normalized = {}355for name, val in items:356key = section + "." + _normalize_name(name)357normalized[key] = val358return normalized359360def _get_environ_vars(self):361# type: () -> Iterable[Tuple[str, str]]362"""Returns a generator with all environmental vars with prefix PIP_"""363for key, val in os.environ.items():364should_be_yielded = (365key.startswith("PIP_") and366key[4:].lower() not in self._ignore_env_names367)368if should_be_yielded:369yield key[4:].lower(), val370371# XXX: This is patched in the tests.372def _iter_config_files(self):373# type: () -> Iterable[Tuple[Kind, List[str]]]374"""Yields variant and configuration files associated with it.375376This should be treated like items of a dictionary.377"""378# SMELL: Move the conditions out of this function379380# environment variables have the lowest priority381config_file = os.environ.get('PIP_CONFIG_FILE', None)382if config_file is not None:383yield kinds.ENV, [config_file]384else:385yield kinds.ENV, []386387config_files = get_configuration_files()388389# at the base we have any global configuration390yield kinds.GLOBAL, config_files[kinds.GLOBAL]391392# per-user configuration next393should_load_user_config = not self.isolated and not (394config_file and os.path.exists(config_file)395)396if should_load_user_config:397# The legacy config file is overridden by the new config file398yield kinds.USER, config_files[kinds.USER]399400# finally virtualenv configuration first trumping others401yield kinds.SITE, config_files[kinds.SITE]402403def _get_parser_to_modify(self):404# type: () -> Tuple[str, RawConfigParser]405# Determine which parser to modify406parsers = self._parsers[self.load_only]407if not parsers:408# This should not happen if everything works correctly.409raise ConfigurationError(410"Fatal Internal error [id=2]. Please report as a bug."411)412413# Use the highest priority parser.414return parsers[-1]415416# XXX: This is patched in the tests.417def _mark_as_modified(self, fname, parser):418# type: (str, RawConfigParser) -> None419file_parser_tuple = (fname, parser)420if file_parser_tuple not in self._modified_parsers:421self._modified_parsers.append(file_parser_tuple)422423def __repr__(self):424# type: () -> str425return "{}({!r})".format(self.__class__.__name__, self._dictionary)426427428