configuration.py 13 KB

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