Let us walk on the 3-isogeny graph
Loading...
Searching...
No Matches
Configuration Class Reference

Public Member Functions

None __init__ (self, bool isolated, Optional[Kind] load_only=None)
 
None load (self)
 
Optional[str] get_file_to_edit (self)
 
Iterable[Tuple[str, Any]] items (self)
 
Any get_value (self, str key)
 
None set_value (self, str key, Any value)
 
None unset_value (self, str key)
 
None save (self)
 
Iterable[Tuple[str, str]] get_environ_vars (self)
 
Iterable[Tuple[Kind, List[str]]] iter_config_files (self)
 
Dict[str, Any] get_values_in_config (self, Kind variant)
 
str __repr__ (self)
 

Data Fields

 isolated
 
 load_only
 

Protected Member Functions

None _ensure_have_load_only (self)
 
Dict[str, Any] _dictionary (self)
 
None _load_config_files (self)
 
RawConfigParser _load_file (self, Kind variant, str fname)
 
RawConfigParser _construct_parser (self, str fname)
 
None _load_environment_vars (self)
 
Dict[str, Any] _normalized_keys (self, str section, Iterable[Tuple[str, Any]] items)
 
Tuple[str, RawConfigParser_get_parser_to_modify (self)
 
None _mark_as_modified (self, str fname, RawConfigParser parser)
 

Detailed Description

Handles management of configuration.

Provides an interface to accessing and managing configuration files.

This class converts provides an API that takes "section.key-name" style
keys and stores the value associated with it as "key-name" under the
section "section".

This allows for a clean interface wherein the both the section and the
key-name are preserved in an easy to manage form in the configuration files
and the data stored is also nice.

Definition at line 87 of file configuration.py.

Constructor & Destructor Documentation

◆ __init__()

None __init__ (   self,
bool  isolated,
Optional[Kind]   load_only = None 
)

Definition at line 101 of file configuration.py.

101 def __init__(self, isolated: bool, load_only: Optional[Kind] = None) -> None:
102 super().__init__()
103
104 if load_only is not None and load_only not in VALID_LOAD_ONLY:
105 raise ConfigurationError(
106 "Got invalid value for load_only - should be one of {}".format(
107 ", ".join(map(repr, VALID_LOAD_ONLY))
108 )
109 )
110 self.isolated = isolated
111 self.load_only = load_only
112
113 # Because we keep track of where we got the data from
114 self._parsers: Dict[Kind, List[Tuple[str, RawConfigParser]]] = {
115 variant: [] for variant in OVERRIDE_ORDER
116 }
117 self._config: Dict[Kind, Dict[str, Any]] = {
118 variant: {} for variant in OVERRIDE_ORDER
119 }
120 self._modified_parsers: List[Tuple[str, RawConfigParser]] = []
121
for i

References Configuration.__init__(), and i.

Referenced by Configuration.__init__(), and Protocol.__init_subclass__().

Here is the call graph for this function:
Here is the caller graph for this function:

Member Function Documentation

◆ __repr__()

str __repr__ (   self)

Definition at line 380 of file configuration.py.

380 def __repr__(self) -> str:
381 return f"{self.__class__.__name__}({self._dictionary!r})"

◆ _construct_parser()

RawConfigParser _construct_parser (   self,
str  fname 
)
protected

Definition at line 277 of file configuration.py.

277 def _construct_parser(self, fname: str) -> RawConfigParser:
279 # If there is no such file, don't bother reading it but create the
280 # parser anyway, to hold the data.
281 # Doing this is useful when modifying and saving files, where we don't
282 # need to construct a parser.
283 if os.path.exists(fname):
284 locale_encoding = locale.getpreferredencoding(False)
285 try:
286 parser.read(fname, encoding=locale_encoding)
287 except UnicodeDecodeError:
288 # See https://github.com/pypa/pip/issues/4963
289 raise ConfigurationFileCouldNotBeLoaded(
290 reason=f"contains invalid {locale_encoding} characters",
291 fname=fname,
292 )
293 except configparser.Error as error:
294 # See https://github.com/pypa/pip/issues/4893
295 raise ConfigurationFileCouldNotBeLoaded(error=error)
296 return parser
297

References i.

Referenced by Configuration._load_file().

Here is the caller graph for this function:

◆ _dictionary()

Dict[str, Any] _dictionary (   self)
protected
A dictionary representing the loaded configuration.

Definition at line 233 of file configuration.py.

233 def _dictionary(self) -> Dict[str, Any]:
234 """A dictionary representing the loaded configuration."""
235 # NOTE: Dictionaries are not populated if not loaded. So, conditionals
236 # are not needed here.
237 retval = {}
238
239 for variant in OVERRIDE_ORDER:
240 retval.update(self._config[variant])
241
242 return retval
243

References i.

Referenced by Configuration.get_value(), and Configuration.items().

Here is the caller graph for this function:

◆ _ensure_have_load_only()

None _ensure_have_load_only (   self)
protected

Definition at line 227 of file configuration.py.

227 def _ensure_have_load_only(self) -> None:
228 if self.load_only is None:
229 raise ConfigurationError("Needed a specific file to be modifying.")
230 logger.debug("Will be working with %s variant only", self.load_only)
231

References i, and Configuration.load_only.

Referenced by Configuration.save(), Configuration.set_value(), and Configuration.unset_value().

Here is the caller graph for this function:

◆ _get_parser_to_modify()

Tuple[str, RawConfigParser] _get_parser_to_modify (   self)
protected

Definition at line 361 of file configuration.py.

361 def _get_parser_to_modify(self) -> Tuple[str, RawConfigParser]:
362 # Determine which parser to modify
363 assert self.load_only
364 parsers = self._parsers[self.load_only]
365 if not parsers:
366 # This should not happen if everything works correctly.
367 raise ConfigurationError(
368 "Fatal Internal error [id=2]. Please report as a bug."
369 )
370
371 # Use the highest priority parser.
372 return parsers[-1]
373

References Configuration.load_only.

Referenced by Configuration.get_file_to_edit(), Configuration.set_value(), and Configuration.unset_value().

Here is the caller graph for this function:

◆ _load_config_files()

None _load_config_files (   self)
protected
Loads configuration from configuration files

Definition at line 244 of file configuration.py.

244 def _load_config_files(self) -> None:
245 """Loads configuration from configuration files"""
246 config_files = dict(self.iter_config_files())
247 if config_files[kinds.ENV][0:1] == [os.devnull]:
249 "Skipping loading configuration files due to "
250 "environment's PIP_CONFIG_FILE being os.devnull"
251 )
252 return
253
254 for variant, files in config_files.items():
255 for fname in files:
256 # If there's specific variant set in `load_only`, load only
257 # that variant, not the others.
258 if self.load_only is not None and variant != self.load_only:
259 logger.debug("Skipping file '%s' (variant: %s)", fname, variant)
260 continue
261
262 parser = self._load_file(variant, fname)
263
264 # Keeping track of the parsers used
265 self._parsers[variant].append((fname, parser))
266

