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