Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

configuration.py 14KB

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