configuration.py 14 KB

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