References Configuration._load_file(), i, Configuration.iter_config_files(), and Configuration.load_only.

Referenced by Configuration.load().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _load_environment_vars()

None _load_environment_vars (   self)
protected
Loads configuration from environment variables

Definition at line 298 of file configuration.py.

298 def _load_environment_vars(self) -> None:
299 """Loads configuration from environment variables"""
300 self._config[kinds.ENV_VAR].update(
301 self._normalized_keys(":env:", self.get_environ_vars())
302 )
303

References Configuration._normalized_keys(), Configuration.get_environ_vars(), and i.

Referenced by Configuration.load().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _load_file()

RawConfigParser _load_file (   self,
Kind  variant,
str  fname 
)
protected

Definition at line 267 of file configuration.py.

267 def _load_file(self, variant: Kind, fname: str) -> RawConfigParser:
268 logger.verbose("For variant '%s', will try loading '%s'", variant, fname)
269 parser = self._construct_parser(fname)
270
271 for section in parser.sections():
272 items = parser.items(section)
273 self._config[variant].update(self._normalized_keys(section, items))
274
275 return parser
276

References Configuration._construct_parser(), Configuration._normalized_keys(), and i.

Referenced by Configuration._load_config_files().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _mark_as_modified()

None _mark_as_modified (   self,
str  fname,
RawConfigParser  parser 
)
protected

Definition at line 375 of file configuration.py.

375 def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None:
376 file_parser_tuple = (fname, parser)
377 if file_parser_tuple not in self._modified_parsers:
378 self._modified_parsers.append(file_parser_tuple)
379

Referenced by Configuration.set_value(), and Configuration.unset_value().

