forked from pypa/virtualenv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
virtualenv.py
executable file
·2628 lines (2303 loc) · 104 KB
/
virtualenv.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 python
"""Create a "virtual" Python installation"""
# fmt: off
import os # isort:skip
import sys # isort:skip
# If we are running in a new interpreter to create a virtualenv,
# we do NOT want paths from our existing location interfering with anything,
# So we remove this file's directory from sys.path - most likely to be
# the previous interpreter's site-packages. Solves #705, #763, #779
if os.environ.get("VIRTUALENV_INTERPRETER_RUNNING"):
for path in sys.path[:]:
if os.path.realpath(os.path.dirname(__file__)) == os.path.realpath(path):
sys.path.remove(path)
# fmt: on
import ast
import base64
import codecs
import contextlib
import distutils.spawn
import distutils.sysconfig
import errno
import glob
import logging
import optparse
import os
import re
import shutil
import struct
import subprocess
import sys
import tempfile
import textwrap
import zipfile
import zlib
from distutils.util import strtobool
from os.path import join
try:
import ConfigParser
except ImportError:
# noinspection PyPep8Naming
import configparser as ConfigParser
__version__ = "16.7.7"
virtualenv_version = __version__ # legacy
DEBUG = os.environ.get("_VIRTUALENV_DEBUG", None) == "1"
if sys.version_info < (2, 7):
print("ERROR: {}".format(sys.exc_info()[1]))
print("ERROR: this script requires Python 2.7 or greater.")
sys.exit(101)
HERE = os.path.dirname(os.path.abspath(__file__))
IS_ZIPAPP = os.path.isfile(HERE)
try:
# noinspection PyUnresolvedReferences,PyUnboundLocalVariable
basestring
except NameError:
basestring = str
VERSION = "{}.{}".format(*sys.version_info)
PY_VERSION = "python{}.{}".format(*sys.version_info)
IS_PYPY = hasattr(sys, "pypy_version_info")
IS_WIN = sys.platform == "win32"
IS_CYGWIN = sys.platform == "cygwin"
IS_DARWIN = sys.platform == "darwin"
ABI_FLAGS = getattr(sys, "abiflags", "")
USER_DIR = os.path.expanduser("~")
if IS_WIN:
DEFAULT_STORAGE_DIR = os.path.join(USER_DIR, "virtualenv")
else:
DEFAULT_STORAGE_DIR = os.path.join(USER_DIR, ".virtualenv")
DEFAULT_CONFIG_FILE = os.path.join(DEFAULT_STORAGE_DIR, "virtualenv.ini")
if IS_PYPY:
EXPECTED_EXE = "pypy"
else:
EXPECTED_EXE = "python"
# Return a mapping of version -> Python executable
# Only provided for Windows, where the information in the registry is used
if not IS_WIN:
def get_installed_pythons():
return {}
else:
try:
import winreg
except ImportError:
# noinspection PyUnresolvedReferences
import _winreg as winreg
def get_installed_pythons():
final_exes = dict()
# Grab exes from 32-bit registry view
exes = _get_installed_pythons_for_view("-32", winreg.KEY_WOW64_32KEY)
# Grab exes from 64-bit registry view
exes_64 = _get_installed_pythons_for_view("-64", winreg.KEY_WOW64_64KEY)
# Check if exes are unique
if set(exes.values()) != set(exes_64.values()):
exes.update(exes_64)
# Create dict with all versions found
for version, bitness in sorted(exes):
exe = exes[(version, bitness)]
# Add minor version (X.Y-32 or X.Y-64)
final_exes[version + bitness] = exe
# Add minor extensionless version (X.Y); 3.2-64 wins over 3.2-32
final_exes[version] = exe
# Add major version (X-32 or X-64)
final_exes[version[0] + bitness] = exe
# Add major extensionless version (X); 3.3-32 wins over 3.2-64
final_exes[version[0]] = exe
return final_exes
def _get_installed_pythons_for_view(bitness, view):
exes = dict()
# If both system and current user installations are found for a
# particular Python version, the current user one is used
for key in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
try:
python_core = winreg.OpenKey(key, "Software\\Python\\PythonCore", 0, view | winreg.KEY_READ)
except WindowsError:
# No registered Python installations
continue
i = 0
while True:
try:
version = winreg.EnumKey(python_core, i)
i += 1
try:
at_path = winreg.QueryValue(python_core, "{}\\InstallPath".format(version))
except WindowsError:
continue
# Remove bitness from version
if version.endswith(bitness):
version = version[: -len(bitness)]
exes[(version, bitness)] = join(at_path, "python.exe")
except WindowsError:
break
winreg.CloseKey(python_core)
return exes
REQUIRED_MODULES = [
"os",
"posix",
"posixpath",
"nt",
"ntpath",
"genericpath",
"fnmatch",
"locale",
"encodings",
"codecs",
"stat",
"UserDict",
"readline",
"copy_reg",
"types",
"re",
"sre",
"sre_parse",
"sre_constants",
"sre_compile",
"zlib",
]
REQUIRED_FILES = ["lib-dynload", "config"]
MAJOR, MINOR = sys.version_info[:2]
if MAJOR == 2:
if MINOR >= 6:
REQUIRED_MODULES.extend(["warnings", "linecache", "_abcoll", "abc"])
if MINOR >= 7:
REQUIRED_MODULES.extend(["_weakrefset"])
elif MAJOR == 3:
# Some extra modules are needed for Python 3, but different ones
# for different versions.
REQUIRED_MODULES.extend(
[
"_abcoll",
"warnings",
"linecache",
"abc",
"io",
"_weakrefset",
"copyreg",
"tempfile",
"random",
"__future__",
"collections",
"keyword",
"tarfile",
"shutil",
"struct",
"copy",
"tokenize",
"token",
"functools",
"heapq",
"bisect",
"weakref",
"reprlib",
]
)
if MINOR >= 2:
REQUIRED_FILES[-1] = "config-{}".format(MAJOR)
if MINOR >= 3:
import sysconfig
platform_dir = sysconfig.get_config_var("PLATDIR")
REQUIRED_FILES.append(platform_dir)
REQUIRED_MODULES.extend(["base64", "_dummy_thread", "hashlib", "hmac", "imp", "importlib", "rlcompleter"])
if MINOR >= 4:
REQUIRED_MODULES.extend(["operator", "_collections_abc", "_bootlocale"])
if MINOR >= 6:
REQUIRED_MODULES.extend(["enum"])
if IS_PYPY:
# these are needed to correctly display the exceptions that may happen
# during the bootstrap
REQUIRED_MODULES.extend(["traceback", "linecache"])
if MAJOR == 3:
# _functools is needed to import locale during stdio initialization and
# needs to be copied on PyPy because it's not built in
REQUIRED_MODULES.append("_functools")
class Logger(object):
"""
Logging object for use in command-line script. Allows ranges of
levels, to avoid some redundancy of displayed information.
"""
DEBUG = logging.DEBUG
INFO = logging.INFO
NOTIFY = (logging.INFO + logging.WARN) / 2
WARN = WARNING = logging.WARN
ERROR = logging.ERROR
FATAL = logging.FATAL
LEVELS = [DEBUG, INFO, NOTIFY, WARN, ERROR, FATAL]
def __init__(self, consumers):
self.consumers = consumers
self.indent = 0
self.in_progress = None
self.in_progress_hanging = False
def debug(self, msg, *args, **kw):
self.log(self.DEBUG, msg, *args, **kw)
def info(self, msg, *args, **kw):
self.log(self.INFO, msg, *args, **kw)
def notify(self, msg, *args, **kw):
self.log(self.NOTIFY, msg, *args, **kw)
def warn(self, msg, *args, **kw):
self.log(self.WARN, msg, *args, **kw)
def error(self, msg, *args, **kw):
self.log(self.ERROR, msg, *args, **kw)
def fatal(self, msg, *args, **kw):
self.log(self.FATAL, msg, *args, **kw)
def log(self, level, msg, *args, **kw):
if args:
if kw:
raise TypeError("You may give positional or keyword arguments, not both")
args = args or kw
rendered = None
for consumer_level, consumer in self.consumers:
if self.level_matches(level, consumer_level):
if self.in_progress_hanging and consumer in (sys.stdout, sys.stderr):
self.in_progress_hanging = False
print("")
sys.stdout.flush()
if rendered is None:
if args:
rendered = msg % args
else:
rendered = msg
rendered = " " * self.indent + rendered
if hasattr(consumer, "write"):
consumer.write(rendered + "\n")
else:
consumer(rendered)
def start_progress(self, msg):
assert not self.in_progress, "Tried to start_progress({!r}) while in_progress {!r}".format(
msg, self.in_progress
)
if self.level_matches(self.NOTIFY, self._stdout_level()):
print(msg)
sys.stdout.flush()
self.in_progress_hanging = True
else:
self.in_progress_hanging = False
self.in_progress = msg
def end_progress(self, msg="done."):
assert self.in_progress, "Tried to end_progress without start_progress"
if self.stdout_level_matches(self.NOTIFY):
if not self.in_progress_hanging:
# Some message has been printed out since start_progress
print("...{}{}".format(self.in_progress, msg))
sys.stdout.flush()
else:
print(msg)
sys.stdout.flush()
self.in_progress = None
self.in_progress_hanging = False
def show_progress(self):
"""If we are in a progress scope, and no log messages have been
shown, write out another '.'"""
if self.in_progress_hanging:
print(".")
sys.stdout.flush()
def stdout_level_matches(self, level):
"""Returns true if a message at this level will go to stdout"""
return self.level_matches(level, self._stdout_level())
def _stdout_level(self):
"""Returns the level that stdout runs at"""
for level, consumer in self.consumers:
if consumer is sys.stdout:
return level
return self.FATAL
@staticmethod
def level_matches(level, consumer_level):
"""
>>> l = Logger([])
>>> l.level_matches(3, 4)
False
>>> l.level_matches(3, 2)
True
>>> l.level_matches(slice(None, 3), 3)
False
>>> l.level_matches(slice(None, 3), 2)
True
>>> l.level_matches(slice(1, 3), 1)
True
>>> l.level_matches(slice(2, 3), 1)
False
"""
if isinstance(level, slice):
start, stop = level.start, level.stop
if start is not None and start > consumer_level:
return False
if stop is not None and stop <= consumer_level:
return False
return True
else:
return level >= consumer_level
@classmethod
def level_for_integer(cls, level):
levels = cls.LEVELS
if level < 0:
return levels[0]
if level >= len(levels):
return levels[-1]
return levels[level]
# create a silent logger just to prevent this from being undefined
# will be overridden with requested verbosity main() is called.
logger = Logger([(Logger.LEVELS[-1], sys.stdout)])
def mkdir(at_path):
if not os.path.exists(at_path):
logger.info("Creating %s", at_path)
os.makedirs(at_path)
else:
logger.info("Directory %s already exists", at_path)
def copy_file_or_folder(src, dest, symlink=True):
if os.path.isdir(src):
shutil.copytree(src, dest, symlink)
else:
shutil.copy2(src, dest)
def copyfile(src, dest, symlink=True):
if not os.path.exists(src):
# Some bad symlink in the src
logger.warn("Cannot find file %s (bad symlink)", src)
return
if os.path.exists(dest):
logger.debug("File %s already exists", dest)
return
if not os.path.exists(os.path.dirname(dest)):
logger.info("Creating parent directories for %s", os.path.dirname(dest))
os.makedirs(os.path.dirname(dest))
if symlink and hasattr(os, "symlink") and not IS_WIN:
logger.info("Symlinking %s", dest)
try:
os.symlink(os.path.realpath(src), dest)
except (OSError, NotImplementedError):
logger.info("Symlinking failed, copying to %s", dest)
copy_file_or_folder(src, dest, symlink)
else:
logger.info("Copying to %s", dest)
copy_file_or_folder(src, dest, symlink)
def writefile(dest, content, overwrite=True):
if not os.path.exists(dest):
logger.info("Writing %s", dest)
with open(dest, "wb") as f:
f.write(content.encode("utf-8"))
return
else:
with open(dest, "rb") as f:
c = f.read()
if c != content.encode("utf-8"):
if not overwrite:
logger.notify("File %s exists with different content; not overwriting", dest)
return
logger.notify("Overwriting %s with new content", dest)
with open(dest, "wb") as f:
f.write(content.encode("utf-8"))
else:
logger.info("Content %s already in place", dest)
def rm_tree(folder):
if os.path.exists(folder):
logger.notify("Deleting tree %s", folder)
shutil.rmtree(folder)
else:
logger.info("Do not need to delete %s; already gone", folder)
def make_exe(fn):
if hasattr(os, "chmod"):
old_mode = os.stat(fn).st_mode & 0xFFF # 0o7777
new_mode = (old_mode | 0x16D) & 0xFFF # 0o555, 0o7777
os.chmod(fn, new_mode)
logger.info("Changed mode of %s to %s", fn, oct(new_mode))
def _find_file(filename, folders):
for folder in reversed(folders):
files = glob.glob(os.path.join(folder, filename))
if files and os.path.isfile(files[0]):
return True, files[0]
return False, filename
@contextlib.contextmanager
def virtualenv_support_dirs():
"""Context manager yielding either [virtualenv_support_dir] or []"""
# normal filesystem installation
if os.path.isdir(join(HERE, "virtualenv_support")):
yield [join(HERE, "virtualenv_support")]
elif IS_ZIPAPP:
tmpdir = tempfile.mkdtemp()
try:
with zipfile.ZipFile(HERE) as zipf:
for member in zipf.namelist():
if os.path.dirname(member) == "virtualenv_support":
zipf.extract(member, tmpdir)
yield [join(tmpdir, "virtualenv_support")]
finally:
shutil.rmtree(tmpdir)
# probably a bootstrap script
elif os.path.splitext(os.path.dirname(__file__))[0] != "virtualenv":
try:
# noinspection PyUnresolvedReferences
import virtualenv
except ImportError:
yield []
else:
yield [join(os.path.dirname(virtualenv.__file__), "virtualenv_support")]
# we tried!
else:
yield []
class UpdatingDefaultsHelpFormatter(optparse.IndentedHelpFormatter):
"""
Custom help formatter for use in ConfigOptionParser that updates
the defaults before expanding them, allowing them to show up correctly
in the help listing
"""
def expand_default(self, option):
if self.parser is not None:
self.parser.update_defaults(self.parser.defaults)
return optparse.IndentedHelpFormatter.expand_default(self, option)
class ConfigOptionParser(optparse.OptionParser):
"""
Custom option parser which updates its defaults by checking the
configuration files and environmental variables
"""
def __init__(self, *args, **kwargs):
self.config = ConfigParser.RawConfigParser()
self.files = self.get_config_files()
self.config.read(self.files)
optparse.OptionParser.__init__(self, *args, **kwargs)
@staticmethod
def get_config_files():
config_file = os.environ.get("VIRTUALENV_CONFIG_FILE", False)
if config_file and os.path.exists(config_file):
return [config_file]
return [DEFAULT_CONFIG_FILE]
def update_defaults(self, defaults):
"""
Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists).
"""
# Then go and look for the other sources of configuration:
config = {}
# 1. config files
config.update(dict(self.get_config_section("virtualenv")))
# 2. environmental variables
config.update(dict(self.get_environ_vars()))
# Then set the options with those values
for key, val in config.items():
key = key.replace("_", "-")
if not key.startswith("--"):
key = "--{}".format(key) # only prefer long opts
option = self.get_option(key)
if option is not None:
# ignore empty values
if not val:
continue
# handle multiline configs
if option.action == "append":
val = val.split()
else:
option.nargs = 1
if option.action == "store_false":
val = not strtobool(val)
elif option.action in ("store_true", "count"):
val = strtobool(val)
try:
val = option.convert_value(key, val)
except optparse.OptionValueError:
e = sys.exc_info()[1]
print("An error occurred during configuration: {!r}".format(e))
sys.exit(3)
defaults[option.dest] = val
return defaults
def get_config_section(self, name):
"""
Get a section of a configuration
"""
if self.config.has_section(name):
return self.config.items(name)
return []
def get_environ_vars(self, prefix="VIRTUALENV_"):
"""
Returns a generator with all environmental vars with prefix VIRTUALENV
"""
for key, val in os.environ.items():
if key.startswith(prefix):
yield (key.replace(prefix, "").lower(), val)
def get_default_values(self):
"""
Overriding to make updating the defaults after instantiation of
the option parser possible, update_defaults() does the dirty work.
"""
if not self.process_default_values:
# Old, pre-Optik 1.5 behaviour.
return optparse.Values(self.defaults)
defaults = self.update_defaults(self.defaults.copy()) # ours
for option in self._get_all_options():
default = defaults.get(option.dest)
if isinstance(default, basestring):
opt_str = option.get_opt_string()
defaults[option.dest] = option.check_value(opt_str, default)
return optparse.Values(defaults)
def main():
parser = ConfigOptionParser(
version=virtualenv_version, usage="%prog [OPTIONS] DEST_DIR", formatter=UpdatingDefaultsHelpFormatter()
)
parser.add_option(
"-v", "--verbose", action="count", dest="verbose", default=5 if DEBUG else 0, help="Increase verbosity."
)
parser.add_option("-q", "--quiet", action="count", dest="quiet", default=0, help="Decrease verbosity.")
parser.add_option(
"-p",
"--python",
dest="python",
metavar="PYTHON_EXE",
help="The Python interpreter to use, e.g., --python=python3.5 will use the python3.5 "
"interpreter to create the new environment. The default is the interpreter that "
"virtualenv was installed with ({})".format(sys.executable),
)
parser.add_option(
"--clear", dest="clear", action="store_true", help="Clear out the non-root install and start from scratch."
)
parser.set_defaults(system_site_packages=False)
parser.add_option(
"--no-site-packages",
dest="system_site_packages",
action="store_false",
help="DEPRECATED. Retained only for backward compatibility. "
"Not having access to global site-packages is now the default behavior.",
)
parser.add_option(
"--system-site-packages",
dest="system_site_packages",
action="store_true",
help="Give the virtual environment access to the global site-packages.",
)
parser.add_option(
"--always-copy",
dest="symlink",
action="store_false",
default=True,
help="Always copy files rather than symlinking.",
)
parser.add_option(
"--relocatable",
dest="relocatable",
action="store_true",
help="Make an EXISTING virtualenv environment relocatable. "
"This fixes up scripts and makes all .pth files relative.",
)
parser.add_option(
"--no-setuptools",
dest="no_setuptools",
action="store_true",
help="Do not install setuptools in the new virtualenv.",
)
parser.add_option("--no-pip", dest="no_pip", action="store_true", help="Do not install pip in the new virtualenv.")
parser.add_option(
"--no-wheel", dest="no_wheel", action="store_true", help="Do not install wheel in the new virtualenv."
)
parser.add_option(
"--extra-search-dir",
dest="search_dirs",
action="append",
metavar="DIR",
default=[],
help="Directory to look for setuptools/pip distributions in. " "This option can be used multiple times.",
)
parser.add_option(
"--download",
dest="download",
default=True,
action="store_true",
help="Download pre-installed packages from PyPI.",
)
parser.add_option(
"--no-download",
"--never-download",
dest="download",
action="store_false",
help="Do not download pre-installed packages from PyPI.",
)
parser.add_option("--prompt", dest="prompt", help="Provides an alternative prompt prefix for this environment.")
parser.add_option(
"--setuptools",
dest="setuptools",
action="store_true",
help="DEPRECATED. Retained only for backward compatibility. This option has no effect.",
)
parser.add_option(
"--distribute",
dest="distribute",
action="store_true",
help="DEPRECATED. Retained only for backward compatibility. This option has no effect.",
)
parser.add_option(
"--unzip-setuptools",
action="store_true",
help="DEPRECATED. Retained only for backward compatibility. This option has no effect.",
)
if "extend_parser" in globals():
# noinspection PyUnresolvedReferences
extend_parser(parser) # noqa: F821
options, args = parser.parse_args()
global logger
if "adjust_options" in globals():
# noinspection PyUnresolvedReferences
adjust_options(options, args) # noqa: F821
verbosity = options.verbose - options.quiet
logger = Logger([(Logger.level_for_integer(2 - verbosity), sys.stdout)])
def should_reinvoke(options):
"""Do we need to reinvoke ourself?"""
# Did the user specify the --python option?
if options.python and not os.environ.get("VIRTUALENV_INTERPRETER_RUNNING"):
interpreter = resolve_interpreter(options.python)
if interpreter != sys.executable:
# The user specified a different interpreter, so we have to reinvoke.
return interpreter
# At this point, we know the user wants to use sys.executable to create the
# virtual environment. But on Windows, sys.executable may be a venv redirector,
# in which case we still need to locate the underlying actual interpreter, and
# reinvoke using that.
if IS_WIN:
# OK. Now things get really fun...
#
# If we are running from a venv, with a redirector, then what happens is as
# follows:
#
# 1. The redirector sets __PYVENV_LAUNCHER__ in the environment to point
# to the redirector executable.
# 2. The redirector launches the "base" Python (from the home value in
# pyvenv.cfg).
# 3. The base Python executable sees __PYVENV_LAUNCHER__ in the environment
# and sets sys.executable to that value.
# 4. If site.py gets run, it sees __PYVENV_LAUNCHER__, and sets
# sys._base_executable to _winapi.GetModuleFileName(0) and removes
# __PYVENV_LAUNCHER__.
#
# Unfortunately, that final step (site.py) may not happen. There are 2 key
# times when that is the case:
#
# 1. Python 3.7.2, which had the redirector but not the site.py code.
# 2. Running a venv from a virtualenv, which uses virtualenv's custom
# site.py.
#
# So, we check for sys._base_executable, but if it's not present and yet we
# have __PYVENV_LAUNCHER__, we do what site.py would have done and get our
# interpreter from GetModuleFileName(0). We also remove __PYVENV_LAUNCHER__
# from the environment, to avoid loops (actually, mainly because site.py
# does so, and my head hurts enough buy now that I just want to be safe!)
# In Python 3.7.4, the rules changed so that sys._base_executable is always
# set. So we now only return sys._base_executable if it's set *and does not
# match sys.executable* (we still have to check that it's set, as we need to
# support Python 3.7.3 and earlier).
# Phew.
if getattr(sys, "_base_executable", sys.executable) != sys.executable:
return sys._base_executable
if "__PYVENV_LAUNCHER__" in os.environ:
import _winapi
del os.environ["__PYVENV_LAUNCHER__"]
return _winapi.GetModuleFileName(0)
# We don't need to reinvoke
return None
interpreter = should_reinvoke(options)
if interpreter is None:
# We don't need to reinvoke - if the user asked us to, tell them why we
# aren't.
if options.python:
logger.warn("Already using interpreter {}".format(sys.executable))
else:
env = os.environ.copy()
logger.notify("Running virtualenv with interpreter {}".format(interpreter))
env["VIRTUALENV_INTERPRETER_RUNNING"] = "true"
# Remove the variable __PYVENV_LAUNCHER__ if it's present, as it causes the
# interpreter to redirect back to the virtual environment.
if "__PYVENV_LAUNCHER__" in env:
del env["__PYVENV_LAUNCHER__"]
file = __file__
if file.endswith(".pyc"):
file = file[:-1]
elif IS_ZIPAPP:
file = HERE
sub_process_call = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env)
raise SystemExit(sub_process_call.wait())
if not args:
print("You must provide a DEST_DIR")
parser.print_help()
sys.exit(2)
if len(args) > 1:
print("There must be only one argument: DEST_DIR (you gave {})".format(" ".join(args)))
parser.print_help()
sys.exit(2)
home_dir = args[0]
if os.path.exists(home_dir) and os.path.isfile(home_dir):
logger.fatal("ERROR: File already exists and is not a directory.")
logger.fatal("Please provide a different path or delete the file.")
sys.exit(3)
if os.pathsep in home_dir:
logger.fatal("ERROR: target path contains the operating system path separator '{}'".format(os.pathsep))
logger.fatal("This is not allowed as would make the activation scripts unusable.".format(os.pathsep))
sys.exit(3)
if os.environ.get("WORKING_ENV"):
logger.fatal("ERROR: you cannot run virtualenv while in a working env")
logger.fatal("Please deactivate your working env, then re-run this script")
sys.exit(3)
if "PYTHONHOME" in os.environ:
logger.warn("PYTHONHOME is set. You *must* activate the virtualenv before using it")
del os.environ["PYTHONHOME"]
if options.relocatable:
make_environment_relocatable(home_dir)
return
with virtualenv_support_dirs() as search_dirs:
create_environment(
home_dir,
site_packages=options.system_site_packages,
clear=options.clear,
prompt=options.prompt,
search_dirs=search_dirs + options.search_dirs,
download=options.download,
no_setuptools=options.no_setuptools,
no_pip=options.no_pip,
no_wheel=options.no_wheel,
symlink=options.symlink,
)
if "after_install" in globals():
# noinspection PyUnresolvedReferences
after_install(options, home_dir) # noqa: F821
def call_subprocess(
cmd,
show_stdout=True,
filter_stdout=None,
cwd=None,
raise_on_return_code=True,
extra_env=None,
remove_from_env=None,
stdin=None,
):
cmd_parts = []
for part in cmd:
if len(part) > 45:
part = part[:20] + "..." + part[-20:]
if " " in part or "\n" in part or '"' in part or "'" in part:
part = '"{}"'.format(part.replace('"', '\\"'))
if hasattr(part, "decode"):
try:
part = part.decode(sys.getdefaultencoding())
except UnicodeDecodeError:
part = part.decode(sys.getfilesystemencoding())
cmd_parts.append(part)
cmd_desc = " ".join(cmd_parts)
if show_stdout:
stdout = None
else:
stdout = subprocess.PIPE
logger.debug("Running command {}".format(cmd_desc))
if extra_env or remove_from_env:
env = os.environ.copy()
if extra_env:
env.update(extra_env)
if remove_from_env:
for var_name in remove_from_env:
env.pop(var_name, None)
else:
env = None
try:
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT,
stdin=None if stdin is None else subprocess.PIPE,
stdout=stdout,
cwd=cwd,
env=env,
)
except Exception:
e = sys.exc_info()[1]
logger.fatal("Error {} while executing command {}".format(e, cmd_desc))
raise
all_output = []
if stdout is not None:
if stdin is not None:
with proc.stdin:
proc.stdin.write(stdin)
encoding = sys.getdefaultencoding()
fs_encoding = sys.getfilesystemencoding()
with proc.stdout as stdout:
while 1:
line = stdout.readline()
try:
line = line.decode(encoding)
except UnicodeDecodeError:
line = line.decode(fs_encoding)
if not line:
break
line = line.rstrip()
all_output.append(line)
if filter_stdout:
level = filter_stdout(line)
if isinstance(level, tuple):
level, line = level
logger.log(level, line)
if not logger.stdout_level_matches(level):
logger.show_progress()
else:
logger.info(line)
else:
proc.communicate(stdin)
proc.wait()
if proc.returncode:
if raise_on_return_code:
if all_output:
logger.notify("Complete output from command {}:".format(cmd_desc))
logger.notify("\n".join(all_output) + "\n----------------------------------------")
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
else:
logger.warn("Command {} had error code {}".format(cmd_desc, proc.returncode))
return all_output
def filter_install_output(line):
if line.strip().startswith("running"):
return Logger.INFO
return Logger.DEBUG
def find_wheels(projects, search_dirs):
"""Find wheels from which we can import PROJECTS.
Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
a list of the first wheel found for each PROJECT
"""
wheels = []
# Look through SEARCH_DIRS for the first suitable wheel. Don't bother
# about version checking here, as this is simply to get something we can
# then use to install the correct version.
for project in projects:
for dirname in search_dirs:
# This relies on only having "universal" wheels available.
# The pattern could be tightened to require -py2.py3-none-any.whl.
files = glob.glob(os.path.join(dirname, "{}-*.whl".format(project)))
if files:
versions = sorted(
[(tuple(int(i) for i in os.path.basename(f).split("-")[1].split(".")), f) for f in files]
)
if project == "pip" and sys.version_info[0:2] == (3, 4):
wheel = next(p for v, p in versions if v <= (19, 1, 1))
else:
wheel = versions[0][1]
wheels.append(wheel)