generated from thoth-station/template-project
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmicropipenv.py
executable file
·1527 lines (1247 loc) · 59.6 KB
/
micropipenv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# micropipenv
# Copyright(C) 2020 Fridolin Pokorny
# Copyright(C) 2021 Lumir Balhar
#
# This program is free software: you can redistribute it and / or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""A lightweight wrapper for pip to support Pipenv/Poetry/requriements files.
This wrapper can convert Pipfile/Pipfile.lock/poetry.lock to requirements.in
and/or requirements.txt file suitable for setup.py script or for pip-tools.
Moreover, this wrapper can mimic `pipenv install --deploy` or `poetry install`.
For any resolved stack, micropipenv can parse
Pipfile/Pipfile.lock/poetry.lock/requirements.txt and install required
dependencies using raw pip. The virtual environment is not created, but one can
issue `python3 -m venv venv/ && . venv/bin/activate` to create one.
"""
__version__ = "1.8.1"
__author__ = "Fridolin Pokorny <[email protected]>"
__title__ = "micropipenv"
import argparse
import hashlib
import json
import logging
import os
import re
import subprocess
import sys
import tempfile
from collections import defaultdict, deque, OrderedDict
from itertools import chain
from importlib import import_module
from pathlib import Path
from urllib.parse import urlparse
_LOGGER = logging.getLogger(__title__)
_SUPPORTED_PIP_STR = ">=9,<=24.3.1" # Respects requirement in setup.py and latest pip to release date.
try:
from pip import __version__ as pip_version
from pip._vendor.packaging.requirements import Requirement
from pip._vendor.packaging.version import Version
from pip._vendor.packaging.specifiers import SpecifierSet
try:
from pip._internal.req import parse_requirements
except ImportError: # for pip<10
from pip.req import parse_requirements # type: ignore
try:
try:
from pip._internal.network.session import PipSession
except ImportError:
from pip._internal.download import PipSession # type: ignore
except ImportError:
from pip.download import PipSession # type: ignore
try:
from pip._internal.index.package_finder import PackageFinder
except ImportError:
try:
from pip._internal.index import PackageFinder # type: ignore
except ImportError:
from pip.index import PackageFinder # type: ignore
except Exception:
_LOGGER.error("Check your pip version, supported pip versions: %s", _SUPPORTED_PIP_STR)
raise
try:
from typing import TYPE_CHECKING
except ImportError:
TYPE_CHECKING = False
if TYPE_CHECKING:
from typing import Any
from typing import Dict
from typing import Generator
from typing import List
from typing import MutableMapping
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
from pip._internal.req.req_file import ParsedRequirement
def get_index_urls(): # type: () -> Tuple[str, ...]
"""Return parsed MICROPIPENV_DEFAULT_INDEX_URLS env variable or the default value."""
urls = os.getenv("MICROPIPENV_DEFAULT_INDEX_URLS")
if urls and urls.strip() != "":
return tuple([url.strip() for url in urls.split(",")])
return ("https://pypi.org/simple",)
_DEFAULT_INDEX_URLS = get_index_urls()
_MAX_DIR_TRAVERSAL = 42 # Avoid any symlinks that would loop.
_PIP_BIN = os.getenv("MICROPIPENV_PIP_BIN", "pip")
_SUPPORTED_PIP = SpecifierSet(_SUPPORTED_PIP_STR)
_DEBUG = int(os.getenv("MICROPIPENV_DEBUG", 0))
_NO_LOCKFILE_PRINT = int(os.getenv("MICROPIPENV_NO_LOCKFILE_PRINT", 0))
_NO_LOCKFILE_WRITE = int(os.getenv("MICROPIPENV_NO_LOCKFILE_WRITE", 0))
_FILE_METHOD_MAP = OrderedDict(
[ # The order here defines priorities
("Pipfile.lock", "pipenv"),
("poetry.lock", "poetry"),
("requirements.txt", "requirements"),
]
)
__re_nested_vars = re.compile(r"\$\{(?P<name>[^\}:]*)(?::-(?P<default>[^\}]*))?\}")
__re_sub_vars = re.compile(r"\$\{[^}]*\}")
class MicropipenvException(Exception):
"""A base class for all micropipenv exceptions."""
class FileNotFound(MicropipenvException):
"""Raised if the given file was not found on the filesystem."""
class FileReadError(MicropipenvException):
"""Raised if the given file cannot be loaded or parsed."""
class ExtrasMissing(MicropipenvException):
"""Raised when micropipenv was invoked with functionality requiring a missing extras."""
class ArgumentsError(MicropipenvException):
"""Raised when arguments passed are disjoint or wrong."""
class PythonVersionMismatch(MicropipenvException):
"""Raised if Python version found does not correspond to the one present in Pipfile.lock."""
class HashMismatch(MicropipenvException):
"""Raised when computed hash out of Pipfile does not correspond to the hash stated in Pipfile.lock."""
class PipInstallError(MicropipenvException):
"""Raised when `pip install` returned a non-zero exit code."""
class PipRequirementsNotLocked(MicropipenvException):
"""Raised when requirements in requirements.txt are not fully locked."""
class RequirementsError(MicropipenvException):
"""Raised when requirements file has any issue."""
class PoetryError(MicropipenvException):
"""Raised when any of the pyproject.toml or poetry.lock file has any issue."""
class CompatibilityError(MicropipenvException):
"""Raised when internal pip API is incompatible with micropipenv."""
class NotSupportedError(MicropipenvException):
"""Raised when the given feature is not supported by micropipenv."""
def normalize_package_name(package_name): # type: (str) -> str
"""Implement package name normalization as decribed in PEP 503."""
return re.sub(r"[-_.]+", "-", package_name).lower()
def _check_pip_version(raise_on_incompatible=False): # type: (bool) -> bool
"""Check pip version running."""
if Version(pip_version) not in _SUPPORTED_PIP:
msg = "pip in version {!r} not tested, tested versions: {!r}".format(pip_version, _SUPPORTED_PIP_STR)
if raise_on_incompatible:
raise CompatibilityError(msg)
_LOGGER.warning(msg)
return False
return True
def _import_toml(): # type: () -> Any
"""Import and return tomllib, toml, pytoml, or tomli module (in this order)."""
exception_names = {
"tomllib": "TOMLDecodeError",
"toml": "TomlDecodeError",
"pytoml": "TomlError",
"tomli": "TOMLDecodeError",
}
# Only tomli/tomllib requires TOML files to be opened
# in binary mode: https://github.com/hukkin/tomli#parse-a-toml-file
open_kwargs = defaultdict(dict) # type: Dict[str, Dict[str, str]]
open_kwargs["tomli"] = open_kwargs["tomllib"] = {"mode": "rb"}
for module_name in "tomllib", "toml", "pytoml", "tomli":
try:
module = import_module(module_name)
exception = getattr(module, exception_names[module_name])
return module, exception, open_kwargs[module_name]
except ImportError:
pass
else:
raise ExtrasMissing(
"Failed to import toml needed for parsing Pipfile, please install micropipenv "
"with toml extra: pip install micropipenv[toml]"
)
def _traverse_up_find_file(file_name): # type: (str) -> str
"""Traverse the root up, find the given file by name and return its path."""
path = os.getcwd()
traversed = _MAX_DIR_TRAVERSAL
while traversed > 0:
if file_name in os.listdir(path):
_LOGGER.debug("Found %r in %r", file_name, path)
return os.path.join(path, file_name)
traversed -= 1
path = os.path.realpath(os.path.join(path, ".."))
else:
raise FileNotFound("File {!r} not found in {!r} or any parent directory".format(file_name, os.getcwd()))
def _read_pipfile_lock(): # type: () -> Any
"""Find and load Pipfile.lock."""
pipfile_lock_path = _traverse_up_find_file("Pipfile.lock")
try:
with open(pipfile_lock_path) as input_file:
content = json.load(input_file)
except json.JSONDecodeError as exc:
raise FileReadError("Filed to parse Pipfile.lock: {}".format(str(exc))) from exc
except Exception as exc:
raise FileReadError(str(exc)) from exc
pipfile_spec_version = content.get("_meta", {}).get("pipfile-spec")
if pipfile_spec_version != 6:
_LOGGER.warning("Unsupported Pipfile.lock spec version - supported is 6, got {}".format(pipfile_spec_version))
return content
def _read_pipfile(): # type: () -> Any
"""Find and read Pipfile."""
toml, toml_exception, open_kwargs = _import_toml()
pipfile_path = _traverse_up_find_file("Pipfile")
try:
with open(pipfile_path, **open_kwargs) as input_file:
return toml.load(input_file)
except toml_exception as exc:
raise FileReadError("Failed to parse Pipfile: {}".format(str(exc))) from exc
except Exception as exc:
raise FileReadError(str(exc)) from exc
def _read_poetry(): # type: () -> Tuple[MutableMapping[str, Any], MutableMapping[str, Any]]
"""Find and read poetry.lock and pyproject.toml."""
toml, toml_exception, open_kwargs = _import_toml()
poetry_lock_path = _traverse_up_find_file("poetry.lock")
pyproject_toml_path = _traverse_up_find_file("pyproject.toml")
try:
with open(poetry_lock_path, **open_kwargs) as input_file:
poetry_lock = toml.load(input_file)
except toml_exception as exc:
raise FileReadError("Failed to parse poetry.lock: {}".format(str(exc))) from exc
except Exception as exc:
raise FileReadError(str(exc)) from exc
try:
with open(pyproject_toml_path, **open_kwargs) as input_file:
pyproject_toml = toml.load(input_file)
except toml_exception as exc:
raise FileReadError("Failed to parse pyproject.toml: {}".format(str(exc))) from exc
except Exception as exc:
raise FileReadError(str(exc)) from exc
return poetry_lock, pyproject_toml
def _compute_pipfile_hash(pipfile): # type: (Dict[str, Any]) -> str
"""Compute Pipfile hash based on its content."""
data = {
"_meta": {"requires": pipfile.get("requires", {}), "sources": pipfile["source"]},
"default": pipfile.get("packages", {}),
"develop": pipfile.get("dev-packages", {}),
}
content = json.dumps(data, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(content.encode("utf8")).hexdigest()
def _compute_poetry_hash(pyproject): # type: (MutableMapping[str, Any]) -> str
"""Compute pyproject.toml hash based on poetry content."""
poetry_data = pyproject["tool"]["poetry"]
relevant_keys = ["dependencies", "dev-dependencies", "source", "extras"]
relevant_content = {key: poetry_data.get(key) for key in relevant_keys}
# relevant_keys are the original one and they should always be in
# the relevant_content even their value is None.
# group is a new key since poetry 1.2 and we should include it only
# if pyproject.toml contains it. Including it always would break
# backward compatibility.
# See: https://github.com/python-poetry/poetry/blob/4a07b5e0243bb8879dd6725cb901d9fa0f6eb182/src/poetry/packages/locker.py#L278-L293
if "group" in poetry_data:
relevant_content["group"] = poetry_data.get("group")
return hashlib.sha256(json.dumps(relevant_content, sort_keys=True).encode()).hexdigest()
def _get_installed_python_version(): # type: () -> str
return "{}.{}".format(sys.version_info.major, sys.version_info.minor)
def _validate_poetry_python_version(
poetry_lock, current_python, debug=False
): # type: (MutableMapping[str, Any], str, bool) -> None
# TODO: Implement or use external parser for Python versions in Poetry specification.
# See for details: https://github.com/thoth-station/micropipenv/issues/187
wanted_python_version = poetry_lock["metadata"]["python-versions"]
message = (
"Warning: Currently, Micropipenv is not able to parse complex Python version specifications used by Poetry. "
f"Desired version: {wanted_python_version}, current version: {current_python}."
)
level = "debug" if debug else "warning"
getattr(_LOGGER, level)(message)
def verify_poetry_lockfile(
pyproject=None, poetry_lock=None, current_python_version=None
): # type: (Optional[MutableMapping[str, Any]], Optional[MutableMapping[str, Any]], Optional[str]) -> None
"""Validate that Poetry.lock is up to date with pyproject.toml."""
if pyproject is None or poetry_lock is None:
poetry_lock, pyproject = _read_poetry()
if current_python_version is None:
current_python_version = _get_installed_python_version()
_validate_poetry_python_version(poetry_lock, current_python_version)
pyproject_hash = _compute_poetry_hash(pyproject)
poetry_lock_hash = poetry_lock["metadata"]["content-hash"]
if pyproject_hash != poetry_lock_hash:
raise HashMismatch(
"Poetry.lock hash {!r} does not correspond to hash computed based on "
"pyproject.toml {!r}, aborting deployment".format(poetry_lock_hash, pyproject_hash)
)
def verify_pipenv_lockfile(
pipfile=None, pipfile_lock=None
): # type: (Optional[Dict[str, Any]], Optional[Dict[str, Any]]) -> None
"""Validate that Pipfile.lock is up to date with Pipfile."""
pipfile_lock = pipfile_lock or _read_pipfile_lock()
pipenv_python_version = pipfile_lock["_meta"].get("requires", {}).get("python_version")
if pipenv_python_version is not None:
installed_python_version = _get_installed_python_version()
if pipenv_python_version != installed_python_version:
raise PythonVersionMismatch(
"Running Python version {}, but Pipfile.lock requires "
"Python version {}".format(installed_python_version, pipenv_python_version)
)
else:
_LOGGER.warning("No Python version requirement in Pipfile.lock found, no Python version check is performed")
pipfile_lock_hash = pipfile_lock.get("_meta", {}).get("hash", {}).get("sha256")
pipfile_hash = _compute_pipfile_hash(pipfile or _read_pipfile())
if pipfile_hash != pipfile_lock_hash:
raise HashMismatch(
"Pipfile.lock hash {!r} does not correspond to hash computed based on "
"Pipfile {!r}, aborting deployment".format(pipfile_lock_hash, pipfile_hash)
)
def install_pipenv(
pip_bin=_PIP_BIN, pipfile=None, pipfile_lock=None, *, deploy=False, dev=False, pip_args=None
): # type: (str, Optional[Dict[str, Any]], Optional[Dict[str, Any]], bool, bool, Optional[List[str]]) -> None
"""Perform installation of packages from Pipfile.lock."""
pipfile_lock = pipfile_lock or _read_pipfile_lock()
_maybe_print_pipfile_lock(pipfile_lock)
sections = get_requirements_sections(pipfile_lock=pipfile_lock, no_dev=not dev)
if deploy:
verify_pipenv_lockfile(pipfile, pipfile_lock)
tmp_file = tempfile.NamedTemporaryFile("w", prefix="requirements_micropipenv-", suffix=".txt", delete=False)
_LOGGER.debug("Using temporary file for storing requirements: %r", tmp_file.name)
cmd = [pip_bin, "install", "--no-deps", "--disable-pip-version-check", "-r", tmp_file.name, *(pip_args or [])]
_LOGGER.debug("Requirements will be installed using %r", cmd)
packages = chain(
sections.get("default", {}).items(),
sections.get("develop", {}).items() if dev else [],
)
# We maintain an integer assigned to each package - this integer holds a value - how
# many times the given package failed to install. If a package fails to install, it is
# re-scheduled to the next installation round, until we try all the packages to
# satisfy requirements. If any package succeeds with installation, the integer is
# set to 0 again for all failed installations. This way we can break "cycles" in
# installation errors.
to_install = deque({"package_name": i[0], "info": i[1], "error": 0} for i in packages)
try:
while to_install:
entry = to_install.popleft()
package_name, info, had_error = entry["package_name"], entry["info"], entry["error"]
if "git" in info:
_LOGGER.warning("!!! Requirement %s uses a VCS version: %r", package_name, info)
package_entry_str = _get_package_entry_str(package_name, info)
for index_config_str in _iter_index_entry_str(sections, info):
# We are opening the tmp_file for the second time here.
# The purpose of this is to make sure that the content is always
# flushed from buffers and that we start from the beggining
# of the file every time. All of that to make sure that there is
# only one package written in the tmp_file and pip is able to
# read the package name from the file.
with open(tmp_file.name, "w") as f:
f.write(index_config_str)
f.write(package_entry_str)
_LOGGER.info("Installing %r", package_name)
called_process = subprocess.run(cmd)
if called_process.returncode == 0:
# Discard any error flag if we have any packages that fail to install.
for item in reversed(to_install):
if item["error"] == 0:
# Fast path - errors are always added to the end of the queue,
# if we find a package without any error we can safely break.
break
item["error"] = 0
break
else:
if len(to_install) == 0 or (had_error and had_error > len(to_install)):
raise PipInstallError(
"Failed to install requirements, dependency {!r} could not be installed".format(package_name)
)
_LOGGER.warning("Failed to install %r, will try in next installation round...", package_name)
to_install.append({"package_name": package_name, "info": info, "error": had_error + 1})
finally:
tmp_file.close()
os.remove(tmp_file.name)
def _instantiate_package_finder(pip_session): # type: (PipSession) -> PackageFinder
"""Instantiate package finder, in a pip>=10 and pip<10 compatible way."""
try:
return PackageFinder(find_links=[], session=pip_session, index_urls=_DEFAULT_INDEX_URLS) # type: ignore
except TypeError: # API changed in pip>=10
from pip._internal.models.search_scope import SearchScope
from pip._internal.models.selection_prefs import SelectionPreferences
selection_prefs = SelectionPreferences(
allow_yanked=True,
)
additional_kwargs = {}
if Version(pip_version).release >= (22, 3):
# New argument in pip 22.3
# https://github.com/pypa/pip/commit/5d7a1a68c7feb75136a0fd120de54b85df105bac
additional_kwargs["no_index"] = False
search_scope = SearchScope([], [], **additional_kwargs) # type: ignore
try:
from pip._internal.index.collector import LinkCollector
except ModuleNotFoundError:
try:
from pip._internal.collector import LinkCollector # type: ignore
except ModuleNotFoundError: # pip>=19.2<20
return PackageFinder.create( # type: ignore
session=pip_session, selection_prefs=selection_prefs, search_scope=search_scope
)
link_collector = LinkCollector(session=pip_session, search_scope=search_scope)
additional_kwargs = {}
# pip 22 deprecates vendored html5lib and uses stdlib html.parser
# https://github.com/pypa/pip/pull/10291
# pip 22.2 will remove that switch
# https://github.com/pypa/pip/issues/10825
if (22, 2) > Version(pip_version).release >= (22,):
additional_kwargs["use_deprecated_html5lib"] = False
return PackageFinder.create(
link_collector=link_collector,
selection_prefs=selection_prefs,
**additional_kwargs, # type: ignore
)
def _get_requirement_info(requirement): # type: (ParsedRequirement) -> Dict[str, Any]
"""Get information about the requirement supporting multiple pip versions.
This function acts like a compatibility layer across multiple pip releases supporting
changes in pip's internal API to obtain information about requirements.
"""
# Editable requirements.
editable = getattr(requirement, "editable", False) or getattr(requirement, "is_editable", False)
# Check for unsupported VCS.
link_url = getattr(requirement, "requirement", None) or getattr(requirement, "link", None)
if link_url and str(link_url).startswith(("hg+", "svn+", "bzr+")):
raise NotSupportedError("Non-Git VCS requirement {!r} is not supported yet".format(str(link_url)))
is_url = False
req = None
if hasattr(requirement, "req"):
req = requirement.req # type: ignore
elif hasattr(requirement, "requirement") and not editable:
if not requirement.requirement.startswith("git+"):
req = Requirement(requirement.requirement)
else:
is_url = True
# Link for requirements passed by URL or using path.
link = None
if editable:
if hasattr(requirement, "link"):
link = str(requirement.link) # type: ignore
elif req is not None:
link = req.url
elif hasattr(requirement, "requirement"):
link = str(requirement.requirement)
else:
raise CompatibilityError
# Requirement name.
if editable:
name = str(link)
elif hasattr(requirement, "name"):
name = requirement.name # type: ignore
elif req is not None:
name = req.name
elif hasattr(requirement, "requirement") and is_url:
name = requirement.requirement
else:
raise CompatibilityError
# Version specifier.
version_specifier = None
version_specifier_length = None
if not editable and not is_url:
if hasattr(requirement, "specifier"):
version_specifier = str(requirement.specifier) # type: ignore
version_specifier_length = len(requirement.specifier) # type: ignore
elif req is not None:
# pip>=20
version_specifier = str(req.specifier)
version_specifier_length = len(req.specifier)
else:
raise CompatibilityError
# Artifact hashes.
hash_options = None
if not editable and not is_url:
if hasattr(requirement, "options"):
hash_options = requirement.options.get("hashes") # type: ignore
else:
hash_options = requirement.hash_options # type: ignore
hashes = {}
for hash_type, hashes_present in hash_options.items() if hash_options else []:
hashes = {
"hash_type": hash_type,
"hashes_present": hashes_present,
}
# Markers.
markers = None
if not editable and not is_url:
if hasattr(requirement, "markers"):
markers = requirement.markers # type: ignore
elif req is not None:
markers = req.marker
else:
raise CompatibilityError
# Extras.
extras = None
if not editable and not is_url:
if hasattr(requirement, "extras"):
extras = requirement.extras # type: ignore
elif req is not None:
extras = req.extras
else:
raise CompatibilityError
return {
"editable": editable,
"version_specifier": version_specifier,
"version_specifier_length": version_specifier_length,
"hashes": hashes,
"link": link,
"extras": extras,
"markers": markers,
"name": name,
}
def _requirements2pipfile_lock(requirements_txt_path=None): # type: (Optional[str]) -> Dict[str, Any]
"""Parse requirements.txt file and return its Pipfile.lock representation."""
requirements_txt_path = requirements_txt_path or _traverse_up_find_file("requirements.txt")
pip_session = PipSession()
finder = _instantiate_package_finder(pip_session)
result = {} # type: Dict[str, Any]
for requirement in parse_requirements(filename=requirements_txt_path, session=PipSession(), finder=finder):
requirement_info = _get_requirement_info(requirement)
entry = {} # type: Dict[str, Any]
if not requirement_info["editable"]:
if requirement_info["version_specifier"] is None or not (
requirement_info["hashes"]
and requirement_info["version_specifier_length"] == 1
and requirement_info["version_specifier"].startswith("==")
):
# Not pinned down software stack using pip-tools.
raise PipRequirementsNotLocked
hashes = []
for hash_ in requirement_info["hashes"]["hashes_present"]:
hashes.append("{}:{}".format(requirement_info["hashes"]["hash_type"], hash_))
entry["hashes"] = sorted(hashes)
entry["version"] = requirement_info["version_specifier"]
else:
entry["editable"] = True
entry["path"] = requirement_info["link"]
if requirement_info["extras"]:
entry["extras"] = sorted(requirement_info["extras"])
if requirement_info["markers"]:
entry["markers"] = str(requirement_info["markers"])
if entry.get("editable", False):
# Create a unique name for editable to avoid possible clashes.
requirement_name = hashlib.sha256(json.dumps(entry, sort_keys=True).encode("utf8")).hexdigest()
else:
requirement_name = requirement_info["name"]
# We add all dependencies to default, develop should not be present in requirements.txt file, but rather
# in dev-requirements.txt or similar.
if requirement_name in result:
raise RequirementsError("Duplicate entry for requirement {}".format(requirement.name)) # type: ignore
result[requirement_name] = entry
if all(dep.get("editable", False) for dep in result.values()):
# If all the dependencies are editable, we cannot safely say that we
# have a lock file - users can easily end up with missing dependencies
# as we install dependencies with --no-deps in case of lock files. Let
# pip resolver do its job, just to be sure.
raise PipRequirementsNotLocked
sources = [] # type: List[Dict[str, Any]]
for index_url in chain(finder.index_urls, _DEFAULT_INDEX_URLS):
if any(s["url"] == index_url for s in sources):
continue
sources.append({"name": hashlib.sha256(index_url.encode()).hexdigest(), "url": index_url, "verify_ssl": True})
if len(sources) == 1:
# Explicitly assign index if there is just one.
for entry in result.values():
if not entry.get("editable", False):
entry["index"] = sources[0]["name"]
with open(requirements_txt_path, "r") as requirements_file:
requirements_hash = hashlib.sha256(requirements_file.read().encode()).hexdigest()
return {
"_meta": {
"hash": {"sha256": requirements_hash},
"pipfile-spec": 6,
"sources": sources,
"requires": {"python_version": _get_installed_python_version()},
},
"default": result,
"develop": {},
}
def _maybe_print_pipfile_lock(pipfile_lock): # type: (Dict[str, Any]) -> None
"""Print and store Pipfile.lock based on configuration supplied."""
if _NO_LOCKFILE_PRINT and _NO_LOCKFILE_WRITE:
return
pipfile_lock_json = json.dumps(pipfile_lock, sort_keys=True, indent=4)
if not _NO_LOCKFILE_PRINT:
print("-" * 33 + "- Pipfile.lock -" + "-" * 33, file=sys.stderr)
print(pipfile_lock_json, file=sys.stderr)
print("-" * 33 + "- Pipfile.lock -" + "-" * 33, file=sys.stderr)
if not _NO_LOCKFILE_WRITE:
try:
with open("Pipfile.lock", "w") as lock_file:
lock_file.write(pipfile_lock_json)
except Exception as exc:
_LOGGER.warning("Failed to write lockfile to container image: %s", str(exc))
def _maybe_print_pip_freeze(pip_bin): # type: (str) -> None
"""Print and store requirements.txt based on configuration supplied."""
if _NO_LOCKFILE_PRINT:
return
print("-" * 33 + "- pip freeze -" + "-" * 33, file=sys.stderr)
cmd = [pip_bin, "freeze", "--disable-pip-version-check"]
called_process = subprocess.run(cmd)
print("-" * 33 + "- pip freeze -" + "-" * 33, file=sys.stderr)
if called_process.returncode != 0:
_LOGGER.warning("Failed to perform pip freeze to check installed dependencies, the error is not fatal")
def _translate_poetry_dependency(info): # type: (str) -> str
"""Translate Poetry dependency specification as written in pyproject.toml into its Pipfile.lock equivalent."""
if isinstance(info, str) and re.match(r"^\d", info):
return "=={}".format(info)
# TODO: poetry uses version like ^0.10.4 that are not Pipfile.lock complaint.
return info
def _poetry2pipfile_lock(
only_direct=False,
no_default=False,
no_dev=False,
deploy=False,
): # type: (bool, bool, bool, bool) -> Dict[str, Any]
"""Convert Poetry files to Pipfile.lock as Pipenv would produce."""
poetry_lock, pyproject_toml = _read_poetry()
current_python_version = _get_installed_python_version()
if deploy:
verify_poetry_lockfile(pyproject_toml, poetry_lock, current_python_version)
else:
_validate_poetry_python_version(poetry_lock, current_python_version, debug=True)
pyproject_poetry_section = pyproject_toml.get("tool", {}).get("poetry", {})
sources = []
has_default = False # If default flag is set, it disallows PyPI.
for item in pyproject_poetry_section.get("source", []):
source = {"name": item["name"], "verify_ssl": True}
if item.get("url"):
source["url"] = item.get("url")
sources.append(source)
has_default = has_default or item.get("default", False)
for index_url in reversed(_DEFAULT_INDEX_URLS) if not has_default else []:
# Place defaults as first.
entry = {
"url": index_url,
"name": hashlib.sha256(index_url.encode()).hexdigest(),
"verify_ssl": True,
} # type: Any
sources.insert(0, entry)
default: Dict[str, Any] = {}
develop: Dict[str, Any] = {}
if only_direct:
if not no_default:
for dependency_name, info in pyproject_poetry_section.get("dependencies", {}).items():
if dependency_name != "python":
default[dependency_name] = _translate_poetry_dependency(info)
if not no_dev:
for dependency_name, info in pyproject_poetry_section.get("dev-dependencies", {}).items():
develop[dependency_name] = _translate_poetry_dependency(info)
return {
"_meta": {
"hash": {"sha256": poetry_lock["metadata"]["content-hash"]},
"pipfile-spec": 6,
"sources": sources,
"requires": {"python_version": current_python_version},
},
"default": default,
"develop": develop,
}
additional_markers = defaultdict(list)
skip_all_markers = object()
dev_category = set()
main_category = set()
normalized_pyproject_poetry_dependencies = [
normalize_package_name(name) for name in pyproject_poetry_section.get("dependencies", ())
]
normalized_pyproject_poetry_dev_dependencies = []
groups = pyproject_poetry_section.get("group", {})
for group, content in groups.items():
if "dependencies" in content:
normalized_pyproject_poetry_dev_dependencies.extend(
[normalize_package_name(name) for name in content["dependencies"]]
)
# Double-ended queue for entries
entries_queue = deque(poetry_lock["package"])
# Record of attempts of getting a category of an entry
# to potentially break endless loop caused by corrupted metadata.
# Example: a package is in poetry.lock but it's neither direct
# nor indirect dependency.
entry_category_attempts = defaultdict(int) # type: Dict[str, int]
while entries_queue:
entry = entries_queue.popleft()
# Use normalized names everywhere possible.
# Original name is needed for example for getting hashes from poetry.lock.
original_name = entry["name"]
entry["name"] = normalize_package_name(entry["name"])
# Poetry 1.5+ no longer provides category in poetry.lock so we have to
# guess it from the content of pyproject.toml and dependency graph.
if entry.get("category") == "main" or entry["name"] in normalized_pyproject_poetry_dependencies:
main_category.add(entry["name"])
if entry.get("category") == "dev" or entry["name"] in normalized_pyproject_poetry_dev_dependencies:
dev_category.add(entry["name"])
if entry["name"] not in main_category and entry["name"] not in dev_category:
# If we don't know the category yet, process the package later
entry_category_attempts[entry["name"]] += 1
if entry_category_attempts[entry["name"]] > 3:
raise PoetryError(f"Failed to find package category for: {entry['name']}")
entries_queue.append(entry)
continue
hashes = []
# Older poetry.lock format contains files in [metadata].
# New version 2.0 has files in [[package]] section.
metadata_file_entries = poetry_lock["metadata"].get("files", {}).get(original_name, [])
package_file_entries = entry.get("files", [])
for file_entry in metadata_file_entries + package_file_entries:
hashes.append(file_entry["hash"])
requirement: Dict[str, Any] = {"version": "=={}".format(entry["version"])}
if hashes:
requirement["hashes"] = hashes
if entry.get("marker"):
requirement["markers"] = entry["marker"]
if "source" in entry:
if entry["source"]["type"] == "git":
requirement["git"] = entry["source"]["url"]
requirement["ref"] = entry["source"].get("resolved_reference", entry["source"]["reference"])
try:
requirement["subdirectory"] = entry["source"]["subdirectory"]
except KeyError:
pass
elif entry["source"]["type"] == "directory":
requirement["path"] = entry["source"]["url"]
elif entry["source"]["type"] == "legacy":
# Newer poetry marks packages using the old PyPI API as legacy.
# If we have only one source, we can ignore it.
# Otherwise, configure it explicitly.
if len(sources) > 1:
requirement["index"] = entry["source"]["reference"]
elif entry["source"]["type"] == "url":
requirement["file"] = entry["source"]["url"]
else:
raise NotSupportedError(
"micropipenv supports Git VCS or directories, got {} instead".format(entry["source"]["type"])
)
# Poetry does not store information about extras in poetry.lock
# (directly). It stores extras used for direct dependencies in
# pyproject.toml but it lacks this info being tracked for the
# transitive ones. We approximate extras used - we check what
# dependencies are installed as optional. If they form a set with all
# dependencies present in specific extra, the given extra was used.
extra_dependencies = set()
for dependency_name, dependency_info in entry.get("dependencies", {}).items():
dependency_name = normalize_package_name(dependency_name)
if isinstance(dependency_info, dict):
if dependency_info.get("optional", False):
extra_dependencies.add(dependency_name)
# If the dependency is not direct and has some markers,
# we should move the markers to the main dependency definition.
# If there are no additional markers, we have to have a record
# that the dependency has to be installed unconditionaly and that
# we have to skip all other additional markers.
# Also, we don't care about "extra" markers which are computed separatedly
# and are usually not combined with other markers.
if dependency_name not in normalized_pyproject_poetry_dependencies:
if (
isinstance(dependency_info, dict)
and "markers" in dependency_info
and not dependency_info["markers"].startswith("extra")
):
additional_markers[dependency_name].append(dependency_info["markers"])
else:
additional_markers[dependency_name].append(skip_all_markers)
# If package fits into both main and dev categories, poetry add it to the main one.
# This might be a problem in the following scenario:
# Let's say our project looks like this:
# dependencies:
# - A
# dev-dependencies:
# - B
# - A (A is also a dependency of B)
# Package A is therefore in the main category so if we use "--do-default" we get
# only package B but no package A. But using requirements file requires to have
# all dependencies with their hashes and pinned versions.
# So, if a package is in dev and has a dependency in main, add the dependency also to dev or
# if a package is already in "dev_category", add there also all its dependencies.
if entry["name"] in dev_category:
dev_category.add(dependency_name)
# If this package is in main category, all of it's dependencies has to be
# there as well.
if entry["name"] in main_category:
main_category.add(dependency_name)
for extra_name, extras_listed in entry.get("extras", {}).items():
# Turn requirement specification into the actual requirement name.
all_extra_dependencies = set(Requirement(r.split(" ", maxsplit=1)[0]).name for r in extras_listed)
if all_extra_dependencies.issubset(extra_dependencies):
if "extras" not in requirement:
requirement["extras"] = []
requirement["extras"].append(extra_name)
# Sort extras to have always the same output.
if "extras" in requirement:
requirement["extras"] = sorted(requirement["extras"])
if not no_default and entry["name"] in main_category:
default[entry["name"]] = requirement
if not no_dev and (entry["name"] in dev_category):
develop[entry["name"]] = requirement
for dependency_name, markers in additional_markers.items():
# If a package depends on another package unconditionaly
# we should skip all the markers for it.
if skip_all_markers in markers:
continue
category: Optional[Dict[str, Any]]
if dependency_name in default:
category = default
elif dependency_name in develop:
category = develop
else:
category = None
if category:
all_markers = [category[dependency_name].get("markers", None), *markers]
all_markers.remove(None)
category[dependency_name]["markers"] = "(" + ") or (".join(sorted(all_markers)) + ")"
if len(sources) == 1:
# Explicitly assign index if there is just one.
for entry in chain(default.values(), develop.values()):
if "git" not in entry:
entry["index"] = sources[0]["name"]
return {
"_meta": {
"hash": {"sha256": poetry_lock["metadata"]["content-hash"]},
"pipfile-spec": 6,
"sources": sources,
"requires": {"python_version": _get_installed_python_version()},
},
"default": default,
"develop": develop,
}
def install_poetry(
pip_bin=_PIP_BIN, *, deploy=False, dev=False, pip_args=None