metaflow 2.15.4__py2.py3-none-any.whl → 2.15.6__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. metaflow/_vendor/typeguard/_checkers.py +259 -95
  2. metaflow/_vendor/typeguard/_config.py +4 -4
  3. metaflow/_vendor/typeguard/_decorators.py +8 -12
  4. metaflow/_vendor/typeguard/_functions.py +33 -32
  5. metaflow/_vendor/typeguard/_pytest_plugin.py +40 -13
  6. metaflow/_vendor/typeguard/_suppression.py +3 -5
  7. metaflow/_vendor/typeguard/_transformer.py +84 -48
  8. metaflow/_vendor/typeguard/_union_transformer.py +1 -0
  9. metaflow/_vendor/typeguard/_utils.py +13 -9
  10. metaflow/_vendor/typing_extensions.py +1088 -500
  11. metaflow/_vendor/v3_7/__init__.py +1 -0
  12. metaflow/_vendor/v3_7/importlib_metadata/__init__.py +1063 -0
  13. metaflow/_vendor/v3_7/importlib_metadata/_adapters.py +68 -0
  14. metaflow/_vendor/v3_7/importlib_metadata/_collections.py +30 -0
  15. metaflow/_vendor/v3_7/importlib_metadata/_compat.py +71 -0
  16. metaflow/_vendor/v3_7/importlib_metadata/_functools.py +104 -0
  17. metaflow/_vendor/v3_7/importlib_metadata/_itertools.py +73 -0
  18. metaflow/_vendor/v3_7/importlib_metadata/_meta.py +48 -0
  19. metaflow/_vendor/v3_7/importlib_metadata/_text.py +99 -0
  20. metaflow/_vendor/v3_7/importlib_metadata/py.typed +0 -0
  21. metaflow/_vendor/v3_7/typeguard/__init__.py +48 -0
  22. metaflow/_vendor/v3_7/typeguard/_checkers.py +906 -0
  23. metaflow/_vendor/v3_7/typeguard/_config.py +108 -0
  24. metaflow/_vendor/v3_7/typeguard/_decorators.py +237 -0
  25. metaflow/_vendor/v3_7/typeguard/_exceptions.py +42 -0
  26. metaflow/_vendor/v3_7/typeguard/_functions.py +310 -0
  27. metaflow/_vendor/v3_7/typeguard/_importhook.py +213 -0
  28. metaflow/_vendor/v3_7/typeguard/_memo.py +48 -0
  29. metaflow/_vendor/v3_7/typeguard/_pytest_plugin.py +100 -0
  30. metaflow/_vendor/v3_7/typeguard/_suppression.py +88 -0
  31. metaflow/_vendor/v3_7/typeguard/_transformer.py +1207 -0
  32. metaflow/_vendor/v3_7/typeguard/_union_transformer.py +54 -0
  33. metaflow/_vendor/v3_7/typeguard/_utils.py +169 -0
  34. metaflow/_vendor/v3_7/typeguard/py.typed +0 -0
  35. metaflow/_vendor/v3_7/typing_extensions.py +3072 -0
  36. metaflow/_vendor/v3_7/zipp.py +329 -0
  37. metaflow/cmd/develop/stubs.py +1 -1
  38. metaflow/extension_support/__init__.py +1 -1
  39. metaflow/plugins/argo/argo_client.py +9 -2
  40. metaflow/plugins/argo/argo_workflows.py +79 -28
  41. metaflow/plugins/argo/argo_workflows_cli.py +16 -25
  42. metaflow/plugins/argo/argo_workflows_deployer_objects.py +5 -2
  43. metaflow/plugins/cards/card_modules/main.js +52 -50
  44. metaflow/plugins/metadata_providers/service.py +16 -7
  45. metaflow/plugins/pypi/utils.py +4 -0
  46. metaflow/runner/click_api.py +7 -2
  47. metaflow/runner/deployer.py +3 -2
  48. metaflow/vendor.py +1 -0
  49. metaflow/version.py +1 -1
  50. {metaflow-2.15.4.data → metaflow-2.15.6.data}/data/share/metaflow/devtools/Tiltfile +4 -4
  51. metaflow-2.15.6.dist-info/METADATA +103 -0
  52. {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/RECORD +58 -32
  53. {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/WHEEL +1 -1
  54. metaflow-2.15.4.dist-info/METADATA +0 -110
  55. {metaflow-2.15.4.data → metaflow-2.15.6.data}/data/share/metaflow/devtools/Makefile +0 -0
  56. {metaflow-2.15.4.data → metaflow-2.15.6.data}/data/share/metaflow/devtools/pick_services.sh +0 -0
  57. {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/LICENSE +0 -0
  58. {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/entry_points.txt +0 -0
  59. {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1063 @@
1
+ import os
2
+ import re
3
+ import abc
4
+ import csv
5
+ import sys
6
+ from metaflow._vendor.v3_7 import zipp
7
+ import email
8
+ import pathlib
9
+ import operator
10
+ import textwrap
11
+ import warnings
12
+ import functools
13
+ import itertools
14
+ import posixpath
15
+ import collections
16
+
17
+ from . import _adapters, _meta
18
+ from ._collections import FreezableDefaultDict, Pair
19
+ from ._compat import (
20
+ NullFinder,
21
+ install,
22
+ pypy_partial,
23
+ )
24
+ from ._functools import method_cache, pass_none
25
+ from ._itertools import always_iterable, unique_everseen
26
+ from ._meta import PackageMetadata, SimplePath
27
+
28
+ from contextlib import suppress
29
+ from importlib import import_module
30
+ from importlib.abc import MetaPathFinder
31
+ from itertools import starmap
32
+ from typing import List, Mapping, Optional, Union
33
+
34
+
35
+ __all__ = [
36
+ 'Distribution',
37
+ 'DistributionFinder',
38
+ 'PackageMetadata',
39
+ 'PackageNotFoundError',
40
+ 'distribution',
41
+ 'distributions',
42
+ 'entry_points',
43
+ 'files',
44
+ 'metadata',
45
+ 'packages_distributions',
46
+ 'requires',
47
+ 'version',
48
+ ]
49
+
50
+
51
+ class PackageNotFoundError(ModuleNotFoundError):
52
+ """The package was not found."""
53
+
54
+ def __str__(self):
55
+ return f"No package metadata was found for {self.name}"
56
+
57
+ @property
58
+ def name(self):
59
+ (name,) = self.args
60
+ return name
61
+
62
+
63
+ class Sectioned:
64
+ """
65
+ A simple entry point config parser for performance
66
+
67
+ >>> for item in Sectioned.read(Sectioned._sample):
68
+ ... print(item)
69
+ Pair(name='sec1', value='# comments ignored')
70
+ Pair(name='sec1', value='a = 1')
71
+ Pair(name='sec1', value='b = 2')
72
+ Pair(name='sec2', value='a = 2')
73
+
74
+ >>> res = Sectioned.section_pairs(Sectioned._sample)
75
+ >>> item = next(res)
76
+ >>> item.name
77
+ 'sec1'
78
+ >>> item.value
79
+ Pair(name='a', value='1')
80
+ >>> item = next(res)
81
+ >>> item.value
82
+ Pair(name='b', value='2')
83
+ >>> item = next(res)
84
+ >>> item.name
85
+ 'sec2'
86
+ >>> item.value
87
+ Pair(name='a', value='2')
88
+ >>> list(res)
89
+ []
90
+ """
91
+
92
+ _sample = textwrap.dedent(
93
+ """
94
+ [sec1]
95
+ # comments ignored
96
+ a = 1
97
+ b = 2
98
+
99
+ [sec2]
100
+ a = 2
101
+ """
102
+ ).lstrip()
103
+
104
+ @classmethod
105
+ def section_pairs(cls, text):
106
+ return (
107
+ section._replace(value=Pair.parse(section.value))
108
+ for section in cls.read(text, filter_=cls.valid)
109
+ if section.name is not None
110
+ )
111
+
112
+ @staticmethod
113
+ def read(text, filter_=None):
114
+ lines = filter(filter_, map(str.strip, text.splitlines()))
115
+ name = None
116
+ for value in lines:
117
+ section_match = value.startswith('[') and value.endswith(']')
118
+ if section_match:
119
+ name = value.strip('[]')
120
+ continue
121
+ yield Pair(name, value)
122
+
123
+ @staticmethod
124
+ def valid(line):
125
+ return line and not line.startswith('#')
126
+
127
+
128
+ class DeprecatedTuple:
129
+ """
130
+ Provide subscript item access for backward compatibility.
131
+
132
+ >>> recwarn = getfixture('recwarn')
133
+ >>> ep = EntryPoint(name='name', value='value', group='group')
134
+ >>> ep[:]
135
+ ('name', 'value', 'group')
136
+ >>> ep[0]
137
+ 'name'
138
+ >>> len(recwarn)
139
+ 1
140
+ """
141
+
142
+ _warn = functools.partial(
143
+ warnings.warn,
144
+ "EntryPoint tuple interface is deprecated. Access members by name.",
145
+ DeprecationWarning,
146
+ stacklevel=pypy_partial(2),
147
+ )
148
+
149
+ def __getitem__(self, item):
150
+ self._warn()
151
+ return self._key()[item]
152
+
153
+
154
+ class EntryPoint(DeprecatedTuple):
155
+ """An entry point as defined by Python packaging conventions.
156
+
157
+ See `the packaging docs on entry points
158
+ <https://packaging.python.org/specifications/entry-points/>`_
159
+ for more information.
160
+ """
161
+
162
+ pattern = re.compile(
163
+ r'(?P<module>[\w.]+)\s*'
164
+ r'(:\s*(?P<attr>[\w.]+))?\s*'
165
+ r'(?P<extras>\[.*\])?\s*$'
166
+ )
167
+ """
168
+ A regular expression describing the syntax for an entry point,
169
+ which might look like:
170
+
171
+ - module
172
+ - package.module
173
+ - package.module:attribute
174
+ - package.module:object.attribute
175
+ - package.module:attr [extra1, extra2]
176
+
177
+ Other combinations are possible as well.
178
+
179
+ The expression is lenient about whitespace around the ':',
180
+ following the attr, and following any extras.
181
+ """
182
+
183
+ dist: Optional['Distribution'] = None
184
+
185
+ def __init__(self, name, value, group):
186
+ vars(self).update(name=name, value=value, group=group)
187
+
188
+ def load(self):
189
+ """Load the entry point from its definition. If only a module
190
+ is indicated by the value, return that module. Otherwise,
191
+ return the named object.
192
+ """
193
+ match = self.pattern.match(self.value)
194
+ module = import_module(match.group('module'))
195
+ attrs = filter(None, (match.group('attr') or '').split('.'))
196
+ return functools.reduce(getattr, attrs, module)
197
+
198
+ @property
199
+ def module(self):
200
+ match = self.pattern.match(self.value)
201
+ return match.group('module')
202
+
203
+ @property
204
+ def attr(self):
205
+ match = self.pattern.match(self.value)
206
+ return match.group('attr')
207
+
208
+ @property
209
+ def extras(self):
210
+ match = self.pattern.match(self.value)
211
+ return list(re.finditer(r'\w+', match.group('extras') or ''))
212
+
213
+ def _for(self, dist):
214
+ vars(self).update(dist=dist)
215
+ return self
216
+
217
+ def __iter__(self):
218
+ """
219
+ Supply iter so one may construct dicts of EntryPoints by name.
220
+ """
221
+ msg = (
222
+ "Construction of dict of EntryPoints is deprecated in "
223
+ "favor of EntryPoints."
224
+ )
225
+ warnings.warn(msg, DeprecationWarning)
226
+ return iter((self.name, self))
227
+
228
+ def matches(self, **params):
229
+ attrs = (getattr(self, param) for param in params)
230
+ return all(map(operator.eq, params.values(), attrs))
231
+
232
+ def _key(self):
233
+ return self.name, self.value, self.group
234
+
235
+ def __lt__(self, other):
236
+ return self._key() < other._key()
237
+
238
+ def __eq__(self, other):
239
+ return self._key() == other._key()
240
+
241
+ def __setattr__(self, name, value):
242
+ raise AttributeError("EntryPoint objects are immutable.")
243
+
244
+ def __repr__(self):
245
+ return (
246
+ f'EntryPoint(name={self.name!r}, value={self.value!r}, '
247
+ f'group={self.group!r})'
248
+ )
249
+
250
+ def __hash__(self):
251
+ return hash(self._key())
252
+
253
+
254
+ class DeprecatedList(list):
255
+ """
256
+ Allow an otherwise immutable object to implement mutability
257
+ for compatibility.
258
+
259
+ >>> recwarn = getfixture('recwarn')
260
+ >>> dl = DeprecatedList(range(3))
261
+ >>> dl[0] = 1
262
+ >>> dl.append(3)
263
+ >>> del dl[3]
264
+ >>> dl.reverse()
265
+ >>> dl.sort()
266
+ >>> dl.extend([4])
267
+ >>> dl.pop(-1)
268
+ 4
269
+ >>> dl.remove(1)
270
+ >>> dl += [5]
271
+ >>> dl + [6]
272
+ [1, 2, 5, 6]
273
+ >>> dl + (6,)
274
+ [1, 2, 5, 6]
275
+ >>> dl.insert(0, 0)
276
+ >>> dl
277
+ [0, 1, 2, 5]
278
+ >>> dl == [0, 1, 2, 5]
279
+ True
280
+ >>> dl == (0, 1, 2, 5)
281
+ True
282
+ >>> len(recwarn)
283
+ 1
284
+ """
285
+
286
+ _warn = functools.partial(
287
+ warnings.warn,
288
+ "EntryPoints list interface is deprecated. Cast to list if needed.",
289
+ DeprecationWarning,
290
+ stacklevel=pypy_partial(2),
291
+ )
292
+
293
+ def _wrap_deprecated_method(method_name: str): # type: ignore
294
+ def wrapped(self, *args, **kwargs):
295
+ self._warn()
296
+ return getattr(super(), method_name)(*args, **kwargs)
297
+
298
+ return wrapped
299
+
300
+ for method_name in [
301
+ '__setitem__',
302
+ '__delitem__',
303
+ 'append',
304
+ 'reverse',
305
+ 'extend',
306
+ 'pop',
307
+ 'remove',
308
+ '__iadd__',
309
+ 'insert',
310
+ 'sort',
311
+ ]:
312
+ locals()[method_name] = _wrap_deprecated_method(method_name)
313
+
314
+ def __add__(self, other):
315
+ if not isinstance(other, tuple):
316
+ self._warn()
317
+ other = tuple(other)
318
+ return self.__class__(tuple(self) + other)
319
+
320
+ def __eq__(self, other):
321
+ if not isinstance(other, tuple):
322
+ self._warn()
323
+ other = tuple(other)
324
+
325
+ return tuple(self).__eq__(other)
326
+
327
+
328
+ class EntryPoints(DeprecatedList):
329
+ """
330
+ An immutable collection of selectable EntryPoint objects.
331
+ """
332
+
333
+ __slots__ = ()
334
+
335
+ def __getitem__(self, name): # -> EntryPoint:
336
+ """
337
+ Get the EntryPoint in self matching name.
338
+ """
339
+ if isinstance(name, int):
340
+ warnings.warn(
341
+ "Accessing entry points by index is deprecated. "
342
+ "Cast to tuple if needed.",
343
+ DeprecationWarning,
344
+ stacklevel=2,
345
+ )
346
+ return super().__getitem__(name)
347
+ try:
348
+ return next(iter(self.select(name=name)))
349
+ except StopIteration:
350
+ raise KeyError(name)
351
+
352
+ def select(self, **params):
353
+ """
354
+ Select entry points from self that match the
355
+ given parameters (typically group and/or name).
356
+ """
357
+ return EntryPoints(ep for ep in self if ep.matches(**params))
358
+
359
+ @property
360
+ def names(self):
361
+ """
362
+ Return the set of all names of all entry points.
363
+ """
364
+ return {ep.name for ep in self}
365
+
366
+ @property
367
+ def groups(self):
368
+ """
369
+ Return the set of all groups of all entry points.
370
+
371
+ For coverage while SelectableGroups is present.
372
+ >>> EntryPoints().groups
373
+ set()
374
+ """
375
+ return {ep.group for ep in self}
376
+
377
+ @classmethod
378
+ def _from_text_for(cls, text, dist):
379
+ return cls(ep._for(dist) for ep in cls._from_text(text))
380
+
381
+ @staticmethod
382
+ def _from_text(text):
383
+ return (
384
+ EntryPoint(name=item.value.name, value=item.value.value, group=item.name)
385
+ for item in Sectioned.section_pairs(text or '')
386
+ )
387
+
388
+
389
+ class Deprecated:
390
+ """
391
+ Compatibility add-in for mapping to indicate that
392
+ mapping behavior is deprecated.
393
+
394
+ >>> recwarn = getfixture('recwarn')
395
+ >>> class DeprecatedDict(Deprecated, dict): pass
396
+ >>> dd = DeprecatedDict(foo='bar')
397
+ >>> dd.get('baz', None)
398
+ >>> dd['foo']
399
+ 'bar'
400
+ >>> list(dd)
401
+ ['foo']
402
+ >>> list(dd.keys())
403
+ ['foo']
404
+ >>> 'foo' in dd
405
+ True
406
+ >>> list(dd.values())
407
+ ['bar']
408
+ >>> len(recwarn)
409
+ 1
410
+ """
411
+
412
+ _warn = functools.partial(
413
+ warnings.warn,
414
+ "SelectableGroups dict interface is deprecated. Use select.",
415
+ DeprecationWarning,
416
+ stacklevel=pypy_partial(2),
417
+ )
418
+
419
+ def __getitem__(self, name):
420
+ self._warn()
421
+ return super().__getitem__(name)
422
+
423
+ def get(self, name, default=None):
424
+ self._warn()
425
+ return super().get(name, default)
426
+
427
+ def __iter__(self):
428
+ self._warn()
429
+ return super().__iter__()
430
+
431
+ def __contains__(self, *args):
432
+ self._warn()
433
+ return super().__contains__(*args)
434
+
435
+ def keys(self):
436
+ self._warn()
437
+ return super().keys()
438
+
439
+ def values(self):
440
+ self._warn()
441
+ return super().values()
442
+
443
+
444
+ class SelectableGroups(Deprecated, dict):
445
+ """
446
+ A backward- and forward-compatible result from
447
+ entry_points that fully implements the dict interface.
448
+ """
449
+
450
+ @classmethod
451
+ def load(cls, eps):
452
+ by_group = operator.attrgetter('group')
453
+ ordered = sorted(eps, key=by_group)
454
+ grouped = itertools.groupby(ordered, by_group)
455
+ return cls((group, EntryPoints(eps)) for group, eps in grouped)
456
+
457
+ @property
458
+ def _all(self):
459
+ """
460
+ Reconstruct a list of all entrypoints from the groups.
461
+ """
462
+ groups = super(Deprecated, self).values()
463
+ return EntryPoints(itertools.chain.from_iterable(groups))
464
+
465
+ @property
466
+ def groups(self):
467
+ return self._all.groups
468
+
469
+ @property
470
+ def names(self):
471
+ """
472
+ for coverage:
473
+ >>> SelectableGroups().names
474
+ set()
475
+ """
476
+ return self._all.names
477
+
478
+ def select(self, **params):
479
+ if not params:
480
+ return self
481
+ return self._all.select(**params)
482
+
483
+
484
+ class PackagePath(pathlib.PurePosixPath):
485
+ """A reference to a path in a package"""
486
+
487
+ def read_text(self, encoding='utf-8'):
488
+ with self.locate().open(encoding=encoding) as stream:
489
+ return stream.read()
490
+
491
+ def read_binary(self):
492
+ with self.locate().open('rb') as stream:
493
+ return stream.read()
494
+
495
+ def locate(self):
496
+ """Return a path-like object for this path"""
497
+ return self.dist.locate_file(self)
498
+
499
+
500
+ class FileHash:
501
+ def __init__(self, spec):
502
+ self.mode, _, self.value = spec.partition('=')
503
+
504
+ def __repr__(self):
505
+ return f'<FileHash mode: {self.mode} value: {self.value}>'
506
+
507
+
508
+ class Distribution:
509
+ """A Python distribution package."""
510
+
511
+ @abc.abstractmethod
512
+ def read_text(self, filename):
513
+ """Attempt to load metadata file given by the name.
514
+
515
+ :param filename: The name of the file in the distribution info.
516
+ :return: The text if found, otherwise None.
517
+ """
518
+
519
+ @abc.abstractmethod
520
+ def locate_file(self, path):
521
+ """
522
+ Given a path to a file in this distribution, return a path
523
+ to it.
524
+ """
525
+
526
+ @classmethod
527
+ def from_name(cls, name):
528
+ """Return the Distribution for the given package name.
529
+
530
+ :param name: The name of the distribution package to search for.
531
+ :return: The Distribution instance (or subclass thereof) for the named
532
+ package, if found.
533
+ :raises PackageNotFoundError: When the named package's distribution
534
+ metadata cannot be found.
535
+ """
536
+ for resolver in cls._discover_resolvers():
537
+ dists = resolver(DistributionFinder.Context(name=name))
538
+ dist = next(iter(dists), None)
539
+ if dist is not None:
540
+ return dist
541
+ else:
542
+ raise PackageNotFoundError(name)
543
+
544
+ @classmethod
545
+ def discover(cls, **kwargs):
546
+ """Return an iterable of Distribution objects for all packages.
547
+
548
+ Pass a ``context`` or pass keyword arguments for constructing
549
+ a context.
550
+
551
+ :context: A ``DistributionFinder.Context`` object.
552
+ :return: Iterable of Distribution objects for all packages.
553
+ """
554
+ context = kwargs.pop('context', None)
555
+ if context and kwargs:
556
+ raise ValueError("cannot accept context and kwargs")
557
+ context = context or DistributionFinder.Context(**kwargs)
558
+ return itertools.chain.from_iterable(
559
+ resolver(context) for resolver in cls._discover_resolvers()
560
+ )
561
+
562
+ @staticmethod
563
+ def at(path):
564
+ """Return a Distribution for the indicated metadata path
565
+
566
+ :param path: a string or path-like object
567
+ :return: a concrete Distribution instance for the path
568
+ """
569
+ return PathDistribution(pathlib.Path(path))
570
+
571
+ @staticmethod
572
+ def _discover_resolvers():
573
+ """Search the meta_path for resolvers."""
574
+ declared = (
575
+ getattr(finder, 'find_distributions', None) for finder in sys.meta_path
576
+ )
577
+ return filter(None, declared)
578
+
579
+ @classmethod
580
+ def _local(cls, root='.'):
581
+ from pep517 import build, meta
582
+
583
+ system = build.compat_system(root)
584
+ builder = functools.partial(
585
+ meta.build,
586
+ source_dir=root,
587
+ system=system,
588
+ )
589
+ return PathDistribution(zipp.Path(meta.build_as_zip(builder)))
590
+
591
+ @property
592
+ def metadata(self) -> _meta.PackageMetadata:
593
+ """Return the parsed metadata for this Distribution.
594
+
595
+ The returned object will have keys that name the various bits of
596
+ metadata. See PEP 566 for details.
597
+ """
598
+ text = (
599
+ self.read_text('METADATA')
600
+ or self.read_text('PKG-INFO')
601
+ # This last clause is here to support old egg-info files. Its
602
+ # effect is to just end up using the PathDistribution's self._path
603
+ # (which points to the egg-info file) attribute unchanged.
604
+ or self.read_text('')
605
+ )
606
+ return _adapters.Message(email.message_from_string(text))
607
+
608
+ @property
609
+ def name(self):
610
+ """Return the 'Name' metadata for the distribution package."""
611
+ return self.metadata['Name']
612
+
613
+ @property
614
+ def _normalized_name(self):
615
+ """Return a normalized version of the name."""
616
+ return Prepared.normalize(self.name)
617
+
618
+ @property
619
+ def version(self):
620
+ """Return the 'Version' metadata for the distribution package."""
621
+ return self.metadata['Version']
622
+
623
+ @property
624
+ def entry_points(self):
625
+ return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self)
626
+
627
+ @property
628
+ def files(self):
629
+ """Files in this distribution.
630
+
631
+ :return: List of PackagePath for this distribution or None
632
+
633
+ Result is `None` if the metadata file that enumerates files
634
+ (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is
635
+ missing.
636
+ Result may be empty if the metadata exists but is empty.
637
+ """
638
+
639
+ def make_file(name, hash=None, size_str=None):
640
+ result = PackagePath(name)
641
+ result.hash = FileHash(hash) if hash else None
642
+ result.size = int(size_str) if size_str else None
643
+ result.dist = self
644
+ return result
645
+
646
+ @pass_none
647
+ def make_files(lines):
648
+ return list(starmap(make_file, csv.reader(lines)))
649
+
650
+ return make_files(self._read_files_distinfo() or self._read_files_egginfo())
651
+
652
+ def _read_files_distinfo(self):
653
+ """
654
+ Read the lines of RECORD
655
+ """
656
+ text = self.read_text('RECORD')
657
+ return text and text.splitlines()
658
+
659
+ def _read_files_egginfo(self):
660
+ """
661
+ SOURCES.txt might contain literal commas, so wrap each line
662
+ in quotes.
663
+ """
664
+ text = self.read_text('SOURCES.txt')
665
+ return text and map('"{}"'.format, text.splitlines())
666
+
667
+ @property
668
+ def requires(self):
669
+ """Generated requirements specified for this Distribution"""
670
+ reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs()
671
+ return reqs and list(reqs)
672
+
673
+ def _read_dist_info_reqs(self):
674
+ return self.metadata.get_all('Requires-Dist')
675
+
676
+ def _read_egg_info_reqs(self):
677
+ source = self.read_text('requires.txt')
678
+ return source and self._deps_from_requires_text(source)
679
+
680
+ @classmethod
681
+ def _deps_from_requires_text(cls, source):
682
+ return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source))
683
+
684
+ @staticmethod
685
+ def _convert_egg_info_reqs_to_simple_reqs(sections):
686
+ """
687
+ Historically, setuptools would solicit and store 'extra'
688
+ requirements, including those with environment markers,
689
+ in separate sections. More modern tools expect each
690
+ dependency to be defined separately, with any relevant
691
+ extras and environment markers attached directly to that
692
+ requirement. This method converts the former to the
693
+ latter. See _test_deps_from_requires_text for an example.
694
+ """
695
+
696
+ def make_condition(name):
697
+ return name and f'extra == "{name}"'
698
+
699
+ def quoted_marker(section):
700
+ section = section or ''
701
+ extra, sep, markers = section.partition(':')
702
+ if extra and markers:
703
+ markers = f'({markers})'
704
+ conditions = list(filter(None, [markers, make_condition(extra)]))
705
+ return '; ' + ' and '.join(conditions) if conditions else ''
706
+
707
+ def url_req_space(req):
708
+ """
709
+ PEP 508 requires a space between the url_spec and the quoted_marker.
710
+ Ref python/importlib_metadata#357.
711
+ """
712
+ # '@' is uniquely indicative of a url_req.
713
+ return ' ' * ('@' in req)
714
+
715
+ for section in sections:
716
+ space = url_req_space(section.value)
717
+ yield section.value + space + quoted_marker(section.name)
718
+
719
+
720
+ class DistributionFinder(MetaPathFinder):
721
+ """
722
+ A MetaPathFinder capable of discovering installed distributions.
723
+ """
724
+
725
+ class Context:
726
+ """
727
+ Keyword arguments presented by the caller to
728
+ ``distributions()`` or ``Distribution.discover()``
729
+ to narrow the scope of a search for distributions
730
+ in all DistributionFinders.
731
+
732
+ Each DistributionFinder may expect any parameters
733
+ and should attempt to honor the canonical
734
+ parameters defined below when appropriate.
735
+ """
736
+
737
+ name = None
738
+ """
739
+ Specific name for which a distribution finder should match.
740
+ A name of ``None`` matches all distributions.
741
+ """
742
+
743
+ def __init__(self, **kwargs):
744
+ vars(self).update(kwargs)
745
+
746
+ @property
747
+ def path(self):
748
+ """
749
+ The sequence of directory path that a distribution finder
750
+ should search.
751
+
752
+ Typically refers to Python installed package paths such as
753
+ "site-packages" directories and defaults to ``sys.path``.
754
+ """
755
+ return vars(self).get('path', sys.path)
756
+
757
+ @abc.abstractmethod
758
+ def find_distributions(self, context=Context()):
759
+ """
760
+ Find distributions.
761
+
762
+ Return an iterable of all Distribution instances capable of
763
+ loading the metadata for packages matching the ``context``,
764
+ a DistributionFinder.Context instance.
765
+ """
766
+
767
+
768
+ class FastPath:
769
+ """
770
+ Micro-optimized class for searching a path for
771
+ children.
772
+
773
+ >>> FastPath('').children()
774
+ ['...']
775
+ """
776
+
777
+ @functools.lru_cache() # type: ignore
778
+ def __new__(cls, root):
779
+ return super().__new__(cls)
780
+
781
+ def __init__(self, root):
782
+ self.root = str(root)
783
+
784
+ def joinpath(self, child):
785
+ return pathlib.Path(self.root, child)
786
+
787
+ def children(self):
788
+ with suppress(Exception):
789
+ return os.listdir(self.root or '.')
790
+ with suppress(Exception):
791
+ return self.zip_children()
792
+ return []
793
+
794
+ def zip_children(self):
795
+ zip_path = zipp.Path(self.root)
796
+ names = zip_path.root.namelist()
797
+ self.joinpath = zip_path.joinpath
798
+
799
+ return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names)
800
+
801
+ def search(self, name):
802
+ return self.lookup(self.mtime).search(name)
803
+
804
+ @property
805
+ def mtime(self):
806
+ with suppress(OSError):
807
+ return os.stat(self.root).st_mtime
808
+ self.lookup.cache_clear()
809
+
810
+ @method_cache
811
+ def lookup(self, mtime):
812
+ return Lookup(self)
813
+
814
+
815
+ class Lookup:
816
+ def __init__(self, path: FastPath):
817
+ base = os.path.basename(path.root).lower()
818
+ base_is_egg = base.endswith(".egg")
819
+ self.infos = FreezableDefaultDict(list)
820
+ self.eggs = FreezableDefaultDict(list)
821
+
822
+ for child in path.children():
823
+ low = child.lower()
824
+ if low.endswith((".dist-info", ".egg-info")):
825
+ # rpartition is faster than splitext and suitable for this purpose.
826
+ name = low.rpartition(".")[0].partition("-")[0]
827
+ normalized = Prepared.normalize(name)
828
+ self.infos[normalized].append(path.joinpath(child))
829
+ elif base_is_egg and low == "egg-info":
830
+ name = base.rpartition(".")[0].partition("-")[0]
831
+ legacy_normalized = Prepared.legacy_normalize(name)
832
+ self.eggs[legacy_normalized].append(path.joinpath(child))
833
+
834
+ self.infos.freeze()
835
+ self.eggs.freeze()
836
+
837
+ def search(self, prepared):
838
+ infos = (
839
+ self.infos[prepared.normalized]
840
+ if prepared
841
+ else itertools.chain.from_iterable(self.infos.values())
842
+ )
843
+ eggs = (
844
+ self.eggs[prepared.legacy_normalized]
845
+ if prepared
846
+ else itertools.chain.from_iterable(self.eggs.values())
847
+ )
848
+ return itertools.chain(infos, eggs)
849
+
850
+
851
+ class Prepared:
852
+ """
853
+ A prepared search for metadata on a possibly-named package.
854
+ """
855
+
856
+ normalized = None
857
+ legacy_normalized = None
858
+
859
+ def __init__(self, name):
860
+ self.name = name
861
+ if name is None:
862
+ return
863
+ self.normalized = self.normalize(name)
864
+ self.legacy_normalized = self.legacy_normalize(name)
865
+
866
+ @staticmethod
867
+ def normalize(name):
868
+ """
869
+ PEP 503 normalization plus dashes as underscores.
870
+ """
871
+ return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_')
872
+
873
+ @staticmethod
874
+ def legacy_normalize(name):
875
+ """
876
+ Normalize the package name as found in the convention in
877
+ older packaging tools versions and specs.
878
+ """
879
+ return name.lower().replace('-', '_')
880
+
881
+ def __bool__(self):
882
+ return bool(self.name)
883
+
884
+
885
+ @install
886
+ class MetadataPathFinder(NullFinder, DistributionFinder):
887
+ """A degenerate finder for distribution packages on the file system.
888
+
889
+ This finder supplies only a find_distributions() method for versions
890
+ of Python that do not have a PathFinder find_distributions().
891
+ """
892
+
893
+ def find_distributions(self, context=DistributionFinder.Context()):
894
+ """
895
+ Find distributions.
896
+
897
+ Return an iterable of all Distribution instances capable of
898
+ loading the metadata for packages matching ``context.name``
899
+ (or all names if ``None`` indicated) along the paths in the list
900
+ of directories ``context.path``.
901
+ """
902
+ found = self._search_paths(context.name, context.path)
903
+ return map(PathDistribution, found)
904
+
905
+ @classmethod
906
+ def _search_paths(cls, name, paths):
907
+ """Find metadata directories in paths heuristically."""
908
+ prepared = Prepared(name)
909
+ return itertools.chain.from_iterable(
910
+ path.search(prepared) for path in map(FastPath, paths)
911
+ )
912
+
913
+ def invalidate_caches(cls):
914
+ FastPath.__new__.cache_clear()
915
+
916
+
917
+ class PathDistribution(Distribution):
918
+ def __init__(self, path: SimplePath):
919
+ """Construct a distribution.
920
+
921
+ :param path: SimplePath indicating the metadata directory.
922
+ """
923
+ self._path = path
924
+
925
+ def read_text(self, filename):
926
+ with suppress(
927
+ FileNotFoundError,
928
+ IsADirectoryError,
929
+ KeyError,
930
+ NotADirectoryError,
931
+ PermissionError,
932
+ ):
933
+ return self._path.joinpath(filename).read_text(encoding='utf-8')
934
+
935
+ read_text.__doc__ = Distribution.read_text.__doc__
936
+
937
+ def locate_file(self, path):
938
+ return self._path.parent / path
939
+
940
+ @property
941
+ def _normalized_name(self):
942
+ """
943
+ Performance optimization: where possible, resolve the
944
+ normalized name from the file system path.
945
+ """
946
+ stem = os.path.basename(str(self._path))
947
+ return self._name_from_stem(stem) or super()._normalized_name
948
+
949
+ def _name_from_stem(self, stem):
950
+ name, ext = os.path.splitext(stem)
951
+ if ext not in ('.dist-info', '.egg-info'):
952
+ return
953
+ name, sep, rest = stem.partition('-')
954
+ return name
955
+
956
+
957
+ def distribution(distribution_name):
958
+ """Get the ``Distribution`` instance for the named package.
959
+
960
+ :param distribution_name: The name of the distribution package as a string.
961
+ :return: A ``Distribution`` instance (or subclass thereof).
962
+ """
963
+ return Distribution.from_name(distribution_name)
964
+
965
+
966
+ def distributions(**kwargs):
967
+ """Get all ``Distribution`` instances in the current environment.
968
+
969
+ :return: An iterable of ``Distribution`` instances.
970
+ """
971
+ return Distribution.discover(**kwargs)
972
+
973
+
974
+ def metadata(distribution_name) -> _meta.PackageMetadata:
975
+ """Get the metadata for the named package.
976
+
977
+ :param distribution_name: The name of the distribution package to query.
978
+ :return: A PackageMetadata containing the parsed metadata.
979
+ """
980
+ return Distribution.from_name(distribution_name).metadata
981
+
982
+
983
+ def version(distribution_name):
984
+ """Get the version string for the named package.
985
+
986
+ :param distribution_name: The name of the distribution package to query.
987
+ :return: The version string for the package as defined in the package's
988
+ "Version" metadata key.
989
+ """
990
+ return distribution(distribution_name).version
991
+
992
+
993
+ def entry_points(**params) -> Union[EntryPoints, SelectableGroups]:
994
+ """Return EntryPoint objects for all installed packages.
995
+
996
+ Pass selection parameters (group or name) to filter the
997
+ result to entry points matching those properties (see
998
+ EntryPoints.select()).
999
+
1000
+ For compatibility, returns ``SelectableGroups`` object unless
1001
+ selection parameters are supplied. In the future, this function
1002
+ will return ``EntryPoints`` instead of ``SelectableGroups``
1003
+ even when no selection parameters are supplied.
1004
+
1005
+ For maximum future compatibility, pass selection parameters
1006
+ or invoke ``.select`` with parameters on the result.
1007
+
1008
+ :return: EntryPoints or SelectableGroups for all installed packages.
1009
+ """
1010
+ norm_name = operator.attrgetter('_normalized_name')
1011
+ unique = functools.partial(unique_everseen, key=norm_name)
1012
+ eps = itertools.chain.from_iterable(
1013
+ dist.entry_points for dist in unique(distributions())
1014
+ )
1015
+ return SelectableGroups.load(eps).select(**params)
1016
+
1017
+
1018
+ def files(distribution_name):
1019
+ """Return a list of files for the named package.
1020
+
1021
+ :param distribution_name: The name of the distribution package to query.
1022
+ :return: List of files composing the distribution.
1023
+ """
1024
+ return distribution(distribution_name).files
1025
+
1026
+
1027
+ def requires(distribution_name):
1028
+ """
1029
+ Return a list of requirements for the named package.
1030
+
1031
+ :return: An iterator of requirements, suitable for
1032
+ packaging.requirement.Requirement.
1033
+ """
1034
+ return distribution(distribution_name).requires
1035
+
1036
+
1037
+ def packages_distributions() -> Mapping[str, List[str]]:
1038
+ """
1039
+ Return a mapping of top-level packages to their
1040
+ distributions.
1041
+
1042
+ >>> import collections.abc
1043
+ >>> pkgs = packages_distributions()
1044
+ >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values())
1045
+ True
1046
+ """
1047
+ pkg_to_dist = collections.defaultdict(list)
1048
+ for dist in distributions():
1049
+ for pkg in _top_level_declared(dist) or _top_level_inferred(dist):
1050
+ pkg_to_dist[pkg].append(dist.metadata['Name'])
1051
+ return dict(pkg_to_dist)
1052
+
1053
+
1054
+ def _top_level_declared(dist):
1055
+ return (dist.read_text('top_level.txt') or '').split()
1056
+
1057
+
1058
+ def _top_level_inferred(dist):
1059
+ return {
1060
+ f.parts[0] if len(f.parts) > 1 else f.with_suffix('').name
1061
+ for f in always_iterable(dist.files)
1062
+ if f.suffix == ".py"
1063
+ }