techprotrade commited on
Commit
eddc35d
·
verified ·
1 Parent(s): 7a6292f

Add loan-advisor-agent

Browse files
Files changed (26) hide show
  1. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__init__.py +1191 -0
  2. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/__init__.cpython-312.pyc +0 -0
  3. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_adapters.cpython-312.pyc +0 -0
  4. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_collections.cpython-312.pyc +0 -0
  5. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_compat.cpython-312.pyc +0 -0
  6. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_functools.cpython-312.pyc +0 -0
  7. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_itertools.cpython-312.pyc +0 -0
  8. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_meta.cpython-312.pyc +0 -0
  9. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_text.cpython-312.pyc +0 -0
  10. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_typing.cpython-312.pyc +0 -0
  11. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_adapters.py +136 -0
  12. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_collections.py +34 -0
  13. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_compat.py +56 -0
  14. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_functools.py +135 -0
  15. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_itertools.py +171 -0
  16. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_meta.py +71 -0
  17. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_text.py +99 -0
  18. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_typing.py +15 -0
  19. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/__init__.py +0 -0
  20. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/__pycache__/__init__.cpython-312.pyc +0 -0
  21. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/__pycache__/py311.cpython-312.pyc +0 -0
  22. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/__pycache__/py39.cpython-312.pyc +0 -0
  23. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/py311.py +22 -0
  24. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/py39.py +42 -0
  25. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/diagnose.py +21 -0
  26. loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/py.typed +0 -0
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__init__.py ADDED
@@ -0,0 +1,1191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ APIs exposing metadata from third-party Python packages.
3
+
4
+ This codebase is shared between importlib.metadata in the stdlib
5
+ and importlib_metadata in PyPI. See
6
+ https://github.com/python/importlib_metadata/wiki/Development-Methodology
7
+ for more detail.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import abc
13
+ import collections
14
+ import email
15
+ import functools
16
+ import itertools
17
+ import operator
18
+ import os
19
+ import pathlib
20
+ import posixpath
21
+ import re
22
+ import sys
23
+ import textwrap
24
+ import types
25
+ from collections.abc import Iterable, Mapping
26
+ from contextlib import suppress
27
+ from importlib import import_module
28
+ from importlib.abc import MetaPathFinder
29
+ from itertools import starmap
30
+ from typing import Any
31
+
32
+ from . import _meta
33
+ from ._collections import FreezableDefaultDict, Pair
34
+ from ._compat import (
35
+ NullFinder,
36
+ install,
37
+ )
38
+ from ._functools import method_cache, noop, pass_none, passthrough
39
+ from ._itertools import always_iterable, bucket, unique_everseen
40
+ from ._meta import PackageMetadata, SimplePath
41
+ from ._typing import md_none
42
+ from .compat import py39, py311
43
+
44
+ __all__ = [
45
+ 'Distribution',
46
+ 'DistributionFinder',
47
+ 'PackageMetadata',
48
+ 'PackageNotFoundError',
49
+ 'SimplePath',
50
+ 'distribution',
51
+ 'distributions',
52
+ 'entry_points',
53
+ 'files',
54
+ 'metadata',
55
+ 'packages_distributions',
56
+ 'requires',
57
+ 'version',
58
+ ]
59
+
60
+
61
+ class PackageNotFoundError(ModuleNotFoundError):
62
+ """The package was not found."""
63
+
64
+ def __str__(self) -> str:
65
+ return f"No package metadata was found for {self.name}"
66
+
67
+ @property
68
+ def name(self) -> str: # type: ignore[override] # make readonly
69
+ (name,) = self.args
70
+ return name
71
+
72
+
73
+ class Sectioned:
74
+ """
75
+ A simple entry point config parser for performance
76
+
77
+ >>> for item in Sectioned.read(Sectioned._sample):
78
+ ... print(item)
79
+ Pair(name='sec1', value='# comments ignored')
80
+ Pair(name='sec1', value='a = 1')
81
+ Pair(name='sec1', value='b = 2')
82
+ Pair(name='sec2', value='a = 2')
83
+
84
+ >>> res = Sectioned.section_pairs(Sectioned._sample)
85
+ >>> item = next(res)
86
+ >>> item.name
87
+ 'sec1'
88
+ >>> item.value
89
+ Pair(name='a', value='1')
90
+ >>> item = next(res)
91
+ >>> item.value
92
+ Pair(name='b', value='2')
93
+ >>> item = next(res)
94
+ >>> item.name
95
+ 'sec2'
96
+ >>> item.value
97
+ Pair(name='a', value='2')
98
+ >>> list(res)
99
+ []
100
+ """
101
+
102
+ _sample = textwrap.dedent(
103
+ """
104
+ [sec1]
105
+ # comments ignored
106
+ a = 1
107
+ b = 2
108
+
109
+ [sec2]
110
+ a = 2
111
+ """
112
+ ).lstrip()
113
+
114
+ @classmethod
115
+ def section_pairs(cls, text):
116
+ return (
117
+ section._replace(value=Pair.parse(section.value))
118
+ for section in cls.read(text, filter_=cls.valid)
119
+ if section.name is not None
120
+ )
121
+
122
+ @staticmethod
123
+ def read(text, filter_=None):
124
+ lines = filter(filter_, map(str.strip, text.splitlines()))
125
+ name = None
126
+ for value in lines:
127
+ section_match = value.startswith('[') and value.endswith(']')
128
+ if section_match:
129
+ name = value.strip('[]')
130
+ continue
131
+ yield Pair(name, value)
132
+
133
+ @staticmethod
134
+ def valid(line: str):
135
+ return line and not line.startswith('#')
136
+
137
+
138
+ class _EntryPointMatch(types.SimpleNamespace):
139
+ module: str
140
+ attr: str
141
+ extras: str
142
+
143
+
144
+ class EntryPoint:
145
+ """An entry point as defined by Python packaging conventions.
146
+
147
+ See `the packaging docs on entry points
148
+ <https://packaging.python.org/specifications/entry-points/>`_
149
+ for more information.
150
+
151
+ >>> ep = EntryPoint(
152
+ ... name=None, group=None, value='package.module:attr [extra1, extra2]')
153
+ >>> ep.module
154
+ 'package.module'
155
+ >>> ep.attr
156
+ 'attr'
157
+ >>> ep.extras
158
+ ['extra1', 'extra2']
159
+
160
+ If the value package or module are not valid identifiers, a
161
+ ValueError is raised on access.
162
+
163
+ >>> EntryPoint(name=None, group=None, value='invalid-name').module
164
+ Traceback (most recent call last):
165
+ ...
166
+ ValueError: ('Invalid object reference...invalid-name...
167
+ >>> EntryPoint(name=None, group=None, value='invalid-name').attr
168
+ Traceback (most recent call last):
169
+ ...
170
+ ValueError: ('Invalid object reference...invalid-name...
171
+ >>> EntryPoint(name=None, group=None, value='invalid-name').extras
172
+ Traceback (most recent call last):
173
+ ...
174
+ ValueError: ('Invalid object reference...invalid-name...
175
+
176
+ The same thing happens on construction.
177
+
178
+ >>> EntryPoint(name=None, group=None, value='invalid-name')
179
+ Traceback (most recent call last):
180
+ ...
181
+ ValueError: ('Invalid object reference...invalid-name...
182
+
183
+ """
184
+
185
+ pattern = re.compile(
186
+ r'(?P<module>[\w.]+)\s*'
187
+ r'(:\s*(?P<attr>[\w.]+)\s*)?'
188
+ r'((?P<extras>\[.*\])\s*)?$'
189
+ )
190
+ """
191
+ A regular expression describing the syntax for an entry point,
192
+ which might look like:
193
+
194
+ - module
195
+ - package.module
196
+ - package.module:attribute
197
+ - package.module:object.attribute
198
+ - package.module:attr [extra1, extra2]
199
+
200
+ Other combinations are possible as well.
201
+
202
+ The expression is lenient about whitespace around the ':',
203
+ following the attr, and following any extras.
204
+ """
205
+
206
+ name: str
207
+ value: str
208
+ group: str
209
+
210
+ dist: Distribution | None = None
211
+
212
+ def __init__(self, name: str, value: str, group: str) -> None:
213
+ vars(self).update(name=name, value=value, group=group)
214
+ self.module
215
+
216
+ def load(self) -> Any:
217
+ """Load the entry point from its definition. If only a module
218
+ is indicated by the value, return that module. Otherwise,
219
+ return the named object.
220
+ """
221
+ module = import_module(self.module)
222
+ attrs = filter(None, (self.attr or '').split('.'))
223
+ return functools.reduce(getattr, attrs, module)
224
+
225
+ @property
226
+ def module(self) -> str:
227
+ return self._match.module
228
+
229
+ @property
230
+ def attr(self) -> str:
231
+ return self._match.attr
232
+
233
+ @property
234
+ def extras(self) -> list[str]:
235
+ return re.findall(r'\w+', self._match.extras or '')
236
+
237
+ @functools.cached_property
238
+ def _match(self) -> _EntryPointMatch:
239
+ match = self.pattern.match(self.value)
240
+ if not match:
241
+ raise ValueError(
242
+ 'Invalid object reference. '
243
+ 'See https://packaging.python.org'
244
+ '/en/latest/specifications/entry-points/#data-model',
245
+ self.value,
246
+ )
247
+ return _EntryPointMatch(**match.groupdict())
248
+
249
+ def _for(self, dist):
250
+ vars(self).update(dist=dist)
251
+ return self
252
+
253
+ def matches(self, **params):
254
+ """
255
+ EntryPoint matches the given parameters.
256
+
257
+ >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]')
258
+ >>> ep.matches(group='foo')
259
+ True
260
+ >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]')
261
+ True
262
+ >>> ep.matches(group='foo', name='other')
263
+ False
264
+ >>> ep.matches()
265
+ True
266
+ >>> ep.matches(extras=['extra1', 'extra2'])
267
+ True
268
+ >>> ep.matches(module='bing')
269
+ True
270
+ >>> ep.matches(attr='bong')
271
+ True
272
+ """
273
+ self._disallow_dist(params)
274
+ attrs = (getattr(self, param) for param in params)
275
+ return all(map(operator.eq, params.values(), attrs))
276
+
277
+ @staticmethod
278
+ def _disallow_dist(params):
279
+ """
280
+ Querying by dist is not allowed (dist objects are not comparable).
281
+ >>> EntryPoint(name='fan', value='fav', group='fag').matches(dist='foo')
282
+ Traceback (most recent call last):
283
+ ...
284
+ ValueError: "dist" is not suitable for matching...
285
+ """
286
+ if "dist" in params:
287
+ raise ValueError(
288
+ '"dist" is not suitable for matching. '
289
+ "Instead, use Distribution.entry_points.select() on a "
290
+ "located distribution."
291
+ )
292
+
293
+ def _key(self):
294
+ return self.name, self.value, self.group
295
+
296
+ def __lt__(self, other):
297
+ return self._key() < other._key()
298
+
299
+ def __eq__(self, other):
300
+ return self._key() == other._key()
301
+
302
+ def __setattr__(self, name, value):
303
+ raise AttributeError("EntryPoint objects are immutable.")
304
+
305
+ def __repr__(self):
306
+ return (
307
+ f'EntryPoint(name={self.name!r}, value={self.value!r}, '
308
+ f'group={self.group!r})'
309
+ )
310
+
311
+ def __hash__(self) -> int:
312
+ return hash(self._key())
313
+
314
+
315
+ class EntryPoints(tuple):
316
+ """
317
+ An immutable collection of selectable EntryPoint objects.
318
+ """
319
+
320
+ __slots__ = ()
321
+
322
+ def __getitem__(self, name: str) -> EntryPoint: # type: ignore[override] # Work with str instead of int
323
+ """
324
+ Get the EntryPoint in self matching name.
325
+ """
326
+ try:
327
+ return next(iter(self.select(name=name)))
328
+ except StopIteration:
329
+ raise KeyError(name)
330
+
331
+ def __repr__(self):
332
+ """
333
+ Repr with classname and tuple constructor to
334
+ signal that we deviate from regular tuple behavior.
335
+ """
336
+ return '%s(%r)' % (self.__class__.__name__, tuple(self))
337
+
338
+ def select(self, **params) -> EntryPoints:
339
+ """
340
+ Select entry points from self that match the
341
+ given parameters (typically group and/or name).
342
+ """
343
+ return EntryPoints(ep for ep in self if py39.ep_matches(ep, **params))
344
+
345
+ @property
346
+ def names(self) -> set[str]:
347
+ """
348
+ Return the set of all names of all entry points.
349
+ """
350
+ return {ep.name for ep in self}
351
+
352
+ @property
353
+ def groups(self) -> set[str]:
354
+ """
355
+ Return the set of all groups of all entry points.
356
+ """
357
+ return {ep.group for ep in self}
358
+
359
+ @classmethod
360
+ def _from_text_for(cls, text, dist):
361
+ return cls(ep._for(dist) for ep in cls._from_text(text))
362
+
363
+ @staticmethod
364
+ def _from_text(text):
365
+ return (
366
+ EntryPoint(name=item.value.name, value=item.value.value, group=item.name)
367
+ for item in Sectioned.section_pairs(text or '')
368
+ )
369
+
370
+
371
+ class PackagePath(pathlib.PurePosixPath):
372
+ """A reference to a path in a package"""
373
+
374
+ hash: FileHash | None
375
+ size: int
376
+ dist: Distribution
377
+
378
+ def read_text(self, encoding: str = 'utf-8') -> str:
379
+ return self.locate().read_text(encoding=encoding)
380
+
381
+ def read_binary(self) -> bytes:
382
+ return self.locate().read_bytes()
383
+
384
+ def locate(self) -> SimplePath:
385
+ """Return a path-like object for this path"""
386
+ return self.dist.locate_file(self)
387
+
388
+
389
+ class FileHash:
390
+ def __init__(self, spec: str) -> None:
391
+ self.mode, _, self.value = spec.partition('=')
392
+
393
+ def __repr__(self) -> str:
394
+ return f'<FileHash mode: {self.mode} value: {self.value}>'
395
+
396
+
397
+ class Distribution(metaclass=abc.ABCMeta):
398
+ """
399
+ An abstract Python distribution package.
400
+
401
+ Custom providers may derive from this class and define
402
+ the abstract methods to provide a concrete implementation
403
+ for their environment. Some providers may opt to override
404
+ the default implementation of some properties to bypass
405
+ the file-reading mechanism.
406
+ """
407
+
408
+ @abc.abstractmethod
409
+ def read_text(self, filename) -> str | None:
410
+ """Attempt to load metadata file given by the name.
411
+
412
+ Python distribution metadata is organized by blobs of text
413
+ typically represented as "files" in the metadata directory
414
+ (e.g. package-1.0.dist-info). These files include things
415
+ like:
416
+
417
+ - METADATA: The distribution metadata including fields
418
+ like Name and Version and Description.
419
+ - entry_points.txt: A series of entry points as defined in
420
+ `the entry points spec <https://packaging.python.org/en/latest/specifications/entry-points/#file-format>`_.
421
+ - RECORD: A record of files according to
422
+ `this recording spec <https://packaging.python.org/en/latest/specifications/recording-installed-packages/#the-record-file>`_.
423
+
424
+ A package may provide any set of files, including those
425
+ not listed here or none at all.
426
+
427
+ :param filename: The name of the file in the distribution info.
428
+ :return: The text if found, otherwise None.
429
+ """
430
+
431
+ @abc.abstractmethod
432
+ def locate_file(self, path: str | os.PathLike[str]) -> SimplePath:
433
+ """
434
+ Given a path to a file in this distribution, return a SimplePath
435
+ to it.
436
+
437
+ This method is used by callers of ``Distribution.files()`` to
438
+ locate files within the distribution. If it's possible for a
439
+ Distribution to represent files in the distribution as
440
+ ``SimplePath`` objects, it should implement this method
441
+ to resolve such objects.
442
+
443
+ Some Distribution providers may elect not to resolve SimplePath
444
+ objects within the distribution by raising a
445
+ NotImplementedError, but consumers of such a Distribution would
446
+ be unable to invoke ``Distribution.files()``.
447
+ """
448
+
449
+ @classmethod
450
+ def from_name(cls, name: str) -> Distribution:
451
+ """Return the Distribution for the given package name.
452
+
453
+ :param name: The name of the distribution package to search for.
454
+ :return: The Distribution instance (or subclass thereof) for the named
455
+ package, if found.
456
+ :raises PackageNotFoundError: When the named package's distribution
457
+ metadata cannot be found.
458
+ :raises ValueError: When an invalid value is supplied for name.
459
+ """
460
+ if not name:
461
+ raise ValueError("A distribution name is required.")
462
+ try:
463
+ return next(iter(cls._prefer_valid(cls.discover(name=name))))
464
+ except StopIteration:
465
+ raise PackageNotFoundError(name)
466
+
467
+ @classmethod
468
+ def discover(
469
+ cls, *, context: DistributionFinder.Context | None = None, **kwargs
470
+ ) -> Iterable[Distribution]:
471
+ """Return an iterable of Distribution objects for all packages.
472
+
473
+ Pass a ``context`` or pass keyword arguments for constructing
474
+ a context.
475
+
476
+ :context: A ``DistributionFinder.Context`` object.
477
+ :return: Iterable of Distribution objects for packages matching
478
+ the context.
479
+ """
480
+ if context and kwargs:
481
+ raise ValueError("cannot accept context and kwargs")
482
+ context = context or DistributionFinder.Context(**kwargs)
483
+ return itertools.chain.from_iterable(
484
+ resolver(context) for resolver in cls._discover_resolvers()
485
+ )
486
+
487
+ @staticmethod
488
+ def _prefer_valid(dists: Iterable[Distribution]) -> Iterable[Distribution]:
489
+ """
490
+ Prefer (move to the front) distributions that have metadata.
491
+
492
+ Ref python/importlib_resources#489.
493
+ """
494
+ buckets = bucket(dists, lambda dist: bool(dist.metadata))
495
+ return itertools.chain(buckets[True], buckets[False])
496
+
497
+ @staticmethod
498
+ def at(path: str | os.PathLike[str]) -> Distribution:
499
+ """Return a Distribution for the indicated metadata path.
500
+
501
+ :param path: a string or path-like object
502
+ :return: a concrete Distribution instance for the path
503
+ """
504
+ return PathDistribution(pathlib.Path(path))
505
+
506
+ @staticmethod
507
+ def _discover_resolvers():
508
+ """Search the meta_path for resolvers (MetadataPathFinders)."""
509
+ declared = (
510
+ getattr(finder, 'find_distributions', None) for finder in sys.meta_path
511
+ )
512
+ return filter(None, declared)
513
+
514
+ @property
515
+ def metadata(self) -> _meta.PackageMetadata | None:
516
+ """Return the parsed metadata for this Distribution.
517
+
518
+ The returned object will have keys that name the various bits of
519
+ metadata per the
520
+ `Core metadata specifications <https://packaging.python.org/en/latest/specifications/core-metadata/#core-metadata>`_.
521
+
522
+ Custom providers may provide the METADATA file or override this
523
+ property.
524
+ """
525
+
526
+ text = (
527
+ self.read_text('METADATA')
528
+ or self.read_text('PKG-INFO')
529
+ # This last clause is here to support old egg-info files. Its
530
+ # effect is to just end up using the PathDistribution's self._path
531
+ # (which points to the egg-info file) attribute unchanged.
532
+ or self.read_text('')
533
+ )
534
+ return self._assemble_message(text)
535
+
536
+ @staticmethod
537
+ @pass_none
538
+ def _assemble_message(text: str) -> _meta.PackageMetadata:
539
+ # deferred for performance (python/cpython#109829)
540
+ from . import _adapters
541
+
542
+ return _adapters.Message(email.message_from_string(text))
543
+
544
+ @property
545
+ def name(self) -> str:
546
+ """Return the 'Name' metadata for the distribution package."""
547
+ return md_none(self.metadata)['Name']
548
+
549
+ @property
550
+ def _normalized_name(self):
551
+ """Return a normalized version of the name."""
552
+ return Prepared.normalize(self.name)
553
+
554
+ @property
555
+ def version(self) -> str:
556
+ """Return the 'Version' metadata for the distribution package."""
557
+ return md_none(self.metadata)['Version']
558
+
559
+ @property
560
+ def entry_points(self) -> EntryPoints:
561
+ """
562
+ Return EntryPoints for this distribution.
563
+
564
+ Custom providers may provide the ``entry_points.txt`` file
565
+ or override this property.
566
+ """
567
+ return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self)
568
+
569
+ @property
570
+ def files(self) -> list[PackagePath] | None:
571
+ """Files in this distribution.
572
+
573
+ :return: List of PackagePath for this distribution or None
574
+
575
+ Result is `None` if the metadata file that enumerates files
576
+ (i.e. RECORD for dist-info, or installed-files.txt or
577
+ SOURCES.txt for egg-info) is missing.
578
+ Result may be empty if the metadata exists but is empty.
579
+
580
+ Custom providers are recommended to provide a "RECORD" file (in
581
+ ``read_text``) or override this property to allow for callers to be
582
+ able to resolve filenames provided by the package.
583
+ """
584
+
585
+ def make_file(name, hash=None, size_str=None):
586
+ result = PackagePath(name)
587
+ result.hash = FileHash(hash) if hash else None
588
+ result.size = int(size_str) if size_str else None
589
+ result.dist = self
590
+ return result
591
+
592
+ @pass_none
593
+ def make_files(lines):
594
+ # Delay csv import, since Distribution.files is not as widely used
595
+ # as other parts of importlib.metadata
596
+ import csv
597
+
598
+ return starmap(make_file, csv.reader(lines))
599
+
600
+ @pass_none
601
+ def skip_missing_files(package_paths):
602
+ return list(filter(lambda path: path.locate().exists(), package_paths))
603
+
604
+ return skip_missing_files(
605
+ make_files(
606
+ self._read_files_distinfo()
607
+ or self._read_files_egginfo_installed()
608
+ or self._read_files_egginfo_sources()
609
+ )
610
+ )
611
+
612
+ def _read_files_distinfo(self):
613
+ """
614
+ Read the lines of RECORD.
615
+ """
616
+ text = self.read_text('RECORD')
617
+ return text and text.splitlines()
618
+
619
+ def _read_files_egginfo_installed(self):
620
+ """
621
+ Read installed-files.txt and return lines in a similar
622
+ CSV-parsable format as RECORD: each file must be placed
623
+ relative to the site-packages directory and must also be
624
+ quoted (since file names can contain literal commas).
625
+
626
+ This file is written when the package is installed by pip,
627
+ but it might not be written for other installation methods.
628
+ Assume the file is accurate if it exists.
629
+ """
630
+ text = self.read_text('installed-files.txt')
631
+ # Prepend the .egg-info/ subdir to the lines in this file.
632
+ # But this subdir is only available from PathDistribution's
633
+ # self._path.
634
+ subdir = getattr(self, '_path', None)
635
+ if not text or not subdir:
636
+ return
637
+
638
+ paths = (
639
+ py311
640
+ .relative_fix((subdir / name).resolve())
641
+ .relative_to(self.locate_file('').resolve(), walk_up=True)
642
+ .as_posix()
643
+ for name in text.splitlines()
644
+ )
645
+ return map('"{}"'.format, paths)
646
+
647
+ def _read_files_egginfo_sources(self):
648
+ """
649
+ Read SOURCES.txt and return lines in a similar CSV-parsable
650
+ format as RECORD: each file name must be quoted (since it
651
+ might contain literal commas).
652
+
653
+ Note that SOURCES.txt is not a reliable source for what
654
+ files are installed by a package. This file is generated
655
+ for a source archive, and the files that are present
656
+ there (e.g. setup.py) may not correctly reflect the files
657
+ that are present after the package has been installed.
658
+ """
659
+ text = self.read_text('SOURCES.txt')
660
+ return text and map('"{}"'.format, text.splitlines())
661
+
662
+ @property
663
+ def requires(self) -> list[str] | None:
664
+ """Generated requirements specified for this Distribution"""
665
+ reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs()
666
+ return reqs and list(reqs)
667
+
668
+ def _read_dist_info_reqs(self):
669
+ return self.metadata.get_all('Requires-Dist')
670
+
671
+ def _read_egg_info_reqs(self):
672
+ source = self.read_text('requires.txt')
673
+ return pass_none(self._deps_from_requires_text)(source)
674
+
675
+ @classmethod
676
+ def _deps_from_requires_text(cls, source):
677
+ return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source))
678
+
679
+ @staticmethod
680
+ def _convert_egg_info_reqs_to_simple_reqs(sections):
681
+ """
682
+ Historically, setuptools would solicit and store 'extra'
683
+ requirements, including those with environment markers,
684
+ in separate sections. More modern tools expect each
685
+ dependency to be defined separately, with any relevant
686
+ extras and environment markers attached directly to that
687
+ requirement. This method converts the former to the
688
+ latter. See _test_deps_from_requires_text for an example.
689
+ """
690
+
691
+ def make_condition(name):
692
+ return name and f'extra == "{name}"'
693
+
694
+ def quoted_marker(section):
695
+ section = section or ''
696
+ extra, sep, markers = section.partition(':')
697
+ if extra and markers:
698
+ markers = f'({markers})'
699
+ conditions = list(filter(None, [markers, make_condition(extra)]))
700
+ return '; ' + ' and '.join(conditions) if conditions else ''
701
+
702
+ def url_req_space(req):
703
+ """
704
+ PEP 508 requires a space between the url_spec and the quoted_marker.
705
+ Ref python/importlib_metadata#357.
706
+ """
707
+ # '@' is uniquely indicative of a url_req.
708
+ return ' ' * ('@' in req)
709
+
710
+ for section in sections:
711
+ space = url_req_space(section.value)
712
+ yield section.value + space + quoted_marker(section.name)
713
+
714
+ @property
715
+ def origin(self):
716
+ return self._load_json('direct_url.json')
717
+
718
+ def _load_json(self, filename):
719
+ # Deferred for performance (python/importlib_metadata#503)
720
+ import json
721
+
722
+ return pass_none(json.loads)(
723
+ self.read_text(filename),
724
+ object_hook=lambda data: types.SimpleNamespace(**data),
725
+ )
726
+
727
+
728
+ class DistributionFinder(MetaPathFinder):
729
+ """
730
+ A MetaPathFinder capable of discovering installed distributions.
731
+
732
+ Custom providers should implement this interface in order to
733
+ supply metadata.
734
+ """
735
+
736
+ class Context:
737
+ """
738
+ Keyword arguments presented by the caller to
739
+ ``distributions()`` or ``Distribution.discover()``
740
+ to narrow the scope of a search for distributions
741
+ in all DistributionFinders.
742
+
743
+ Each DistributionFinder may expect any parameters
744
+ and should attempt to honor the canonical
745
+ parameters defined below when appropriate.
746
+
747
+ This mechanism gives a custom provider a means to
748
+ solicit additional details from the caller beyond
749
+ "name" and "path" when searching distributions.
750
+ For example, imagine a provider that exposes suites
751
+ of packages in either a "public" or "private" ``realm``.
752
+ A caller may wish to query only for distributions in
753
+ a particular realm and could call
754
+ ``distributions(realm="private")`` to signal to the
755
+ custom provider to only include distributions from that
756
+ realm.
757
+ """
758
+
759
+ name = None
760
+ """
761
+ Specific name for which a distribution finder should match.
762
+ A name of ``None`` matches all distributions.
763
+ """
764
+
765
+ def __init__(self, **kwargs):
766
+ vars(self).update(kwargs)
767
+
768
+ @property
769
+ def path(self) -> list[str]:
770
+ """
771
+ The sequence of directory path that a distribution finder
772
+ should search.
773
+
774
+ Typically refers to Python installed package paths such as
775
+ "site-packages" directories and defaults to ``sys.path``.
776
+ """
777
+ return vars(self).get('path', sys.path)
778
+
779
+ @abc.abstractmethod
780
+ def find_distributions(self, context=Context()) -> Iterable[Distribution]:
781
+ """
782
+ Find distributions.
783
+
784
+ Return an iterable of all Distribution instances capable of
785
+ loading the metadata for packages matching the ``context``,
786
+ a DistributionFinder.Context instance.
787
+ """
788
+
789
+
790
+ @passthrough
791
+ def _clear_after_fork(cached):
792
+ """Ensure ``func`` clears cached state after ``fork`` when supported.
793
+
794
+ ``FastPath`` caches zip-backed ``pathlib.Path`` objects that retain a
795
+ reference to the parent's open ``ZipFile`` handle. Re-using a cached
796
+ instance in a forked child can therefore resurrect invalid file pointers
797
+ and trigger ``BadZipFile``/``OSError`` failures (python/importlib_metadata#520).
798
+ Registering ``cache_clear`` with ``os.register_at_fork`` keeps each process
799
+ on its own cache.
800
+ """
801
+ getattr(os, 'register_at_fork', noop)(after_in_child=cached.cache_clear)
802
+
803
+
804
+ class FastPath:
805
+ """
806
+ Micro-optimized class for searching a root for children.
807
+
808
+ Root is a path on the file system that may contain metadata
809
+ directories either as natural directories or within a zip file.
810
+
811
+ >>> FastPath('').children()
812
+ ['...']
813
+
814
+ FastPath objects are cached and recycled for any given root.
815
+
816
+ >>> FastPath('foobar') is FastPath('foobar')
817
+ True
818
+ """
819
+
820
+ @_clear_after_fork # type: ignore[misc]
821
+ @functools.lru_cache()
822
+ def __new__(cls, root):
823
+ return super().__new__(cls)
824
+
825
+ def __init__(self, root):
826
+ self.root = root
827
+
828
+ def joinpath(self, child):
829
+ return pathlib.Path(self.root, child)
830
+
831
+ def children(self):
832
+ with suppress(Exception):
833
+ return os.listdir(self.root or '.')
834
+ with suppress(Exception):
835
+ return self.zip_children()
836
+ return []
837
+
838
+ def zip_children(self):
839
+ # deferred for performance (python/importlib_metadata#502)
840
+ from zipp.compat.overlay import zipfile
841
+
842
+ zip_path = zipfile.Path(self.root)
843
+ names = zip_path.root.namelist()
844
+ self.joinpath = zip_path.joinpath
845
+
846
+ return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names)
847
+
848
+ def search(self, name):
849
+ return self.lookup(self.mtime).search(name)
850
+
851
+ @property
852
+ def mtime(self):
853
+ with suppress(OSError):
854
+ return os.stat(self.root).st_mtime
855
+ self.lookup.cache_clear()
856
+
857
+ @method_cache
858
+ def lookup(self, mtime):
859
+ return Lookup(self)
860
+
861
+
862
+ class Lookup:
863
+ """
864
+ A micro-optimized class for searching a (fast) path for metadata.
865
+ """
866
+
867
+ def __init__(self, path: FastPath):
868
+ """
869
+ Calculate all of the children representing metadata.
870
+
871
+ From the children in the path, calculate early all of the
872
+ children that appear to represent metadata (infos) or legacy
873
+ metadata (eggs).
874
+ """
875
+
876
+ base = os.path.basename(path.root).lower()
877
+ base_is_egg = base.endswith(".egg")
878
+ self.infos = FreezableDefaultDict(list)
879
+ self.eggs = FreezableDefaultDict(list)
880
+
881
+ for child in path.children():
882
+ low = child.lower()
883
+ if low.endswith((".dist-info", ".egg-info")):
884
+ # rpartition is faster than splitext and suitable for this purpose.
885
+ name = low.rpartition(".")[0].partition("-")[0]
886
+ normalized = Prepared.normalize(name)
887
+ self.infos[normalized].append(path.joinpath(child))
888
+ elif base_is_egg and low == "egg-info":
889
+ name = base.rpartition(".")[0].partition("-")[0]
890
+ legacy_normalized = Prepared.legacy_normalize(name)
891
+ self.eggs[legacy_normalized].append(path.joinpath(child))
892
+
893
+ self.infos.freeze()
894
+ self.eggs.freeze()
895
+
896
+ def search(self, prepared: Prepared):
897
+ """
898
+ Yield all infos and eggs matching the Prepared query.
899
+ """
900
+ infos = (
901
+ self.infos[prepared.normalized]
902
+ if prepared
903
+ else itertools.chain.from_iterable(self.infos.values())
904
+ )
905
+ eggs = (
906
+ self.eggs[prepared.legacy_normalized]
907
+ if prepared
908
+ else itertools.chain.from_iterable(self.eggs.values())
909
+ )
910
+ return itertools.chain(infos, eggs)
911
+
912
+
913
+ class Prepared:
914
+ """
915
+ A prepared search query for metadata on a possibly-named package.
916
+
917
+ Pre-calculates the normalization to prevent repeated operations.
918
+
919
+ >>> none = Prepared(None)
920
+ >>> none.normalized
921
+ >>> none.legacy_normalized
922
+ >>> bool(none)
923
+ False
924
+ >>> sample = Prepared('Sample__Pkg-name.foo')
925
+ >>> sample.normalized
926
+ 'sample_pkg_name_foo'
927
+ >>> sample.legacy_normalized
928
+ 'sample__pkg_name.foo'
929
+ >>> bool(sample)
930
+ True
931
+ """
932
+
933
+ normalized = None
934
+ legacy_normalized = None
935
+
936
+ def __init__(self, name: str | None):
937
+ self.name = name
938
+ if name is None:
939
+ return
940
+ self.normalized = self.normalize(name)
941
+ self.legacy_normalized = self.legacy_normalize(name)
942
+
943
+ @staticmethod
944
+ def normalize(name):
945
+ """
946
+ PEP 503 normalization plus dashes as underscores.
947
+ """
948
+ return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_')
949
+
950
+ @staticmethod
951
+ def legacy_normalize(name):
952
+ """
953
+ Normalize the package name as found in the convention in
954
+ older packaging tools versions and specs.
955
+ """
956
+ return name.lower().replace('-', '_')
957
+
958
+ def __bool__(self):
959
+ return bool(self.name)
960
+
961
+
962
+ @install
963
+ class MetadataPathFinder(NullFinder, DistributionFinder):
964
+ """A degenerate finder for distribution packages on the file system.
965
+
966
+ This finder supplies only a find_distributions() method for versions
967
+ of Python that do not have a PathFinder find_distributions().
968
+ """
969
+
970
+ @classmethod
971
+ def find_distributions(
972
+ cls, context=DistributionFinder.Context()
973
+ ) -> Iterable[PathDistribution]:
974
+ """
975
+ Find distributions.
976
+
977
+ Return an iterable of all Distribution instances capable of
978
+ loading the metadata for packages matching ``context.name``
979
+ (or all names if ``None`` indicated) along the paths in the list
980
+ of directories ``context.path``.
981
+ """
982
+ found = cls._search_paths(context.name, context.path)
983
+ return map(PathDistribution, found)
984
+
985
+ @classmethod
986
+ def _search_paths(cls, name, paths):
987
+ """Find metadata directories in paths heuristically."""
988
+ prepared = Prepared(name)
989
+ return itertools.chain.from_iterable(
990
+ path.search(prepared) for path in map(FastPath, paths)
991
+ )
992
+
993
+ @classmethod
994
+ def invalidate_caches(cls) -> None:
995
+ FastPath.__new__.cache_clear()
996
+
997
+
998
+ class PathDistribution(Distribution):
999
+ def __init__(self, path: SimplePath) -> None:
1000
+ """Construct a distribution.
1001
+
1002
+ :param path: SimplePath indicating the metadata directory.
1003
+ """
1004
+ self._path = path
1005
+
1006
+ def read_text(self, filename: str | os.PathLike[str]) -> str | None:
1007
+ with suppress(
1008
+ FileNotFoundError,
1009
+ IsADirectoryError,
1010
+ KeyError,
1011
+ NotADirectoryError,
1012
+ PermissionError,
1013
+ ):
1014
+ return self._path.joinpath(filename).read_text(encoding='utf-8')
1015
+
1016
+ return None
1017
+
1018
+ read_text.__doc__ = Distribution.read_text.__doc__
1019
+
1020
+ def locate_file(self, path: str | os.PathLike[str]) -> SimplePath:
1021
+ return self._path.parent / path
1022
+
1023
+ @property
1024
+ def _normalized_name(self):
1025
+ """
1026
+ Performance optimization: where possible, resolve the
1027
+ normalized name from the file system path.
1028
+ """
1029
+ stem = os.path.basename(str(self._path))
1030
+ return (
1031
+ pass_none(Prepared.normalize)(self._name_from_stem(stem))
1032
+ or super()._normalized_name
1033
+ )
1034
+
1035
+ @staticmethod
1036
+ def _name_from_stem(stem):
1037
+ """
1038
+ >>> PathDistribution._name_from_stem('foo-3.0.egg-info')
1039
+ 'foo'
1040
+ >>> PathDistribution._name_from_stem('CherryPy-3.0.dist-info')
1041
+ 'CherryPy'
1042
+ >>> PathDistribution._name_from_stem('face.egg-info')
1043
+ 'face'
1044
+ >>> PathDistribution._name_from_stem('foo.bar')
1045
+ """
1046
+ filename, ext = os.path.splitext(stem)
1047
+ if ext not in ('.dist-info', '.egg-info'):
1048
+ return
1049
+ name, sep, rest = filename.partition('-')
1050
+ return name
1051
+
1052
+
1053
+ def distribution(distribution_name: str) -> Distribution:
1054
+ """Get the ``Distribution`` instance for the named package.
1055
+
1056
+ :param distribution_name: The name of the distribution package as a string.
1057
+ :return: A ``Distribution`` instance (or subclass thereof).
1058
+ """
1059
+ return Distribution.from_name(distribution_name)
1060
+
1061
+
1062
+ def distributions(**kwargs) -> Iterable[Distribution]:
1063
+ """Get all ``Distribution`` instances in the current environment.
1064
+
1065
+ :return: An iterable of ``Distribution`` instances.
1066
+ """
1067
+ return Distribution.discover(**kwargs)
1068
+
1069
+
1070
+ def metadata(distribution_name: str) -> _meta.PackageMetadata | None:
1071
+ """Get the metadata for the named package.
1072
+
1073
+ :param distribution_name: The name of the distribution package to query.
1074
+ :return: A PackageMetadata containing the parsed metadata.
1075
+ """
1076
+ return Distribution.from_name(distribution_name).metadata
1077
+
1078
+
1079
+ def version(distribution_name: str) -> str:
1080
+ """Get the version string for the named package.
1081
+
1082
+ :param distribution_name: The name of the distribution package to query.
1083
+ :return: The version string for the package as defined in the package's
1084
+ "Version" metadata key.
1085
+ """
1086
+ return distribution(distribution_name).version
1087
+
1088
+
1089
+ _unique = functools.partial(
1090
+ unique_everseen,
1091
+ key=py39.normalized_name,
1092
+ )
1093
+ """
1094
+ Wrapper for ``distributions`` to return unique distributions by name.
1095
+ """
1096
+
1097
+
1098
+ def entry_points(**params) -> EntryPoints:
1099
+ """Return EntryPoint objects for all installed packages.
1100
+
1101
+ Pass selection parameters (group or name) to filter the
1102
+ result to entry points matching those properties (see
1103
+ EntryPoints.select()).
1104
+
1105
+ :return: EntryPoints for all installed packages.
1106
+ """
1107
+ eps = itertools.chain.from_iterable(
1108
+ dist.entry_points for dist in _unique(distributions())
1109
+ )
1110
+ return EntryPoints(eps).select(**params)
1111
+
1112
+
1113
+ def files(distribution_name: str) -> list[PackagePath] | None:
1114
+ """Return a list of files for the named package.
1115
+
1116
+ :param distribution_name: The name of the distribution package to query.
1117
+ :return: List of files composing the distribution.
1118
+ """
1119
+ return distribution(distribution_name).files
1120
+
1121
+
1122
+ def requires(distribution_name: str) -> list[str] | None:
1123
+ """
1124
+ Return a list of requirements for the named package.
1125
+
1126
+ :return: An iterable of requirements, suitable for
1127
+ packaging.requirement.Requirement.
1128
+ """
1129
+ return distribution(distribution_name).requires
1130
+
1131
+
1132
+ def packages_distributions() -> Mapping[str, list[str]]:
1133
+ """
1134
+ Return a mapping of top-level packages to their
1135
+ distributions.
1136
+
1137
+ >>> import collections.abc
1138
+ >>> pkgs = packages_distributions()
1139
+ >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values())
1140
+ True
1141
+ """
1142
+ pkg_to_dist = collections.defaultdict(list)
1143
+ for dist in distributions():
1144
+ for pkg in _top_level_declared(dist) or _top_level_inferred(dist):
1145
+ pkg_to_dist[pkg].append(md_none(dist.metadata)['Name'])
1146
+ return dict(pkg_to_dist)
1147
+
1148
+
1149
+ def _top_level_declared(dist):
1150
+ return (dist.read_text('top_level.txt') or '').split()
1151
+
1152
+
1153
+ def _topmost(name: PackagePath) -> str | None:
1154
+ """
1155
+ Return the top-most parent as long as there is a parent.
1156
+ """
1157
+ top, *rest = name.parts
1158
+ return top if rest else None
1159
+
1160
+
1161
+ def _get_toplevel_name(name: PackagePath) -> str:
1162
+ """
1163
+ Infer a possibly importable module name from a name presumed on
1164
+ sys.path.
1165
+
1166
+ >>> _get_toplevel_name(PackagePath('foo.py'))
1167
+ 'foo'
1168
+ >>> _get_toplevel_name(PackagePath('foo'))
1169
+ 'foo'
1170
+ >>> _get_toplevel_name(PackagePath('foo.pyc'))
1171
+ 'foo'
1172
+ >>> _get_toplevel_name(PackagePath('foo/__init__.py'))
1173
+ 'foo'
1174
+ >>> _get_toplevel_name(PackagePath('foo.pth'))
1175
+ 'foo.pth'
1176
+ >>> _get_toplevel_name(PackagePath('foo.dist-info'))
1177
+ 'foo.dist-info'
1178
+ """
1179
+ # Defer import of inspect for performance (python/cpython#118761)
1180
+ import inspect
1181
+
1182
+ return _topmost(name) or inspect.getmodulename(name) or str(name)
1183
+
1184
+
1185
+ def _top_level_inferred(dist):
1186
+ opt_names = set(map(_get_toplevel_name, always_iterable(dist.files)))
1187
+
1188
+ def importable_name(name):
1189
+ return '.' not in name
1190
+
1191
+ return filter(importable_name, opt_names)
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (57.7 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_adapters.cpython-312.pyc ADDED
Binary file (5.94 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_collections.cpython-312.pyc ADDED
Binary file (1.98 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_compat.cpython-312.pyc ADDED
Binary file (2.26 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_functools.cpython-312.pyc ADDED
Binary file (4.42 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_itertools.cpython-312.pyc ADDED
Binary file (6.49 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_meta.cpython-312.pyc ADDED
Binary file (3.58 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_text.cpython-312.pyc ADDED
Binary file (3.89 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/__pycache__/_typing.cpython-312.pyc ADDED
Binary file (399 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_adapters.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import email.message
2
+ import email.policy
3
+ import re
4
+ import textwrap
5
+
6
+ from ._text import FoldedCase
7
+
8
+
9
+ class RawPolicy(email.policy.EmailPolicy):
10
+ def fold(self, name, value):
11
+ folded = self.linesep.join(
12
+ textwrap
13
+ .indent(value, prefix=' ' * 8, predicate=lambda line: True)
14
+ .lstrip()
15
+ .splitlines()
16
+ )
17
+ return f'{name}: {folded}{self.linesep}'
18
+
19
+
20
+ class Message(email.message.Message):
21
+ r"""
22
+ Specialized Message subclass to handle metadata naturally.
23
+
24
+ Reads values that may have newlines in them and converts the
25
+ payload to the Description.
26
+
27
+ >>> msg_text = textwrap.dedent('''
28
+ ... Name: Foo
29
+ ... Version: 3.0
30
+ ... License: blah
31
+ ... de-blah
32
+ ... <BLANKLINE>
33
+ ... First line of description.
34
+ ... Second line of description.
35
+ ... <BLANKLINE>
36
+ ... Fourth line!
37
+ ... ''').lstrip().replace('<BLANKLINE>', '')
38
+ >>> msg = Message(email.message_from_string(msg_text))
39
+ >>> msg['Description']
40
+ 'First line of description.\nSecond line of description.\n\nFourth line!\n'
41
+
42
+ Message should render even if values contain newlines.
43
+
44
+ >>> print(msg)
45
+ Name: Foo
46
+ Version: 3.0
47
+ License: blah
48
+ de-blah
49
+ Description: First line of description.
50
+ Second line of description.
51
+ <BLANKLINE>
52
+ Fourth line!
53
+ <BLANKLINE>
54
+ <BLANKLINE>
55
+ """
56
+
57
+ multiple_use_keys = set(
58
+ map(
59
+ FoldedCase,
60
+ [
61
+ 'Classifier',
62
+ 'Obsoletes-Dist',
63
+ 'Platform',
64
+ 'Project-URL',
65
+ 'Provides-Dist',
66
+ 'Provides-Extra',
67
+ 'Requires-Dist',
68
+ 'Requires-External',
69
+ 'Supported-Platform',
70
+ 'Dynamic',
71
+ ],
72
+ )
73
+ )
74
+ """
75
+ Keys that may be indicated multiple times per PEP 566.
76
+ """
77
+
78
+ def __new__(cls, orig: email.message.Message):
79
+ res = super().__new__(cls)
80
+ vars(res).update(vars(orig))
81
+ return res
82
+
83
+ def __init__(self, *args, **kwargs):
84
+ self._headers = self._repair_headers()
85
+
86
+ # suppress spurious error from mypy
87
+ def __iter__(self):
88
+ return super().__iter__()
89
+
90
+ def __getitem__(self, item):
91
+ """
92
+ Override parent behavior to typical dict behavior.
93
+
94
+ ``email.message.Message`` will emit None values for missing
95
+ keys. Typical mappings, including this ``Message``, will raise
96
+ a key error for missing keys.
97
+
98
+ Ref python/importlib_metadata#371.
99
+ """
100
+ res = super().__getitem__(item)
101
+ if res is None:
102
+ raise KeyError(item)
103
+ return res
104
+
105
+ def _repair_headers(self):
106
+ def redent(value):
107
+ "Correct for RFC822 indentation"
108
+ indent = ' ' * 8
109
+ if not value or '\n' + indent not in value:
110
+ return value
111
+ return textwrap.dedent(indent + value)
112
+
113
+ headers = [(key, redent(value)) for key, value in vars(self)['_headers']]
114
+ if self._payload:
115
+ headers.append(('Description', self.get_payload()))
116
+ self.set_payload('')
117
+ return headers
118
+
119
+ def as_string(self):
120
+ return super().as_string(policy=RawPolicy())
121
+
122
+ @property
123
+ def json(self):
124
+ """
125
+ Convert PackageMetadata to a JSON-compatible format
126
+ per PEP 0566.
127
+ """
128
+
129
+ def transform(key):
130
+ value = self.get_all(key) if key in self.multiple_use_keys else self[key]
131
+ if key == 'Keywords':
132
+ value = re.split(r'\s+', value)
133
+ tk = key.lower().replace('-', '_')
134
+ return tk, value
135
+
136
+ return dict(map(transform, map(FoldedCase, self)))
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_collections.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import typing
3
+
4
+
5
+ # from jaraco.collections 3.3
6
+ class FreezableDefaultDict(collections.defaultdict):
7
+ """
8
+ Often it is desirable to prevent the mutation of
9
+ a default dict after its initial construction, such
10
+ as to prevent mutation during iteration.
11
+
12
+ >>> dd = FreezableDefaultDict(list)
13
+ >>> dd[0].append('1')
14
+ >>> dd.freeze()
15
+ >>> dd[1]
16
+ []
17
+ >>> len(dd)
18
+ 1
19
+ """
20
+
21
+ def __missing__(self, key):
22
+ return getattr(self, '_frozen', super().__missing__)(key)
23
+
24
+ def freeze(self):
25
+ self._frozen = lambda key: self.default_factory()
26
+
27
+
28
+ class Pair(typing.NamedTuple):
29
+ name: str
30
+ value: str
31
+
32
+ @classmethod
33
+ def parse(cls, text):
34
+ return cls(*map(str.strip, text.split("=", 1)))
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_compat.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform
2
+ import sys
3
+
4
+ __all__ = ['install', 'NullFinder']
5
+
6
+
7
+ def install(cls):
8
+ """
9
+ Class decorator for installation on sys.meta_path.
10
+
11
+ Adds the backport DistributionFinder to sys.meta_path and
12
+ attempts to disable the finder functionality of the stdlib
13
+ DistributionFinder.
14
+ """
15
+ sys.meta_path.append(cls())
16
+ disable_stdlib_finder()
17
+ return cls
18
+
19
+
20
+ def disable_stdlib_finder():
21
+ """
22
+ Give the backport primacy for discovering path-based distributions
23
+ by monkey-patching the stdlib O_O.
24
+
25
+ See #91 for more background for rationale on this sketchy
26
+ behavior.
27
+ """
28
+
29
+ def matches(finder):
30
+ return getattr(
31
+ finder, '__module__', None
32
+ ) == '_frozen_importlib_external' and hasattr(finder, 'find_distributions')
33
+
34
+ for finder in filter(matches, sys.meta_path): # pragma: nocover
35
+ del finder.find_distributions
36
+
37
+
38
+ class NullFinder:
39
+ """
40
+ A "Finder" (aka "MetaPathFinder") that never finds any modules,
41
+ but may find distributions.
42
+ """
43
+
44
+ @staticmethod
45
+ def find_spec(*args, **kwargs):
46
+ return None
47
+
48
+
49
+ def pypy_partial(val):
50
+ """
51
+ Adjust for variable stacklevel on partial under PyPy.
52
+
53
+ Workaround for #327.
54
+ """
55
+ is_pypy = platform.python_implementation() == 'PyPy'
56
+ return val + is_pypy
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_functools.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import types
3
+ from typing import Callable, TypeVar
4
+
5
+
6
+ # from jaraco.functools 3.3
7
+ def method_cache(method, cache_wrapper=None):
8
+ """
9
+ Wrap lru_cache to support storing the cache data in the object instances.
10
+
11
+ Abstracts the common paradigm where the method explicitly saves an
12
+ underscore-prefixed protected property on first call and returns that
13
+ subsequently.
14
+
15
+ >>> class MyClass:
16
+ ... calls = 0
17
+ ...
18
+ ... @method_cache
19
+ ... def method(self, value):
20
+ ... self.calls += 1
21
+ ... return value
22
+
23
+ >>> a = MyClass()
24
+ >>> a.method(3)
25
+ 3
26
+ >>> for x in range(75):
27
+ ... res = a.method(x)
28
+ >>> a.calls
29
+ 75
30
+
31
+ Note that the apparent behavior will be exactly like that of lru_cache
32
+ except that the cache is stored on each instance, so values in one
33
+ instance will not flush values from another, and when an instance is
34
+ deleted, so are the cached values for that instance.
35
+
36
+ >>> b = MyClass()
37
+ >>> for x in range(35):
38
+ ... res = b.method(x)
39
+ >>> b.calls
40
+ 35
41
+ >>> a.method(0)
42
+ 0
43
+ >>> a.calls
44
+ 75
45
+
46
+ Note that if method had been decorated with ``functools.lru_cache()``,
47
+ a.calls would have been 76 (due to the cached value of 0 having been
48
+ flushed by the 'b' instance).
49
+
50
+ Clear the cache with ``.cache_clear()``
51
+
52
+ >>> a.method.cache_clear()
53
+
54
+ Same for a method that hasn't yet been called.
55
+
56
+ >>> c = MyClass()
57
+ >>> c.method.cache_clear()
58
+
59
+ Another cache wrapper may be supplied:
60
+
61
+ >>> cache = functools.lru_cache(maxsize=2)
62
+ >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)
63
+ >>> a = MyClass()
64
+ >>> a.method2()
65
+ 3
66
+
67
+ Caution - do not subsequently wrap the method with another decorator, such
68
+ as ``@property``, which changes the semantics of the function.
69
+
70
+ See also
71
+ http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
72
+ for another implementation and additional justification.
73
+ """
74
+ cache_wrapper = cache_wrapper or functools.lru_cache()
75
+
76
+ def wrapper(self, *args, **kwargs):
77
+ # it's the first call, replace the method with a cached, bound method
78
+ bound_method = types.MethodType(method, self)
79
+ cached_method = cache_wrapper(bound_method)
80
+ setattr(self, method.__name__, cached_method)
81
+ return cached_method(*args, **kwargs)
82
+
83
+ # Support cache clear even before cache has been created.
84
+ wrapper.cache_clear = lambda: None
85
+
86
+ return wrapper
87
+
88
+
89
+ # From jaraco.functools 3.3
90
+ def pass_none(func):
91
+ """
92
+ Wrap func so it's not called if its first param is None
93
+
94
+ >>> print_text = pass_none(print)
95
+ >>> print_text('text')
96
+ text
97
+ >>> print_text(None)
98
+ """
99
+
100
+ @functools.wraps(func)
101
+ def wrapper(param, *args, **kwargs):
102
+ if param is not None:
103
+ return func(param, *args, **kwargs)
104
+
105
+ return wrapper
106
+
107
+
108
+ # From jaraco.functools 4.4
109
+ def noop(*args, **kwargs):
110
+ """
111
+ A no-operation function that does nothing.
112
+
113
+ >>> noop(1, 2, three=3)
114
+ """
115
+
116
+
117
+ _T = TypeVar('_T')
118
+
119
+
120
+ # From jaraco.functools 4.4
121
+ def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]:
122
+ """
123
+ Wrap the function to always return the first parameter.
124
+
125
+ >>> passthrough(print)('3')
126
+ 3
127
+ '3'
128
+ """
129
+
130
+ @functools.wraps(func)
131
+ def wrapper(first: _T, *args, **kwargs) -> _T:
132
+ func(first, *args, **kwargs)
133
+ return first
134
+
135
+ return wrapper # type: ignore[return-value]
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_itertools.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict, deque
2
+ from itertools import filterfalse
3
+
4
+
5
+ def unique_everseen(iterable, key=None):
6
+ "List unique elements, preserving order. Remember all elements ever seen."
7
+ # unique_everseen('AAAABBBCCDAABBB') --> A B C D
8
+ # unique_everseen('ABBCcAD', str.lower) --> A B C D
9
+ seen = set()
10
+ seen_add = seen.add
11
+ if key is None:
12
+ for element in filterfalse(seen.__contains__, iterable):
13
+ seen_add(element)
14
+ yield element
15
+ else:
16
+ for element in iterable:
17
+ k = key(element)
18
+ if k not in seen:
19
+ seen_add(k)
20
+ yield element
21
+
22
+
23
+ # copied from more_itertools 8.8
24
+ def always_iterable(obj, base_type=(str, bytes)):
25
+ """If *obj* is iterable, return an iterator over its items::
26
+
27
+ >>> obj = (1, 2, 3)
28
+ >>> list(always_iterable(obj))
29
+ [1, 2, 3]
30
+
31
+ If *obj* is not iterable, return a one-item iterable containing *obj*::
32
+
33
+ >>> obj = 1
34
+ >>> list(always_iterable(obj))
35
+ [1]
36
+
37
+ If *obj* is ``None``, return an empty iterable:
38
+
39
+ >>> obj = None
40
+ >>> list(always_iterable(None))
41
+ []
42
+
43
+ By default, binary and text strings are not considered iterable::
44
+
45
+ >>> obj = 'foo'
46
+ >>> list(always_iterable(obj))
47
+ ['foo']
48
+
49
+ If *base_type* is set, objects for which ``isinstance(obj, base_type)``
50
+ returns ``True`` won't be considered iterable.
51
+
52
+ >>> obj = {'a': 1}
53
+ >>> list(always_iterable(obj)) # Iterate over the dict's keys
54
+ ['a']
55
+ >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit
56
+ [{'a': 1}]
57
+
58
+ Set *base_type* to ``None`` to avoid any special handling and treat objects
59
+ Python considers iterable as iterable:
60
+
61
+ >>> obj = 'foo'
62
+ >>> list(always_iterable(obj, base_type=None))
63
+ ['f', 'o', 'o']
64
+ """
65
+ if obj is None:
66
+ return iter(())
67
+
68
+ if (base_type is not None) and isinstance(obj, base_type):
69
+ return iter((obj,))
70
+
71
+ try:
72
+ return iter(obj)
73
+ except TypeError:
74
+ return iter((obj,))
75
+
76
+
77
+ # Copied from more_itertools 10.3
78
+ class bucket:
79
+ """Wrap *iterable* and return an object that buckets the iterable into
80
+ child iterables based on a *key* function.
81
+
82
+ >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3']
83
+ >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character
84
+ >>> sorted(list(s)) # Get the keys
85
+ ['a', 'b', 'c']
86
+ >>> a_iterable = s['a']
87
+ >>> next(a_iterable)
88
+ 'a1'
89
+ >>> next(a_iterable)
90
+ 'a2'
91
+ >>> list(s['b'])
92
+ ['b1', 'b2', 'b3']
93
+
94
+ The original iterable will be advanced and its items will be cached until
95
+ they are used by the child iterables. This may require significant storage.
96
+
97
+ By default, attempting to select a bucket to which no items belong will
98
+ exhaust the iterable and cache all values.
99
+ If you specify a *validator* function, selected buckets will instead be
100
+ checked against it.
101
+
102
+ >>> from itertools import count
103
+ >>> it = count(1, 2) # Infinite sequence of odd numbers
104
+ >>> key = lambda x: x % 10 # Bucket by last digit
105
+ >>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only
106
+ >>> s = bucket(it, key=key, validator=validator)
107
+ >>> 2 in s
108
+ False
109
+ >>> list(s[2])
110
+ []
111
+
112
+ """
113
+
114
+ def __init__(self, iterable, key, validator=None):
115
+ self._it = iter(iterable)
116
+ self._key = key
117
+ self._cache = defaultdict(deque)
118
+ self._validator = validator or (lambda x: True)
119
+
120
+ def __contains__(self, value):
121
+ if not self._validator(value):
122
+ return False
123
+
124
+ try:
125
+ item = next(self[value])
126
+ except StopIteration:
127
+ return False
128
+ else:
129
+ self._cache[value].appendleft(item)
130
+
131
+ return True
132
+
133
+ def _get_values(self, value):
134
+ """
135
+ Helper to yield items from the parent iterator that match *value*.
136
+ Items that don't match are stored in the local cache as they
137
+ are encountered.
138
+ """
139
+ while True:
140
+ # If we've cached some items that match the target value, emit
141
+ # the first one and evict it from the cache.
142
+ if self._cache[value]:
143
+ yield self._cache[value].popleft()
144
+ # Otherwise we need to advance the parent iterator to search for
145
+ # a matching item, caching the rest.
146
+ else:
147
+ while True:
148
+ try:
149
+ item = next(self._it)
150
+ except StopIteration:
151
+ return
152
+ item_value = self._key(item)
153
+ if item_value == value:
154
+ yield item
155
+ break
156
+ elif self._validator(item_value):
157
+ self._cache[item_value].append(item)
158
+
159
+ def __iter__(self):
160
+ for item in self._it:
161
+ item_value = self._key(item)
162
+ if self._validator(item_value):
163
+ self._cache[item_value].append(item)
164
+
165
+ yield from self._cache.keys()
166
+
167
+ def __getitem__(self, value):
168
+ if not self._validator(value):
169
+ return iter(())
170
+
171
+ return self._get_values(value)
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_meta.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from collections.abc import Iterator
5
+ from typing import (
6
+ Any,
7
+ Protocol,
8
+ TypeVar,
9
+ overload,
10
+ )
11
+
12
+ _T = TypeVar("_T")
13
+
14
+
15
+ class PackageMetadata(Protocol):
16
+ def __len__(self) -> int: ... # pragma: no cover
17
+
18
+ def __contains__(self, item: str) -> bool: ... # pragma: no cover
19
+
20
+ def __getitem__(self, key: str) -> str: ... # pragma: no cover
21
+
22
+ def __iter__(self) -> Iterator[str]: ... # pragma: no cover
23
+
24
+ @overload
25
+ def get(
26
+ self, name: str, failobj: None = None
27
+ ) -> str | None: ... # pragma: no cover
28
+
29
+ @overload
30
+ def get(self, name: str, failobj: _T) -> str | _T: ... # pragma: no cover
31
+
32
+ # overload per python/importlib_metadata#435
33
+ @overload
34
+ def get_all(
35
+ self, name: str, failobj: None = None
36
+ ) -> list[Any] | None: ... # pragma: no cover
37
+
38
+ @overload
39
+ def get_all(self, name: str, failobj: _T) -> list[Any] | _T:
40
+ """
41
+ Return all values associated with a possibly multi-valued key.
42
+ """
43
+
44
+ @property
45
+ def json(self) -> dict[str, str | list[str]]:
46
+ """
47
+ A JSON-compatible form of the metadata.
48
+ """
49
+
50
+
51
+ class SimplePath(Protocol):
52
+ """
53
+ A minimal subset of pathlib.Path required by Distribution.
54
+ """
55
+
56
+ def joinpath(
57
+ self, other: str | os.PathLike[str]
58
+ ) -> SimplePath: ... # pragma: no cover
59
+
60
+ def __truediv__(
61
+ self, other: str | os.PathLike[str]
62
+ ) -> SimplePath: ... # pragma: no cover
63
+
64
+ @property
65
+ def parent(self) -> SimplePath: ... # pragma: no cover
66
+
67
+ def read_text(self, encoding=None) -> str: ... # pragma: no cover
68
+
69
+ def read_bytes(self) -> bytes: ... # pragma: no cover
70
+
71
+ def exists(self) -> bool: ... # pragma: no cover
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_text.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ from ._functools import method_cache
4
+
5
+
6
+ # from jaraco.text 3.5
7
+ class FoldedCase(str):
8
+ """
9
+ A case insensitive string class; behaves just like str
10
+ except compares equal when the only variation is case.
11
+
12
+ >>> s = FoldedCase('hello world')
13
+
14
+ >>> s == 'Hello World'
15
+ True
16
+
17
+ >>> 'Hello World' == s
18
+ True
19
+
20
+ >>> s != 'Hello World'
21
+ False
22
+
23
+ >>> s.index('O')
24
+ 4
25
+
26
+ >>> s.split('O')
27
+ ['hell', ' w', 'rld']
28
+
29
+ >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta']))
30
+ ['alpha', 'Beta', 'GAMMA']
31
+
32
+ Sequence membership is straightforward.
33
+
34
+ >>> "Hello World" in [s]
35
+ True
36
+ >>> s in ["Hello World"]
37
+ True
38
+
39
+ You may test for set inclusion, but candidate and elements
40
+ must both be folded.
41
+
42
+ >>> FoldedCase("Hello World") in {s}
43
+ True
44
+ >>> s in {FoldedCase("Hello World")}
45
+ True
46
+
47
+ String inclusion works as long as the FoldedCase object
48
+ is on the right.
49
+
50
+ >>> "hello" in FoldedCase("Hello World")
51
+ True
52
+
53
+ But not if the FoldedCase object is on the left:
54
+
55
+ >>> FoldedCase('hello') in 'Hello World'
56
+ False
57
+
58
+ In that case, use in_:
59
+
60
+ >>> FoldedCase('hello').in_('Hello World')
61
+ True
62
+
63
+ >>> FoldedCase('hello') > FoldedCase('Hello')
64
+ False
65
+ """
66
+
67
+ def __lt__(self, other):
68
+ return self.lower() < other.lower()
69
+
70
+ def __gt__(self, other):
71
+ return self.lower() > other.lower()
72
+
73
+ def __eq__(self, other):
74
+ return self.lower() == other.lower()
75
+
76
+ def __ne__(self, other):
77
+ return self.lower() != other.lower()
78
+
79
+ def __hash__(self):
80
+ return hash(self.lower())
81
+
82
+ def __contains__(self, other):
83
+ return super().lower().__contains__(other.lower())
84
+
85
+ def in_(self, other):
86
+ "Does self appear in other?"
87
+ return self in FoldedCase(other)
88
+
89
+ # cache lower since it's likely to be called frequently.
90
+ @method_cache
91
+ def lower(self):
92
+ return super().lower()
93
+
94
+ def index(self, sub):
95
+ return self.lower().index(sub.lower())
96
+
97
+ def split(self, splitter=' ', maxsplit=0):
98
+ pattern = re.compile(re.escape(splitter), re.I)
99
+ return pattern.split(self, maxsplit)
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/_typing.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import typing
3
+
4
+ from ._meta import PackageMetadata
5
+
6
+ md_none = functools.partial(typing.cast, PackageMetadata)
7
+ """
8
+ Suppress type errors for optional metadata.
9
+
10
+ Although Distribution.metadata can return None when metadata is corrupt
11
+ and thus None, allow callers to assume it's not None and crash if
12
+ that's the case.
13
+
14
+ # python/importlib_metadata#493
15
+ """
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/__init__.py ADDED
File without changes
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (202 Bytes). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/__pycache__/py311.cpython-312.pyc ADDED
Binary file (1.27 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/__pycache__/py39.cpython-312.pyc ADDED
Binary file (1.71 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/py311.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pathlib
3
+ import sys
4
+ import types
5
+
6
+
7
+ def wrap(path): # pragma: no cover
8
+ """
9
+ Workaround for https://github.com/python/cpython/issues/84538
10
+ to add backward compatibility for walk_up=True.
11
+ An example affected package is dask-labextension, which uses
12
+ jupyter-packaging to install JupyterLab javascript files outside
13
+ of site-packages.
14
+ """
15
+
16
+ def relative_to(root, *, walk_up=False):
17
+ return pathlib.Path(os.path.relpath(path, root))
18
+
19
+ return types.SimpleNamespace(relative_to=relative_to)
20
+
21
+
22
+ relative_fix = wrap if sys.version_info < (3, 12) else lambda x: x
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/compat/py39.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Compatibility layer with Python 3.8/3.9
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ if TYPE_CHECKING: # pragma: no cover
10
+ # Prevent circular imports on runtime.
11
+ from .. import Distribution, EntryPoint
12
+ else:
13
+ Distribution = EntryPoint = Any
14
+
15
+ from .._typing import md_none
16
+
17
+
18
+ def normalized_name(dist: Distribution) -> str | None:
19
+ """
20
+ Honor name normalization for distributions that don't provide ``_normalized_name``.
21
+ """
22
+ try:
23
+ return dist._normalized_name
24
+ except AttributeError:
25
+ from .. import Prepared # -> delay to prevent circular imports.
26
+
27
+ return Prepared.normalize(
28
+ getattr(dist, "name", None) or md_none(dist.metadata)['Name']
29
+ )
30
+
31
+
32
+ def ep_matches(ep: EntryPoint, **params) -> bool:
33
+ """
34
+ Workaround for ``EntryPoint`` objects without the ``matches`` method.
35
+ """
36
+ try:
37
+ return ep.matches(**params)
38
+ except AttributeError:
39
+ from .. import EntryPoint # -> delay to prevent circular imports.
40
+
41
+ # Reconstruct the EntryPoint object to make sure it is compatible.
42
+ return EntryPoint(ep.name, ep.value, ep.group).matches(**params)
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/diagnose.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ from . import Distribution
4
+
5
+
6
+ def inspect(path):
7
+ print("Inspecting", path)
8
+ dists = list(Distribution.discover(path=[path]))
9
+ if not dists:
10
+ return
11
+ print("Found", len(dists), "packages:", end=' ')
12
+ print(', '.join(dist.name for dist in dists))
13
+
14
+
15
+ def run():
16
+ for path in sys.path:
17
+ inspect(path)
18
+
19
+
20
+ if __name__ == '__main__':
21
+ run()
loan-advisor-agent/.venv/Lib/site-packages/importlib_metadata/py.typed ADDED
File without changes