Here is the caller graph for this function:

◆ _normalized_keys()

Dict[str, Any] _normalized_keys (   self,
str  section,
Iterable[Tuple[str, Any]]   items 
)
protected
Normalizes items to construct a dictionary with normalized keys.

This routine is where the names become keys and are made the same
regardless of source - configuration files or environment.

Definition at line 304 of file configuration.py.

306 ) -> Dict[str, Any]:
307 """Normalizes items to construct a dictionary with normalized keys.
308
309 This routine is where the names become keys and are made the same
310 regardless of source - configuration files or environment.
311 """
312 normalized = {}
313 for name, val in items:
314 key = section + "." + _normalize_name(name)
315 normalized[key] = val
316 return normalized
317

References pip._internal.configuration._normalize_name().

Referenced by Configuration._load_environment_vars(), and Configuration._load_file().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ get_environ_vars()

Iterable[Tuple[str, str]] get_environ_vars (   self)
Returns a generator with all environmental vars with prefix PIP_

Definition at line 318 of file configuration.py.

318 def get_environ_vars(self) -> Iterable[Tuple[str, str]]:
319 """Returns a generator with all environmental vars with prefix PIP_"""
320 for key, val in os.environ.items():
321 if key.startswith("PIP_"):
322 name = key[4:].lower()
323 if name not in ENV_NAMES_IGNORED:
324 yield name, val
325

References i.

Referenced by Configuration._load_environment_vars().

Here is the caller graph for this function:

◆ get_file_to_edit()

Optional[str] get_file_to_edit (   self)
Returns the file with highest priority in configuration

Definition at line 128 of file configuration.py.

128 def get_file_to_edit(self) -> Optional[str]:
129 """Returns the file with highest priority in configuration"""
130 assert self.load_only is not None, "Need to be specified a file to be editing"
131
132 try:
133 return self._get_parser_to_modify()[0]
134 except IndexError:
135 return None
136

References Configuration._get_parser_to_modify(), and Configuration.load_only.

Here is the call graph for this function:

◆ get_value()

Any get_value (   self,
str  key 
)
Get a value from the configuration.

Definition at line 143 of file configuration.py.

143 def get_value(self, key: str) -> Any:
144 """Get a value from the configuration."""
145 orig_key = key
146 key = _normalize_name(key)
147 try:
148 return self._dictionary[key]
149 except KeyError:
150 # disassembling triggers a more useful error message than simply
151 # "No such key" in the case that the key isn't in the form command.option
152 _disassemble_key(key)
153 raise ConfigurationError(f"No such key - {orig_key}")
154

References Configuration._dictionary(), pip._internal.configuration._disassemble_key(), and pip._internal.configuration._normalize_name().

Here is the call graph for this function:

◆ get_values_in_config()

Dict[str, Any] get_values_in_config (   self,
Kind  variant 
)
Get values present in a config file

Definition at line 357 of file configuration.py.

357 def get_values_in_config(self, variant: Kind) -> Dict[str, Any]:
358 """Get values present in a config file"""
359 return self._config[variant]
360

◆ items()

Iterable[Tuple[str, Any]] items (   self)
Returns key-value pairs like dict.items() representing the loaded
configuration

Definition at line 137 of file configuration.py.

137 def items(self) -> Iterable[Tuple[str, Any]]:
138 """Returns key-value pairs like dict.items() representing the loaded
139 configuration
140 """
141 return self._dictionary.items()
142

References Configuration._dictionary(), and Configuration.items().

Referenced by OrderedDict.__eq__(), CaseInsensitiveDict.__repr__(), OrderedDict.__repr__(), ParseResults.as_dict(), ParseResults.dump(), and Configuration.items().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ iter_config_files()

Iterable[Tuple[Kind, List[str]]] iter_config_files (   self)
Yields variant and configuration files associated with it.

This should be treated like items of a dictionary.

Definition at line 327 of file configuration.py.

