You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

385 lines
13 KiB

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