-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathcore.py
2634 lines (2480 loc) · 90.6 KB
/
core.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
# -*- coding: utf-8 -*-
import contextlib
import logging
import os
import sys
import shutil
import signal
import time
import tempfile
from glob import glob
import json as simplejson
import click
import click_completion
import crayons
import dotenv
import delegator
from .vendor import pexpect
from first import first
import pipfile
from blindspin import spinner
from requests.packages import urllib3
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import six
from .cmdparse import ScriptEmptyError
from .project import Project, SourceNotFound
from .vendor.requirementslib import Requirement
from .utils import (
convert_deps_to_pip,
is_required_version,
proper_case,
pep423_name,
split_file,
merge_deps,
venv_resolve_deps,
escape_grouped_arguments,
python_version,
find_windows_executable,
prepare_pip_source_args,
temp_environ,
is_valid_url,
download_file,
is_pinned,
is_star,
rmtree,
split_argument,
extract_uri_from_vcs_dep,
fs_str,
)
from ._compat import (
TemporaryDirectory,
vcs,
Path
)
from .import pep508checker, progress
from .environments import (
PIPENV_COLORBLIND,
PIPENV_NOSPIN,
PIPENV_SHELL_FANCY,
PIPENV_TIMEOUT,
PIPENV_SKIP_VALIDATION,
PIPENV_HIDE_EMOJIS,
PIPENV_INSTALL_TIMEOUT,
PYENV_ROOT,
PYENV_INSTALLED,
PIPENV_YES,
PIPENV_DONT_LOAD_ENV,
PIPENV_DEFAULT_PYTHON_VERSION,
PIPENV_MAX_SUBPROCESS,
PIPENV_DONT_USE_PYENV,
SESSION_IS_INTERACTIVE,
PIPENV_USE_SYSTEM,
PIPENV_DOTENV_LOCATION,
PIPENV_SHELL,
PIPENV_PYTHON,
PIPENV_VIRTUALENV,
PIPENV_CACHE_DIR,
)
# Backport required for earlier versions of Python.
if sys.version_info < (3, 3):
from .vendor.backports.shutil_get_terminal_size import get_terminal_size
else:
from shutil import get_terminal_size
# Packages that should be ignored later.
BAD_PACKAGES = ('setuptools', 'pip', 'wheel', 'packaging', 'distribute')
# Are we using the default Python?
USING_DEFAULT_PYTHON = True
if not PIPENV_HIDE_EMOJIS:
now = time.localtime()
# Halloween easter-egg.
if ((now.tm_mon == 10) and (now.tm_mday == 30)) or (
(now.tm_mon == 10) and (now.tm_mday == 31)
):
INSTALL_LABEL = '🎃 '
# Christmas easter-egg.
elif ((now.tm_mon == 12) and (now.tm_mday == 24)) or (
(now.tm_mon == 12) and (now.tm_mday == 25)
):
INSTALL_LABEL = '🎅 '
else:
INSTALL_LABEL = '🐍 '
INSTALL_LABEL2 = crayons.normal('☤ ', bold=True)
STARTING_LABEL = ' '
else:
INSTALL_LABEL = ' '
INSTALL_LABEL2 = ' '
STARTING_LABEL = ' '
# Enable shell completion.
click_completion.init()
# Disable colors, for the color blind and others who do not prefer colors.
if PIPENV_COLORBLIND:
crayons.disable()
# Disable spinner, for cleaner build logs (the unworthy).
if PIPENV_NOSPIN:
@contextlib.contextmanager # noqa: F811
def spinner():
yield
def which(command, location=None, allow_global=False):
if not allow_global and location is None:
location = project.virtualenv_location or os.environ.get('VIRTUAL_ENV')
if not allow_global:
if os.name == 'nt':
p = find_windows_executable(
os.path.join(location, 'Scripts'), command,
)
else:
p = os.path.join(location, 'bin', command)
else:
if command == 'python':
p = sys.executable
if not os.path.exists(p):
if command == 'python':
p = sys.executable or system_which('python')
else:
p = system_which(command)
return p
# Disable warnings for Python 2.6.
if 'urllib3' in globals():
urllib3.disable_warnings(InsecureRequestWarning)
project = Project(which=which)
def load_dot_env():
"""Loads .env file into sys.environ."""
if not PIPENV_DONT_LOAD_ENV:
# If the project doesn't exist yet, check current directory for a .env file
project_directory = project.project_directory or '.'
denv = dotenv.find_dotenv(
PIPENV_DOTENV_LOCATION or os.sep.join([project_directory, '.env'])
)
if os.path.isfile(denv):
click.echo(
crayons.normal(
'Loading .env environment variables…', bold=True
),
err=True,
)
dotenv.load_dotenv(denv, override=True)
def add_to_path(p):
"""Adds a given path to the PATH."""
if p not in os.environ['PATH']:
os.environ['PATH'] = '{0}{1}{2}'.format(
p, os.pathsep, os.environ['PATH']
)
def cleanup_virtualenv(bare=True):
"""Removes the virtualenv directory from the system."""
if not bare:
click.echo(crayons.red('Environment creation aborted.'))
try:
# Delete the virtualenv.
rmtree(project.virtualenv_location)
except OSError as e:
click.echo(
'{0} An error occurred while removing {1}!'.format(
crayons.red('Error: ', bold=True),
crayons.green(project.virtualenv_location),
),
err=True,
)
click.echo(crayons.blue(e), err=True)
def import_requirements(r=None, dev=False):
from .patched.notpip._vendor import requests as pip_requests
from .patched.notpip._internal.req.req_file import parse_requirements
# Parse requirements.txt file with Pip's parser.
# Pip requires a `PipSession` which is a subclass of requests.Session.
# Since we're not making any network calls, it's initialized to nothing.
if r:
assert os.path.isfile(r)
# Default path, if none is provided.
if r is None:
r = project.requirements_location
with open(r, 'r') as f:
contents = f.read()
indexes = []
# Find and add extra indexes.
for line in contents.split('\n'):
if line.startswith(('-i ', '--index ', '--index-url ')):
indexes.append(line.split()[1])
reqs = [f for f in parse_requirements(r, session=pip_requests)]
for package in reqs:
if package.name not in BAD_PACKAGES:
if package.link is not None:
package_string = (
'-e {0}'.format(package.link) if package.editable else str(
package.link
)
)
project.add_package_to_pipfile(package_string, dev=dev)
else:
project.add_package_to_pipfile(str(package.req), dev=dev)
for index in indexes:
project.add_index_to_pipfile(index)
project.recase_pipfile()
def ensure_environment():
# Skip this on Windows...
if os.name != 'nt':
if 'LANG' not in os.environ:
click.echo(
'{0}: the environment variable {1} is not set!'
'\nWe recommend setting this in {2} (or equivalent) for '
'proper expected behavior.'.format(
crayons.red('Warning', bold=True),
crayons.normal('LANG', bold=True),
crayons.green('~/.profile'),
),
err=True,
)
def import_from_code(path='.'):
from pipreqs import pipreqs
rs = []
try:
for r in pipreqs.get_all_imports(path):
if r not in BAD_PACKAGES:
rs.append(r)
pkg_names = pipreqs.get_pkg_names(rs)
return [proper_case(r) for r in pkg_names]
except Exception:
return []
def ensure_pipfile(validate=True, skip_requirements=False, system=False):
"""Creates a Pipfile for the project, if it doesn't exist."""
global USING_DEFAULT_PYTHON, PIPENV_VIRTUALENV
# Assert Pipfile exists.
python = which('python') if not (USING_DEFAULT_PYTHON or system) else None
if project.pipfile_is_empty:
# Show an error message and exit if system is passed and no pipfile exists
if system and not PIPENV_VIRTUALENV:
click.echo(
'{0}: --system is intended to be used for pre-existing Pipfile '
'installation, not installation of specific packages. Aborting.'.format(
crayons.red('Warning', bold=True)
),
err=True,
)
sys.exit(1)
# If there's a requirements file, but no Pipfile...
if project.requirements_exists and not skip_requirements:
click.echo(
crayons.normal(
u'requirements.txt found, instead of Pipfile! Converting…',
bold=True,
)
)
# Create a Pipfile...
project.create_pipfile(python=python)
with spinner():
# Import requirements.txt.
import_requirements()
# Warn the user of side-effects.
click.echo(
u'{0}: Your {1} now contains pinned versions, if your {2} did. \n'
'We recommend updating your {1} to specify the {3} version, instead.'
''.format(
crayons.red('Warning', bold=True),
crayons.normal('Pipfile', bold=True),
crayons.normal('requirements.txt', bold=True),
crayons.normal('"*"', bold=True),
)
)
else:
click.echo(
crayons.normal(
u'Creating a Pipfile for this project…', bold=True
),
err=True,
)
# Create the pipfile if it doesn't exist.
project.create_pipfile(python=python)
# Validate the Pipfile's contents.
if validate and project.virtualenv_exists and not PIPENV_SKIP_VALIDATION:
# Ensure that Pipfile is using proper casing.
p = project.parsed_pipfile
changed = project.ensure_proper_casing()
# Write changes out to disk.
if changed:
click.echo(
crayons.normal(u'Fixing package names in Pipfile…', bold=True),
err=True,
)
project.write_toml(p)
def find_python_from_py(python):
"""Find a Python executable from on Windows.
Ask py.exe for its opinion.
"""
py = system_which('py')
if not py:
return None
version_args = ['-{0}'.format(python[0])]
if len(python) >= 2:
version_args.append('-{0}.{1}'.format(python[0], python[2]))
import subprocess
for ver_arg in reversed(version_args):
try:
python_exe = subprocess.check_output(
[py, ver_arg, '-c', 'import sys; print(sys.executable)']
)
except subprocess.CalledProcessError:
continue
if not isinstance(python_exe, str):
python_exe = python_exe.decode(sys.getdefaultencoding())
python_exe = python_exe.strip()
version = python_version(python_exe)
if (version or '').startswith(python):
return python_exe
def find_python_in_path(python):
"""Find a Python executable from a version number.
This uses the PATH environment variable to locate an appropriate Python.
"""
possibilities = ['python', 'python{0}'.format(python[0])]
if len(python) >= 2:
possibilities.extend(
[
'python{0}{1}'.format(python[0], python[2]),
'python{0}.{1}'.format(python[0], python[2]),
'python{0}.{1}m'.format(python[0], python[2]),
]
)
# Reverse the list, so we find specific ones first.
possibilities = reversed(possibilities)
for possibility in possibilities:
# Windows compatibility.
if os.name == 'nt':
possibility = '{0}.exe'.format(possibility)
pythons = system_which(possibility, mult=True)
for p in pythons:
version = python_version(p)
if (version or '').startswith(python):
return p
def find_a_system_python(python):
"""Finds a system python, given a version (e.g. 2 / 2.7 / 3.6.2), or a full path."""
if python.startswith('py'):
return system_which(python)
elif os.path.isabs(python):
return python
python_from_py = find_python_from_py(python)
if python_from_py:
return python_from_py
return find_python_in_path(python)
def ensure_python(three=None, python=None):
# Support for the PIPENV_PYTHON environment variable.
if PIPENV_PYTHON and python is False and three is None:
python = PIPENV_PYTHON
def abort():
click.echo(
'You can specify specific versions of Python with:\n {0}'.format(
crayons.red(
'$ pipenv --python {0}'.format(
os.sep.join(('path', 'to', 'python'))
)
)
),
err=True,
)
sys.exit(1)
def activate_pyenv():
import notpip
from notpip._vendor.packaging.version import parse as parse_version
"""Adds all pyenv installations to the PATH."""
if PYENV_INSTALLED:
if PYENV_ROOT:
pyenv_paths = {}
for found in glob(
'{0}{1}versions{1}*'.format(PYENV_ROOT, os.sep)
):
pyenv_paths[os.path.split(found)[1]] = '{0}{1}bin'.format(
found, os.sep
)
for version_str, pyenv_path in pyenv_paths.items():
version = parse_version(version_str)
if version.is_prerelease and pyenv_paths.get(
version.base_version
):
continue
add_to_path(pyenv_path)
else:
click.echo(
'{0}: PYENV_ROOT is not set. New python paths will '
'probably not be exported properly after installation.'
''.format(crayons.red('Warning', bold=True),),
err=True,
)
global USING_DEFAULT_PYTHON
# Add pyenv paths to PATH.
activate_pyenv()
path_to_python = None
USING_DEFAULT_PYTHON = (three is None and not python)
# Find out which python is desired.
if not python:
python = convert_three_to_python(three, python)
if not python:
python = project.required_python_version
if not python:
python = PIPENV_DEFAULT_PYTHON_VERSION
if python:
path_to_python = find_a_system_python(python)
if not path_to_python and python is not None:
# We need to install Python.
click.echo(
u'{0}: Python {1} {2}'.format(
crayons.red('Warning', bold=True),
crayons.blue(python),
u'was not found on your system…',
),
err=True,
)
# Pyenv is installed
if not PYENV_INSTALLED:
abort()
else:
if (not PIPENV_DONT_USE_PYENV) and (SESSION_IS_INTERACTIVE or PIPENV_YES):
version_map = {
# TODO: Keep this up to date!
# These versions appear incompatible with pew:
# '2.5': '2.5.6',
'2.6': '2.6.9',
'2.7': '2.7.15',
# '3.1': '3.1.5',
# '3.2': '3.2.6',
'3.3': '3.3.7',
'3.4': '3.4.8',
'3.5': '3.5.5',
'3.6': '3.6.5',
}
try:
if len(python.split('.')) == 2:
# Find the latest version of Python available.
version = version_map[python]
else:
version = python
except KeyError:
abort()
s = (
'{0} {1} {2}'.format(
'Would you like us to install',
crayons.green('CPython {0}'.format(version)),
'with pyenv?',
)
)
# Prompt the user to continue...
if not (PIPENV_YES or click.confirm(s, default=True)):
abort()
else:
# Tell the user we're installing Python.
click.echo(
u'{0} {1} {2} {3}{4}'.format(
crayons.normal(u'Installing', bold=True),
crayons.green(
u'CPython {0}'.format(version), bold=True
),
crayons.normal(u'with pyenv', bold=True),
crayons.normal(u'(this may take a few minutes)'),
crayons.normal(u'…', bold=True),
)
)
with spinner():
# Install Python.
c = delegator.run(
'pyenv install {0} -s'.format(version),
timeout=PIPENV_INSTALL_TIMEOUT,
block=False,
)
# Wait until the process has finished...
c.block()
try:
assert c.return_code == 0
except AssertionError:
click.echo(u'Something went wrong…')
click.echo(crayons.blue(c.err), err=True)
# Print the results, in a beautiful blue...
click.echo(crayons.blue(c.out), err=True)
# Add new paths to PATH.
activate_pyenv()
# Find the newly installed Python, hopefully.
path_to_python = find_a_system_python(version)
try:
assert python_version(path_to_python) == version
except AssertionError:
click.echo(
'{0}: The Python you just installed is not available on your {1}, apparently.'
''.format(
crayons.red('Warning', bold=True),
crayons.normal('PATH', bold=True),
),
err=True,
)
sys.exit(1)
return path_to_python
def ensure_virtualenv(three=None, python=None, site_packages=False):
"""Creates a virtualenv, if one doesn't exist."""
def abort():
sys.exit(1)
global USING_DEFAULT_PYTHON
if not project.virtualenv_exists:
try:
# Ensure environment variables are set properly.
ensure_environment()
# Ensure Python is available.
python = ensure_python(three=three, python=python)
# Create the virtualenv.
# Abort if --system (or running in a virtualenv).
if PIPENV_USE_SYSTEM:
click.echo(
crayons.red(
'You are attempting to re-create a virtualenv that '
'Pipenv did not create. Aborting.'
)
)
sys.exit(1)
do_create_virtualenv(python=python, site_packages=site_packages)
except KeyboardInterrupt:
# If interrupted, cleanup the virtualenv.
cleanup_virtualenv(bare=False)
sys.exit(1)
# If --three, --two, or --python were passed...
elif (python) or (three is not None) or (site_packages is not False):
USING_DEFAULT_PYTHON = False
# Ensure python is installed before deleting existing virtual env
ensure_python(three=three, python=python)
click.echo(crayons.red('Virtualenv already exists!'), err=True)
# If VIRTUAL_ENV is set, there is a possibility that we are
# going to remove the active virtualenv that the user cares
# about, so confirm first.
if 'VIRTUAL_ENV' in os.environ:
if not (
PIPENV_YES or
click.confirm('Remove existing virtualenv?', default=True)
):
abort()
click.echo(
crayons.normal(u'Removing existing virtualenv…', bold=True),
err=True,
)
# Remove the virtualenv.
cleanup_virtualenv(bare=True)
# Call this function again.
ensure_virtualenv(
three=three, python=python, site_packages=site_packages
)
def ensure_project(
three=None,
python=None,
validate=True,
system=False,
warn=True,
site_packages=False,
deploy=False,
skip_requirements=False,
):
"""Ensures both Pipfile and virtualenv exist for the project."""
# Automatically use an activated virtualenv.
if PIPENV_USE_SYSTEM:
system = True
if not project.pipfile_exists:
project.touch_pipfile()
# Skip virtualenv creation when --system was used.
if not system:
ensure_virtualenv(
three=three, python=python, site_packages=site_packages
)
if warn:
# Warn users if they are using the wrong version of Python.
if project.required_python_version:
path_to_python = which('python') or which('py')
if path_to_python and project.required_python_version not in (
python_version(path_to_python) or ''
):
click.echo(
'{0}: Your Pipfile requires {1} {2}, '
'but you are using {3} ({4}).'.format(
crayons.red('Warning', bold=True),
crayons.normal('python_version', bold=True),
crayons.blue(project.required_python_version),
crayons.blue(python_version(path_to_python)),
crayons.green(shorten_path(path_to_python)),
),
err=True,
)
if not deploy:
click.echo(
' {0} will surely fail.'
''.format(crayons.red('$ pipenv check')),
err=True,
)
else:
click.echo(crayons.red('Deploy aborted.'), err=True)
sys.exit(1)
# Ensure the Pipfile exists.
ensure_pipfile(validate=validate, skip_requirements=skip_requirements, system=system)
def shorten_path(location, bold=False):
"""Returns a visually shorter representation of a given system path."""
original = location
short = os.sep.join(
[
s[0] if len(s) > (len('2long4')) else s
for s in location.split(os.sep)
]
)
short = short.split(os.sep)
short[-1] = original.split(os.sep)[-1]
if bold:
short[-1] = str(crayons.normal(short[-1], bold=True))
return os.sep.join(short)
# return short
def do_where(virtualenv=False, bare=True):
"""Executes the where functionality."""
if not virtualenv:
location = project.pipfile_location
# Shorten the virtual display of the path to the virtualenv.
if not bare:
location = shorten_path(location)
if not location:
click.echo(
'No Pipfile present at project home. Consider running '
'{0} first to automatically generate a Pipfile for you.'
''.format(crayons.green('`pipenv install`')),
err=True,
)
elif not bare:
click.echo(
'Pipfile found at {0}.\n Considering this to be the project home.'
''.format(crayons.green(location)),
err=True,
)
pass
else:
click.echo(project.project_directory)
else:
location = project.virtualenv_location
if not bare:
click.echo(
'Virtualenv location: {0}'.format(crayons.green(location)),
err=True,
)
else:
click.echo(location)
def do_install_dependencies(
dev=False,
only=False,
bare=False,
requirements=False,
allow_global=False,
ignore_hashes=False,
skip_lock=False,
verbose=False,
concurrent=True,
requirements_dir=None,
):
""""Executes the install functionality.
If requirements is True, simply spits out a requirements format to stdout.
"""
def cleanup_procs(procs, concurrent):
for c in procs:
if concurrent:
c.block()
if 'Ignoring' in c.out:
click.echo(crayons.yellow(c.out.strip()))
if verbose:
click.echo(crayons.blue(c.out or c.err))
# The Installation failed...
if c.return_code != 0:
# Save the Failed Dependency for later.
failed_deps_list.append((c.dep, c.ignore_hash))
# Alert the user.
click.echo(
'{0} {1}! Will try again.'.format(
crayons.red('An error occurred while installing'),
crayons.green(c.dep.split('--hash')[0].strip()),
)
)
if requirements:
bare = True
blocking = (not concurrent)
# Load the lockfile if it exists, or if only is being used (e.g. lock is being used).
if skip_lock or only or not project.lockfile_exists:
if not bare:
click.echo(
crayons.normal(
u'Installing dependencies from Pipfile…', bold=True
)
)
lockfile = split_file(project._lockfile)
else:
with open(project.lockfile_location) as f:
lockfile = split_file(simplejson.load(f))
if not bare:
click.echo(
crayons.normal(
u'Installing dependencies from Pipfile.lock ({0})…'.format(
lockfile['_meta'].get('hash', {}).get('sha256')[-6:]
),
bold=True,
)
)
# Allow pip to resolve dependencies when in skip-lock mode.
no_deps = (not skip_lock)
deps_list, dev_deps_list = merge_deps(
lockfile,
project,
dev=dev,
requirements=requirements,
ignore_hashes=ignore_hashes,
blocking=blocking,
only=only,
)
failed_deps_list = []
if requirements:
# Comment out packages that shouldn't be included in
# requirements.txt, for pip9.
# Additional package selectors, specific to pip's --hash checking mode.
for l in (deps_list, dev_deps_list):
for i, dep in enumerate(l):
l[i] = list(l[i])
if '--hash' in l[i][0]:
l[i][0] = (l[i][0].split('--hash')[0].strip())
index_args = prepare_pip_source_args(project.sources)
index_args = ' '.join(index_args).replace(' -', '\n-')
# Output only default dependencies
click.echo(index_args)
if not dev:
click.echo('\n'.join(d[0] for d in sorted(deps_list)))
sys.exit(0)
# Output only dev dependencies
if dev:
click.echo('\n'.join(d[0] for d in sorted(dev_deps_list)))
sys.exit(0)
procs = []
deps_list_bar = progress.bar(
deps_list, label=INSTALL_LABEL if os.name != 'nt' else ''
)
for dep, ignore_hash, block in deps_list_bar:
if len(procs) < PIPENV_MAX_SUBPROCESS:
# Use a specific index, if specified.
dep, index = split_argument(dep, short='i', long_='index', num=1)
dep, extra_indexes = split_argument(dep, long_='extra-index-url')
# Install the module.
c = pip_install(
dep,
ignore_hashes=ignore_hash,
allow_global=allow_global,
no_deps=no_deps,
verbose=verbose,
block=block,
index=index,
requirements_dir=requirements_dir,
extra_indexes=extra_indexes,
)
c.dep = dep
c.ignore_hash = ignore_hash
procs.append(c)
if len(procs) >= PIPENV_MAX_SUBPROCESS or len(procs) == len(deps_list):
cleanup_procs(procs, concurrent)
procs = []
cleanup_procs(procs, concurrent)
# Iterate over the hopefully-poorly-packaged dependencies...
if failed_deps_list:
click.echo(
crayons.normal(
u'Installing initially–failed dependencies…', bold=True
)
)
for dep, ignore_hash in progress.bar(
failed_deps_list, label=INSTALL_LABEL2
):
# Use a specific index, if specified.
dep, index = split_argument(dep, short='i', long_='index', num=1)
dep, extra_indexes = split_argument(dep, long_='extra-index-url')
# Install the module.
c = pip_install(
dep,
ignore_hashes=ignore_hash,
allow_global=allow_global,
no_deps=no_deps,
verbose=verbose,
index=index,
requirements_dir=requirements_dir,
extra_indexes=extra_indexes,
)
# The Installation failed...
if c.return_code != 0:
# We echo both c.out and c.err because pip returns error details on out.
click.echo(crayons.blue(format_pip_output(c.out)))
click.echo(crayons.blue(format_pip_error(c.err)), err=True)
# Return the subprocess' return code.
sys.exit(c.return_code)
else:
click.echo(
'{0} {1}{2}'.format(
crayons.green('Success installing'),
crayons.green(dep.split('--hash')[0].strip()),
crayons.green('!'),
)
)
def convert_three_to_python(three, python):
"""Converts a Three flag into a Python flag, and raises customer warnings
in the process, if needed.
"""
if not python:
if three is False:
return '2'
elif three is True:
return '3'
else:
return python
def do_create_virtualenv(python=None, site_packages=False):
"""Creates a virtualenv."""
click.echo(
crayons.normal(u'Creating a virtualenv for this project…', bold=True),
err=True,
)
click.echo(u'Pipfile: {0}'.format(
crayons.red(project.pipfile_location, bold=True),
), err=True)
# The user wants the virtualenv in the project.
if project.is_venv_in_project():
cmd = [
sys.executable, '-m', 'virtualenv',
project.virtualenv_location,
'--prompt=({0})'.format(project.name),
]
# Pass site-packages flag to virtualenv, if desired...
if site_packages:
cmd.append('--system-site-packages')
else:
# Default: use pew.
cmd = [
sys.executable,
'-m',
'pipenv.pew',
'new',
project.virtualenv_name,
'-d',
'-a',
project.project_directory,
]
# Default to using sys.executable, if Python wasn't provided.
if not python:
python = sys.executable
click.echo(
u'{0} {1} {3} {2}'.format(
crayons.normal('Using', bold=True),
crayons.red(python, bold=True),
crayons.normal(u'to create virtualenv…', bold=True),
crayons.green('({0})'.format(python_version(python))),
),
err=True,
)
cmd = cmd + ['-p', python]
# Actually create the virtualenv.
with spinner():
try:
c = delegator.run(cmd, block=False, timeout=PIPENV_TIMEOUT)
except OSError:
click.echo(
'{0}: it looks like {1} is not in your {2}. '
'We cannot continue until this is resolved.'
''.format(
crayons.red('Warning', bold=True),
crayons.red(cmd[0]),
crayons.normal('PATH', bold=True),
),
err=True,
)
sys.exit(1)
click.echo(crayons.blue(c.out), err=True)
# Enable site-packages, if desired...
if not project.is_venv_in_project() and site_packages:
click.echo(
crayons.normal(u'Making site-packages available…', bold=True),
err=True,
)
os.environ['VIRTUAL_ENV'] = project.virtualenv_location
delegator.run('pipenv run pewtwo toggleglobalsitepackages')
del os.environ['VIRTUAL_ENV']
# Say where the virtualenv is.
do_where(virtualenv=True, bare=False)
def parse_download_fname(fname, name):
fname, fextension = os.path.splitext(fname)
if fextension == '.whl':
fname = '-'.join(fname.split('-')[:-3])
if fname.endswith('.tar'):
fname, _ = os.path.splitext(fname)
# Substring out package name (plus dash) from file name to get version.
version = fname[len(name) + 1:]
# Ignore implicit post releases in version number.
if '-' in version and version.split('-')[1].isdigit():
version = version.split('-')[0]
return version
def get_downloads_info(names_map, section):
info = []
p = project.parsed_pipfile
for fname in os.listdir(project.download_location):
# Get name from filename mapping.
name = Requirement.from_line(names_map[fname]).name
# Get the version info from the filenames.
version = parse_download_fname(fname, name)
# Get the hash of each file.
cmd = '{0} hash "{1}"'.format(
escape_grouped_arguments(which_pip()),
os.sep.join([project.download_location, fname]),
)
c = delegator.run(cmd)
hash = c.out.split('--hash=')[1].strip()
# Verify we're adding the correct version from Pipfile
# and not one from a dependency.
specified_version = p[section].get(name, '')
if is_required_version(version, specified_version):
info.append(dict(name=name, version=version, hash=hash))
return info
def do_lock(
verbose=False,
system=False,
clear=False,