ob-metaflow 2.9.10.1__py2.py3-none-any.whl → 2.10.2.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.

Potentially problematic release.


This version of ob-metaflow might be problematic. Click here for more details.

Files changed (57) hide show
  1. metaflow/_vendor/packaging/__init__.py +15 -0
  2. metaflow/_vendor/packaging/_elffile.py +108 -0
  3. metaflow/_vendor/packaging/_manylinux.py +238 -0
  4. metaflow/_vendor/packaging/_musllinux.py +80 -0
  5. metaflow/_vendor/packaging/_parser.py +328 -0
  6. metaflow/_vendor/packaging/_structures.py +61 -0
  7. metaflow/_vendor/packaging/_tokenizer.py +188 -0
  8. metaflow/_vendor/packaging/markers.py +245 -0
  9. metaflow/_vendor/packaging/requirements.py +95 -0
  10. metaflow/_vendor/packaging/specifiers.py +1005 -0
  11. metaflow/_vendor/packaging/tags.py +546 -0
  12. metaflow/_vendor/packaging/utils.py +141 -0
  13. metaflow/_vendor/packaging/version.py +563 -0
  14. metaflow/_vendor/v3_7/__init__.py +1 -0
  15. metaflow/_vendor/v3_7/zipp.py +329 -0
  16. metaflow/metaflow_config.py +2 -1
  17. metaflow/metaflow_environment.py +3 -1
  18. metaflow/mflog/mflog.py +7 -1
  19. metaflow/multicore_utils.py +12 -2
  20. metaflow/plugins/__init__.py +8 -3
  21. metaflow/plugins/airflow/airflow.py +13 -0
  22. metaflow/plugins/argo/argo_client.py +16 -0
  23. metaflow/plugins/argo/argo_events.py +7 -1
  24. metaflow/plugins/argo/argo_workflows.py +62 -0
  25. metaflow/plugins/argo/argo_workflows_cli.py +15 -0
  26. metaflow/plugins/aws/batch/batch.py +10 -0
  27. metaflow/plugins/aws/batch/batch_cli.py +1 -2
  28. metaflow/plugins/aws/batch/batch_decorator.py +2 -9
  29. metaflow/plugins/datatools/s3/s3.py +4 -0
  30. metaflow/plugins/env_escape/client.py +24 -3
  31. metaflow/plugins/env_escape/stub.py +2 -8
  32. metaflow/plugins/kubernetes/kubernetes.py +13 -0
  33. metaflow/plugins/kubernetes/kubernetes_cli.py +1 -2
  34. metaflow/plugins/kubernetes/kubernetes_decorator.py +9 -2
  35. metaflow/plugins/pypi/__init__.py +29 -0
  36. metaflow/plugins/pypi/bootstrap.py +131 -0
  37. metaflow/plugins/pypi/conda_decorator.py +335 -0
  38. metaflow/plugins/pypi/conda_environment.py +414 -0
  39. metaflow/plugins/pypi/micromamba.py +294 -0
  40. metaflow/plugins/pypi/pip.py +205 -0
  41. metaflow/plugins/pypi/pypi_decorator.py +130 -0
  42. metaflow/plugins/pypi/pypi_environment.py +7 -0
  43. metaflow/plugins/pypi/utils.py +75 -0
  44. metaflow/task.py +0 -3
  45. metaflow/vendor.py +1 -0
  46. {ob_metaflow-2.9.10.1.dist-info → ob_metaflow-2.10.2.6.dist-info}/METADATA +1 -1
  47. {ob_metaflow-2.9.10.1.dist-info → ob_metaflow-2.10.2.6.dist-info}/RECORD +51 -33
  48. {ob_metaflow-2.9.10.1.dist-info → ob_metaflow-2.10.2.6.dist-info}/WHEEL +1 -1
  49. metaflow/plugins/conda/__init__.py +0 -90
  50. metaflow/plugins/conda/batch_bootstrap.py +0 -104
  51. metaflow/plugins/conda/conda.py +0 -247
  52. metaflow/plugins/conda/conda_environment.py +0 -136
  53. metaflow/plugins/conda/conda_flow_decorator.py +0 -35
  54. metaflow/plugins/conda/conda_step_decorator.py +0 -416
  55. {ob_metaflow-2.9.10.1.dist-info → ob_metaflow-2.10.2.6.dist-info}/LICENSE +0 -0
  56. {ob_metaflow-2.9.10.1.dist-info → ob_metaflow-2.10.2.6.dist-info}/entry_points.txt +0 -0
  57. {ob_metaflow-2.9.10.1.dist-info → ob_metaflow-2.10.2.6.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,546 @@
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import logging
6
+ import platform
7
+ import subprocess
8
+ import sys
9
+ import sysconfig
10
+ from importlib.machinery import EXTENSION_SUFFIXES
11
+ from typing import (
12
+ Dict,
13
+ FrozenSet,
14
+ Iterable,
15
+ Iterator,
16
+ List,
17
+ Optional,
18
+ Sequence,
19
+ Tuple,
20
+ Union,
21
+ cast,
22
+ )
23
+
24
+ from . import _manylinux, _musllinux
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ PythonVersion = Sequence[int]
29
+ MacVersion = Tuple[int, int]
30
+
31
+ INTERPRETER_SHORT_NAMES: Dict[str, str] = {
32
+ "python": "py", # Generic.
33
+ "cpython": "cp",
34
+ "pypy": "pp",
35
+ "ironpython": "ip",
36
+ "jython": "jy",
37
+ }
38
+
39
+
40
+ _32_BIT_INTERPRETER = sys.maxsize <= 2**32
41
+
42
+
43
+ class Tag:
44
+ """
45
+ A representation of the tag triple for a wheel.
46
+
47
+ Instances are considered immutable and thus are hashable. Equality checking
48
+ is also supported.
49
+ """
50
+
51
+ __slots__ = ["_interpreter", "_abi", "_platform", "_hash"]
52
+
53
+ def __init__(self, interpreter: str, abi: str, platform: str) -> None:
54
+ self._interpreter = interpreter.lower()
55
+ self._abi = abi.lower()
56
+ self._platform = platform.lower()
57
+ # The __hash__ of every single element in a Set[Tag] will be evaluated each time
58
+ # that a set calls its `.disjoint()` method, which may be called hundreds of
59
+ # times when scanning a page of links for packages with tags matching that
60
+ # Set[Tag]. Pre-computing the value here produces significant speedups for
61
+ # downstream consumers.
62
+ self._hash = hash((self._interpreter, self._abi, self._platform))
63
+
64
+ @property
65
+ def interpreter(self) -> str:
66
+ return self._interpreter
67
+
68
+ @property
69
+ def abi(self) -> str:
70
+ return self._abi
71
+
72
+ @property
73
+ def platform(self) -> str:
74
+ return self._platform
75
+
76
+ def __eq__(self, other: object) -> bool:
77
+ if not isinstance(other, Tag):
78
+ return NotImplemented
79
+
80
+ return (
81
+ (self._hash == other._hash) # Short-circuit ASAP for perf reasons.
82
+ and (self._platform == other._platform)
83
+ and (self._abi == other._abi)
84
+ and (self._interpreter == other._interpreter)
85
+ )
86
+
87
+ def __hash__(self) -> int:
88
+ return self._hash
89
+
90
+ def __str__(self) -> str:
91
+ return f"{self._interpreter}-{self._abi}-{self._platform}"
92
+
93
+ def __repr__(self) -> str:
94
+ return f"<{self} @ {id(self)}>"
95
+
96
+
97
+ def parse_tag(tag: str) -> FrozenSet[Tag]:
98
+ """
99
+ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
100
+
101
+ Returning a set is required due to the possibility that the tag is a
102
+ compressed tag set.
103
+ """
104
+ tags = set()
105
+ interpreters, abis, platforms = tag.split("-")
106
+ for interpreter in interpreters.split("."):
107
+ for abi in abis.split("."):
108
+ for platform_ in platforms.split("."):
109
+ tags.add(Tag(interpreter, abi, platform_))
110
+ return frozenset(tags)
111
+
112
+
113
+ def _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]:
114
+ value = sysconfig.get_config_var(name)
115
+ if value is None and warn:
116
+ logger.debug(
117
+ "Config variable '%s' is unset, Python ABI tag may be incorrect", name
118
+ )
119
+ return value
120
+
121
+
122
+ def _normalize_string(string: str) -> str:
123
+ return string.replace(".", "_").replace("-", "_")
124
+
125
+
126
+ def _abi3_applies(python_version: PythonVersion) -> bool:
127
+ """
128
+ Determine if the Python version supports abi3.
129
+
130
+ PEP 384 was first implemented in Python 3.2.
131
+ """
132
+ return len(python_version) > 1 and tuple(python_version) >= (3, 2)
133
+
134
+
135
+ def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:
136
+ py_version = tuple(py_version) # To allow for version comparison.
137
+ abis = []
138
+ version = _version_nodot(py_version[:2])
139
+ debug = pymalloc = ucs4 = ""
140
+ with_debug = _get_config_var("Py_DEBUG", warn)
141
+ has_refcount = hasattr(sys, "gettotalrefcount")
142
+ # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled
143
+ # extension modules is the best option.
144
+ # https://github.com/pypa/pip/issues/3383#issuecomment-173267692
145
+ has_ext = "_d.pyd" in EXTENSION_SUFFIXES
146
+ if with_debug or (with_debug is None and (has_refcount or has_ext)):
147
+ debug = "d"
148
+ if py_version < (3, 8):
149
+ with_pymalloc = _get_config_var("WITH_PYMALLOC", warn)
150
+ if with_pymalloc or with_pymalloc is None:
151
+ pymalloc = "m"
152
+ if py_version < (3, 3):
153
+ unicode_size = _get_config_var("Py_UNICODE_SIZE", warn)
154
+ if unicode_size == 4 or (
155
+ unicode_size is None and sys.maxunicode == 0x10FFFF
156
+ ):
157
+ ucs4 = "u"
158
+ elif debug:
159
+ # Debug builds can also load "normal" extension modules.
160
+ # We can also assume no UCS-4 or pymalloc requirement.
161
+ abis.append(f"cp{version}")
162
+ abis.insert(
163
+ 0,
164
+ "cp{version}{debug}{pymalloc}{ucs4}".format(
165
+ version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4
166
+ ),
167
+ )
168
+ return abis
169
+
170
+
171
+ def cpython_tags(
172
+ python_version: Optional[PythonVersion] = None,
173
+ abis: Optional[Iterable[str]] = None,
174
+ platforms: Optional[Iterable[str]] = None,
175
+ *,
176
+ warn: bool = False,
177
+ ) -> Iterator[Tag]:
178
+ """
179
+ Yields the tags for a CPython interpreter.
180
+
181
+ The tags consist of:
182
+ - cp<python_version>-<abi>-<platform>
183
+ - cp<python_version>-abi3-<platform>
184
+ - cp<python_version>-none-<platform>
185
+ - cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2.
186
+
187
+ If python_version only specifies a major version then user-provided ABIs and
188
+ the 'none' ABItag will be used.
189
+
190
+ If 'abi3' or 'none' are specified in 'abis' then they will be yielded at
191
+ their normal position and not at the beginning.
192
+ """
193
+ if not python_version:
194
+ python_version = sys.version_info[:2]
195
+
196
+ interpreter = f"cp{_version_nodot(python_version[:2])}"
197
+
198
+ if abis is None:
199
+ if len(python_version) > 1:
200
+ abis = _cpython_abis(python_version, warn)
201
+ else:
202
+ abis = []
203
+ abis = list(abis)
204
+ # 'abi3' and 'none' are explicitly handled later.
205
+ for explicit_abi in ("abi3", "none"):
206
+ try:
207
+ abis.remove(explicit_abi)
208
+ except ValueError:
209
+ pass
210
+
211
+ platforms = list(platforms or platform_tags())
212
+ for abi in abis:
213
+ for platform_ in platforms:
214
+ yield Tag(interpreter, abi, platform_)
215
+ if _abi3_applies(python_version):
216
+ yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms)
217
+ yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
218
+
219
+ if _abi3_applies(python_version):
220
+ for minor_version in range(python_version[1] - 1, 1, -1):
221
+ for platform_ in platforms:
222
+ interpreter = "cp{version}".format(
223
+ version=_version_nodot((python_version[0], minor_version))
224
+ )
225
+ yield Tag(interpreter, "abi3", platform_)
226
+
227
+
228
+ def _generic_abi() -> List[str]:
229
+ """
230
+ Return the ABI tag based on EXT_SUFFIX.
231
+ """
232
+ # The following are examples of `EXT_SUFFIX`.
233
+ # We want to keep the parts which are related to the ABI and remove the
234
+ # parts which are related to the platform:
235
+ # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310
236
+ # - mac: '.cpython-310-darwin.so' => cp310
237
+ # - win: '.cp310-win_amd64.pyd' => cp310
238
+ # - win: '.pyd' => cp37 (uses _cpython_abis())
239
+ # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73
240
+ # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib'
241
+ # => graalpy_38_native
242
+
243
+ ext_suffix = _get_config_var("EXT_SUFFIX", warn=True)
244
+ if not isinstance(ext_suffix, str) or ext_suffix[0] != ".":
245
+ raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')")
246
+ parts = ext_suffix.split(".")
247
+ if len(parts) < 3:
248
+ # CPython3.7 and earlier uses ".pyd" on Windows.
249
+ return _cpython_abis(sys.version_info[:2])
250
+ soabi = parts[1]
251
+ if soabi.startswith("cpython"):
252
+ # non-windows
253
+ abi = "cp" + soabi.split("-")[1]
254
+ elif soabi.startswith("cp"):
255
+ # windows
256
+ abi = soabi.split("-")[0]
257
+ elif soabi.startswith("pypy"):
258
+ abi = "-".join(soabi.split("-")[:2])
259
+ elif soabi.startswith("graalpy"):
260
+ abi = "-".join(soabi.split("-")[:3])
261
+ elif soabi:
262
+ # pyston, ironpython, others?
263
+ abi = soabi
264
+ else:
265
+ return []
266
+ return [_normalize_string(abi)]
267
+
268
+
269
+ def generic_tags(
270
+ interpreter: Optional[str] = None,
271
+ abis: Optional[Iterable[str]] = None,
272
+ platforms: Optional[Iterable[str]] = None,
273
+ *,
274
+ warn: bool = False,
275
+ ) -> Iterator[Tag]:
276
+ """
277
+ Yields the tags for a generic interpreter.
278
+
279
+ The tags consist of:
280
+ - <interpreter>-<abi>-<platform>
281
+
282
+ The "none" ABI will be added if it was not explicitly provided.
283
+ """
284
+ if not interpreter:
285
+ interp_name = interpreter_name()
286
+ interp_version = interpreter_version(warn=warn)
287
+ interpreter = "".join([interp_name, interp_version])
288
+ if abis is None:
289
+ abis = _generic_abi()
290
+ else:
291
+ abis = list(abis)
292
+ platforms = list(platforms or platform_tags())
293
+ if "none" not in abis:
294
+ abis.append("none")
295
+ for abi in abis:
296
+ for platform_ in platforms:
297
+ yield Tag(interpreter, abi, platform_)
298
+
299
+
300
+ def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:
301
+ """
302
+ Yields Python versions in descending order.
303
+
304
+ After the latest version, the major-only version will be yielded, and then
305
+ all previous versions of that major version.
306
+ """
307
+ if len(py_version) > 1:
308
+ yield f"py{_version_nodot(py_version[:2])}"
309
+ yield f"py{py_version[0]}"
310
+ if len(py_version) > 1:
311
+ for minor in range(py_version[1] - 1, -1, -1):
312
+ yield f"py{_version_nodot((py_version[0], minor))}"
313
+
314
+
315
+ def compatible_tags(
316
+ python_version: Optional[PythonVersion] = None,
317
+ interpreter: Optional[str] = None,
318
+ platforms: Optional[Iterable[str]] = None,
319
+ ) -> Iterator[Tag]:
320
+ """
321
+ Yields the sequence of tags that are compatible with a specific version of Python.
322
+
323
+ The tags consist of:
324
+ - py*-none-<platform>
325
+ - <interpreter>-none-any # ... if `interpreter` is provided.
326
+ - py*-none-any
327
+ """
328
+ if not python_version:
329
+ python_version = sys.version_info[:2]
330
+ platforms = list(platforms or platform_tags())
331
+ for version in _py_interpreter_range(python_version):
332
+ for platform_ in platforms:
333
+ yield Tag(version, "none", platform_)
334
+ if interpreter:
335
+ yield Tag(interpreter, "none", "any")
336
+ for version in _py_interpreter_range(python_version):
337
+ yield Tag(version, "none", "any")
338
+
339
+
340
+ def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:
341
+ if not is_32bit:
342
+ return arch
343
+
344
+ if arch.startswith("ppc"):
345
+ return "ppc"
346
+
347
+ return "i386"
348
+
349
+
350
+ def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]:
351
+ formats = [cpu_arch]
352
+ if cpu_arch == "x86_64":
353
+ if version < (10, 4):
354
+ return []
355
+ formats.extend(["intel", "fat64", "fat32"])
356
+
357
+ elif cpu_arch == "i386":
358
+ if version < (10, 4):
359
+ return []
360
+ formats.extend(["intel", "fat32", "fat"])
361
+
362
+ elif cpu_arch == "ppc64":
363
+ # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
364
+ if version > (10, 5) or version < (10, 4):
365
+ return []
366
+ formats.append("fat64")
367
+
368
+ elif cpu_arch == "ppc":
369
+ if version > (10, 6):
370
+ return []
371
+ formats.extend(["fat32", "fat"])
372
+
373
+ if cpu_arch in {"arm64", "x86_64"}:
374
+ formats.append("universal2")
375
+
376
+ if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}:
377
+ formats.append("universal")
378
+
379
+ return formats
380
+
381
+
382
+ def mac_platforms(
383
+ version: Optional[MacVersion] = None, arch: Optional[str] = None
384
+ ) -> Iterator[str]:
385
+ """
386
+ Yields the platform tags for a macOS system.
387
+
388
+ The `version` parameter is a two-item tuple specifying the macOS version to
389
+ generate platform tags for. The `arch` parameter is the CPU architecture to
390
+ generate platform tags for. Both parameters default to the appropriate value
391
+ for the current system.
392
+ """
393
+ version_str, _, cpu_arch = platform.mac_ver()
394
+ if version is None:
395
+ version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
396
+ if version == (10, 16):
397
+ # When built against an older macOS SDK, Python will report macOS 10.16
398
+ # instead of the real version.
399
+ version_str = subprocess.run(
400
+ [
401
+ sys.executable,
402
+ "-sS",
403
+ "-c",
404
+ "import platform; print(platform.mac_ver()[0])",
405
+ ],
406
+ check=True,
407
+ env={"SYSTEM_VERSION_COMPAT": "0"},
408
+ stdout=subprocess.PIPE,
409
+ universal_newlines=True,
410
+ ).stdout
411
+ version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2])))
412
+ else:
413
+ version = version
414
+ if arch is None:
415
+ arch = _mac_arch(cpu_arch)
416
+ else:
417
+ arch = arch
418
+
419
+ if (10, 0) <= version and version < (11, 0):
420
+ # Prior to Mac OS 11, each yearly release of Mac OS bumped the
421
+ # "minor" version number. The major version was always 10.
422
+ for minor_version in range(version[1], -1, -1):
423
+ compat_version = 10, minor_version
424
+ binary_formats = _mac_binary_formats(compat_version, arch)
425
+ for binary_format in binary_formats:
426
+ yield "macosx_{major}_{minor}_{binary_format}".format(
427
+ major=10, minor=minor_version, binary_format=binary_format
428
+ )
429
+
430
+ if version >= (11, 0):
431
+ # Starting with Mac OS 11, each yearly release bumps the major version
432
+ # number. The minor versions are now the midyear updates.
433
+ for major_version in range(version[0], 10, -1):
434
+ compat_version = major_version, 0
435
+ binary_formats = _mac_binary_formats(compat_version, arch)
436
+ for binary_format in binary_formats:
437
+ yield "macosx_{major}_{minor}_{binary_format}".format(
438
+ major=major_version, minor=0, binary_format=binary_format
439
+ )
440
+
441
+ if version >= (11, 0):
442
+ # Mac OS 11 on x86_64 is compatible with binaries from previous releases.
443
+ # Arm64 support was introduced in 11.0, so no Arm binaries from previous
444
+ # releases exist.
445
+ #
446
+ # However, the "universal2" binary format can have a
447
+ # macOS version earlier than 11.0 when the x86_64 part of the binary supports
448
+ # that version of macOS.
449
+ if arch == "x86_64":
450
+ for minor_version in range(16, 3, -1):
451
+ compat_version = 10, minor_version
452
+ binary_formats = _mac_binary_formats(compat_version, arch)
453
+ for binary_format in binary_formats:
454
+ yield "macosx_{major}_{minor}_{binary_format}".format(
455
+ major=compat_version[0],
456
+ minor=compat_version[1],
457
+ binary_format=binary_format,
458
+ )
459
+ else:
460
+ for minor_version in range(16, 3, -1):
461
+ compat_version = 10, minor_version
462
+ binary_format = "universal2"
463
+ yield "macosx_{major}_{minor}_{binary_format}".format(
464
+ major=compat_version[0],
465
+ minor=compat_version[1],
466
+ binary_format=binary_format,
467
+ )
468
+
469
+
470
+ def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:
471
+ linux = _normalize_string(sysconfig.get_platform())
472
+ if is_32bit:
473
+ if linux == "linux_x86_64":
474
+ linux = "linux_i686"
475
+ elif linux == "linux_aarch64":
476
+ linux = "linux_armv7l"
477
+ _, arch = linux.split("_", 1)
478
+ yield from _manylinux.platform_tags(linux, arch)
479
+ yield from _musllinux.platform_tags(arch)
480
+ yield linux
481
+
482
+
483
+ def _generic_platforms() -> Iterator[str]:
484
+ yield _normalize_string(sysconfig.get_platform())
485
+
486
+
487
+ def platform_tags() -> Iterator[str]:
488
+ """
489
+ Provides the platform tags for this installation.
490
+ """
491
+ if platform.system() == "Darwin":
492
+ return mac_platforms()
493
+ elif platform.system() == "Linux":
494
+ return _linux_platforms()
495
+ else:
496
+ return _generic_platforms()
497
+
498
+
499
+ def interpreter_name() -> str:
500
+ """
501
+ Returns the name of the running interpreter.
502
+
503
+ Some implementations have a reserved, two-letter abbreviation which will
504
+ be returned when appropriate.
505
+ """
506
+ name = sys.implementation.name
507
+ return INTERPRETER_SHORT_NAMES.get(name) or name
508
+
509
+
510
+ def interpreter_version(*, warn: bool = False) -> str:
511
+ """
512
+ Returns the version of the running interpreter.
513
+ """
514
+ version = _get_config_var("py_version_nodot", warn=warn)
515
+ if version:
516
+ version = str(version)
517
+ else:
518
+ version = _version_nodot(sys.version_info[:2])
519
+ return version
520
+
521
+
522
+ def _version_nodot(version: PythonVersion) -> str:
523
+ return "".join(map(str, version))
524
+
525
+
526
+ def sys_tags(*, warn: bool = False) -> Iterator[Tag]:
527
+ """
528
+ Returns the sequence of tag triples for the running interpreter.
529
+
530
+ The order of the sequence corresponds to priority order for the
531
+ interpreter, from most to least important.
532
+ """
533
+
534
+ interp_name = interpreter_name()
535
+ if interp_name == "cp":
536
+ yield from cpython_tags(warn=warn)
537
+ else:
538
+ yield from generic_tags()
539
+
540
+ if interp_name == "pp":
541
+ interp = "pp3"
542
+ elif interp_name == "cp":
543
+ interp = "cp" + interpreter_version(warn=warn)
544
+ else:
545
+ interp = None
546
+ yield from compatible_tags(interpreter=interp)
@@ -0,0 +1,141 @@
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import re
6
+ from typing import FrozenSet, NewType, Tuple, Union, cast
7
+
8
+ from .tags import Tag, parse_tag
9
+ from .version import InvalidVersion, Version
10
+
11
+ BuildTag = Union[Tuple[()], Tuple[int, str]]
12
+ NormalizedName = NewType("NormalizedName", str)
13
+
14
+
15
+ class InvalidWheelFilename(ValueError):
16
+ """
17
+ An invalid wheel filename was found, users should refer to PEP 427.
18
+ """
19
+
20
+
21
+ class InvalidSdistFilename(ValueError):
22
+ """
23
+ An invalid sdist filename was found, users should refer to the packaging user guide.
24
+ """
25
+
26
+
27
+ _canonicalize_regex = re.compile(r"[-_.]+")
28
+ # PEP 427: The build number must start with a digit.
29
+ _build_tag_regex = re.compile(r"(\d+)(.*)")
30
+
31
+
32
+ def canonicalize_name(name: str) -> NormalizedName:
33
+ # This is taken from PEP 503.
34
+ value = _canonicalize_regex.sub("-", name).lower()
35
+ return cast(NormalizedName, value)
36
+
37
+
38
+ def canonicalize_version(
39
+ version: Union[Version, str], *, strip_trailing_zero: bool = True
40
+ ) -> str:
41
+ """
42
+ This is very similar to Version.__str__, but has one subtle difference
43
+ with the way it handles the release segment.
44
+ """
45
+ if isinstance(version, str):
46
+ try:
47
+ parsed = Version(version)
48
+ except InvalidVersion:
49
+ # Legacy versions cannot be normalized
50
+ return version
51
+ else:
52
+ parsed = version
53
+
54
+ parts = []
55
+
56
+ # Epoch
57
+ if parsed.epoch != 0:
58
+ parts.append(f"{parsed.epoch}!")
59
+
60
+ # Release segment
61
+ release_segment = ".".join(str(x) for x in parsed.release)
62
+ if strip_trailing_zero:
63
+ # NB: This strips trailing '.0's to normalize
64
+ release_segment = re.sub(r"(\.0)+$", "", release_segment)
65
+ parts.append(release_segment)
66
+
67
+ # Pre-release
68
+ if parsed.pre is not None:
69
+ parts.append("".join(str(x) for x in parsed.pre))
70
+
71
+ # Post-release
72
+ if parsed.post is not None:
73
+ parts.append(f".post{parsed.post}")
74
+
75
+ # Development release
76
+ if parsed.dev is not None:
77
+ parts.append(f".dev{parsed.dev}")
78
+
79
+ # Local version segment
80
+ if parsed.local is not None:
81
+ parts.append(f"+{parsed.local}")
82
+
83
+ return "".join(parts)
84
+
85
+
86
+ def parse_wheel_filename(
87
+ filename: str,
88
+ ) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:
89
+ if not filename.endswith(".whl"):
90
+ raise InvalidWheelFilename(
91
+ f"Invalid wheel filename (extension must be '.whl'): {filename}"
92
+ )
93
+
94
+ filename = filename[:-4]
95
+ dashes = filename.count("-")
96
+ if dashes not in (4, 5):
97
+ raise InvalidWheelFilename(
98
+ f"Invalid wheel filename (wrong number of parts): {filename}"
99
+ )
100
+
101
+ parts = filename.split("-", dashes - 2)
102
+ name_part = parts[0]
103
+ # See PEP 427 for the rules on escaping the project name
104
+ if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
105
+ raise InvalidWheelFilename(f"Invalid project name: {filename}")
106
+ name = canonicalize_name(name_part)
107
+ version = Version(parts[1])
108
+ if dashes == 5:
109
+ build_part = parts[2]
110
+ build_match = _build_tag_regex.match(build_part)
111
+ if build_match is None:
112
+ raise InvalidWheelFilename(
113
+ f"Invalid build number: {build_part} in '{filename}'"
114
+ )
115
+ build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))
116
+ else:
117
+ build = ()
118
+ tags = parse_tag(parts[-1])
119
+ return (name, version, build, tags)
120
+
121
+
122
+ def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:
123
+ if filename.endswith(".tar.gz"):
124
+ file_stem = filename[: -len(".tar.gz")]
125
+ elif filename.endswith(".zip"):
126
+ file_stem = filename[: -len(".zip")]
127
+ else:
128
+ raise InvalidSdistFilename(
129
+ f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
130
+ f" {filename}"
131
+ )
132
+
133
+ # We are requiring a PEP 440 version, which cannot contain dashes,
134
+ # so we split on the last dash.
135
+ name_part, sep, version_part = file_stem.rpartition("-")
136
+ if not sep:
137
+ raise InvalidSdistFilename(f"Invalid sdist filename: {filename}")
138
+
139
+ name = canonicalize_name(name_part)
140
+ version = Version(version_part)
141
+ return (name, version)