327 def iter_config_files(self) -> Iterable[Tuple[Kind, List[str]]]:
328 """Yields variant and configuration files associated with it.
329
330 This should be treated like items of a dictionary.
331 """
332 # SMELL: Move the conditions out of this function
333
334 # environment variables have the lowest priority
335 config_file = os.environ.get("PIP_CONFIG_FILE", None)
336 if config_file is not None:
337 yield kinds.ENV, [config_file]
338 else:
339 yield kinds.ENV, []
340
341 config_files = get_configuration_files()
342
343 # at the base we have any global configuration
344 yield kinds.GLOBAL, config_files[kinds.GLOBAL]
345
346 # per-user configuration next
347 should_load_user_config = not self.isolated and not (
348 config_file and os.path.exists(config_file)
349 )
350 if should_load_user_config:
351 # The legacy config file is overridden by the new config file
352 yield kinds.USER, config_files[kinds.USER]
353
354 # finally virtualenv configuration first trumping others
355 yield kinds.SITE, config_files[kinds.SITE]
356

References pip._internal.configuration.get_configuration_files(), i, Configuration.isolated, and InstallRequirement.isolated.

Referenced by Configuration._load_config_files().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ load()

None load (   self)
Loads configuration from configuration files and environment

Definition at line 122 of file configuration.py.

122 def load(self) -> None:
123 """Loads configuration from configuration files and environment"""
124 self._load_config_files()
125 if not self.isolated:
126 self._load_environment_vars()
127

References Configuration._load_config_files(), Configuration._load_environment_vars(), Configuration.isolated, and InstallRequirement.isolated.

Here is the call graph for this function:

◆ save()

None save (   self)
Save the current in-memory state.

Definition at line 203 of file configuration.py.

203 def save(self) -> None:
204 """Save the current in-memory state."""
205 self._ensure_have_load_only()
206
207 for fname, parser in self._modified_parsers:
208 logger.info("Writing to %s", fname)
209
210 # Ensure directory exists.
211 ensure_dir(os.path.dirname(fname))
212
213 # Ensure directory's permission(need to be writeable)
214 try:
215 with open(fname, "w") as f:
216 parser.write(f)
217 except OSError as error:
218 raise ConfigurationError(
219 f"An error occurred while writing to the configuration file "
220 f"{fname}: {error}"
221 )
222

References Configuration._ensure_have_load_only(), and i.

Referenced by pyparsing_test.reset_pyparsing_context.__enter__().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ set_value()

None set_value (   self,
str  key,
Any  value 
)
Modify a value in the configuration.

Definition at line 155 of file configuration.py.

155 def set_value(self, key: str, value: Any) -> None:
156 """Modify a value in the configuration."""
157 key = _normalize_name(key)
158 self._ensure_have_load_only()
159
160 assert self.load_only
161 fname, parser = self._get_parser_to_modify()
162
163 if parser is not None:
164 section, name = _disassemble_key(key)
165
166 # Modify the parser and the configuration
167 if not parser.has_section(section):
168 parser.add_section(section)
169 parser.set(section, name, value)
170
171 self._config[self.load_only][key] = value
172 self._mark_as_modified(fname, parser)
173

References pip._internal.configuration._disassemble_key(), Configuration._ensure_have_load_only(), Configuration._get_parser_to_modify(), Configuration._mark_as_modified(), pip._internal.configuration._normalize_name(), i, and Configuration.load_only.

Here is the call graph for this function:

◆ unset_value()

None unset_value (   self,
str  key 
)
Unset a value in the configuration.

Definition at line 174 of file configuration.py.

174 def unset_value(self, key: str) -> None:
175 """Unset a value in the configuration."""
176 orig_key = key
177 key = _normalize_name(key)
178 self._ensure_have_load_only()
179
180 assert self.load_only
181 if key not in self._config[self.load_only]:
182 raise ConfigurationError(f"No such key - {orig_key}")
183
184 fname, parser = self._get_parser_to_modify()
185
186 if parser is not None:
187 section, name = _disassemble_key(key)
188 if not (
189 parser.has_section(section) and parser.remove_option(section, name)
190 ):
191 # The option was not removed.
192 raise ConfigurationError(
193 "Fatal Internal error [id=1]. Please report as a bug."
194 )
195
196 # The section may be empty after the option was removed.
197 if not parser.items(section):
198 parser.remove_section(section)
199 self._mark_as_modified(fname, parser)
200
201 del self._config[self.load_only][key]
202

References pip._internal.configuration._disassemble_key(), Configuration._ensure_have_load_only(), Configuration._get_parser_to_modify(), Configuration._mark_as_modified(), pip._internal.configuration._normalize_name(), i, and Configuration.load_only.

Here is the call graph for this function:

Field Documentation

◆ isolated

◆ load_only


The documentation for this class was generated from the following file: