diff --git a/Pipfile.lock b/Pipfile.lock index 21b32705..6484ca24 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -5,20 +5,22 @@ }, "pipfile-spec": 6, "requires": {}, - "sources": [{ - "name": "pypi", - "url": "https://pypi.org/simple", - "verify_ssl": true - }] + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] }, "default": {}, "develop": { "alabaster": { "hashes": [ - "sha256:2eef172f44e8d301d25aff8068fddd65f767a3f04b5f15b0f4922f113aa1c732", - "sha256:37cdcb9e9954ed60912ebc1ca12a9d12178c26637abdf124e3cde2341c257fe0" + "sha256:674bb3bab080f598371f4443c5008cbfeb1a5e622dd312395d2d82af2c54c456", + "sha256:b63b1f4dc77c074d386752ec4a8a7517600f6c0db8cd42980cae17ab7b3275d7" ], - "version": "==0.7.10" + "version": "==0.7.11" }, "apipkg": { "hashes": [ @@ -34,13 +36,6 @@ ], "version": "==1.4.3" }, - "atomicwrites": { - "hashes": [ - "sha256:240831ea22da9ab882b551b31d4225591e5e447a68c5e188db5b89ca1d487585", - "sha256:a24da68318b08ac9c9c45029f4a10371ab5b20e4226738e150e6e7c571630ae6" - ], - "version": "==1.1.5" - }, "arpeggio": { "hashes": [ "sha256:828ea85ca3c7a99125dc83000ca170c1ea1105c75cbf67a513c2e16e05e36f67", @@ -48,6 +43,13 @@ ], "version": "==1.8.0" }, + "atomicwrites": { + "hashes": [ + "sha256:240831ea22da9ab882b551b31d4225591e5e447a68c5e188db5b89ca1d487585", + "sha256:a24da68318b08ac9c9c45029f4a10371ab5b20e4226738e150e6e7c571630ae6" + ], + "version": "==1.1.5" + }, "attrs": { "hashes": [ "sha256:4b90b09eeeb9b88c35bc642cbac057e45a5fd85367b985bd2809c62b7b939265", @@ -64,12 +66,12 @@ }, "black": { "hashes": [ - "sha256:3efe92eafbde15f8ac06478de11cfb84e47504896ccdde64507e751d2f91ec3a", - "sha256:fc26c4ab28c541fb824f59fa83d5702f75829495d5a1dee603b29bc4fbe79095" + "sha256:22158b89c1a6b4eb333a1e65e791a3f8b998cf3b11ae094adb2570f31f769a44", + "sha256:4b475bbd528acce094c503a3d2dbc2d05a4075f6d0ef7d9e7514518e14cc5191" ], "index": "pypi", "markers": "python_version >= '3.6'", - "version": "==18.6b2" + "version": "==18.6b4" }, "certifi": { "hashes": [ @@ -93,21 +95,6 @@ "index": "pypi", "version": "==6.7" }, - "colorama": { - "hashes": [ - "sha256:463f8483208e921368c9f306094eb6f725c6ca42b0f97e313cb5d5512459feda", - "sha256:48eb22f4f8461b1df5734a074b57042430fb06e1d61bd1e11b078c0fe6d7a1f1" - ], - "markers": "sys_platform == 'win32'", - "version": "==0.3.9" - }, - "configparser": { - "hashes": [ - "sha256:5308b47021bc2340965c371f0f058cc6971a04502638d4244225c49d80db273a" - ], - "markers": "python_version < '3.2'", - "version": "==3.5.0" - }, "docutils": { "hashes": [ "sha256:02aec4bd92ab067f6ff27a38a38a41173bf01bed8f89157768c1573f53e474a6", @@ -116,16 +103,6 @@ ], "version": "==0.14" }, - "enum34": { - "hashes": [ - "sha256:2d81cbbe0e73112bdfe6ef8576f2238f2ba27dd0d55752a776c41d38b7da2850", - "sha256:644837f692e5f550741432dd3f223bbb9852018674981b1664e5dc339387588a", - "sha256:6bd0f6ad48ec2aa117d3d141940d484deccda84d4fcd884f5c3d93c23ecd8c79", - "sha256:8ad8c4783bf61ded74527bffb48ed9b54166685e4230386a9ed9b1279e2df5b1" - ], - "markers": "python_version < '3.4'", - "version": "==1.1.6" - }, "execnet": { "hashes": [ "sha256:a7a84d5fa07a089186a329528f127c9d73b9de57f1a1131b82bb5320ee651f6a", @@ -156,14 +133,6 @@ ], "version": "==1.0.2" }, - "funcsigs": { - "hashes": [ - "sha256:330cc27ccbf7f1e992e69fef78261dc7c6569012cf397db8d3de0234e6c937ca", - "sha256:a7bb0f2cf3a3fd1ab2732cb49eba4252c2af4240442415b4abce3b87022a8f50" - ], - "markers": "python_version < '3.0'", - "version": "==1.0.2" - }, "idna": { "hashes": [ "sha256:156a6814fb5ac1fc6850fb002e0852d56c0c8d2531923a51032d1b70760e186e", @@ -236,13 +205,6 @@ ], "version": "==4.2.0" }, - "parver": { - "hashes": [ - "sha256:13a1141380aabcf6a7eb9bfc5197540a92f004eeab5a7f90e285cd51476ca512", - "sha256:d7be350da178d42de8c4bd346930bae05a18584110382a299af549ff08b848f9" - ], - "version": "==0.1.0" - }, "packaging": { "hashes": [ "sha256:e9215d2d2535d3ae866c3d6efc77d5b24a0192cce0ff20e42896cc0664f889c0", @@ -250,6 +212,14 @@ ], "version": "==17.1" }, + "parver": { + "hashes": [ + "sha256:ac4afff688d19d5e1876bb68d4bccc1a1b6a5cc8bd6a646939a14d366695ba15", + "sha256:f025fba8f88a9c776971df6d62b6cf7f37d1108f84c163bda91e157d7d527075" + ], + "index": "pypi", + "version": "==0.1.1" + }, "pbr": { "hashes": [ "sha256:3747c6f017f2dc099986c325239661948f9f5176f6880d9fdef164cb664cd665", @@ -274,14 +244,16 @@ "sha256:d345c8fe681115900d6da8d048ba67c25df42973bda370783cd58826442dcd7c", "sha256:e160a7fcf25762bb60efc7e171d4497ff1d8d2d75a3d0df7a21b76821ecbf5c5" ], + "markers": "python_version != '3.2.*' and python_version != '3.1.*' and python_version != '3.0.*' and python_version != '3.3.*' and python_version >= '2.7'", "version": "==0.6.0" }, "py": { "hashes": [ - "sha256:29c9fab495d7528e80ba1e343b958684f4ace687327e6f789a94bf3d1915f881", - "sha256:983f77f3331356039fdd792e9220b7b8ee1aa6bd2b25f567a963ff1de5a64f6a" + "sha256:3fd59af7435864e1a243790d322d763925431213b6b8529c6ca71081ace3bbf7", + "sha256:e31fb2767eb657cbde86c454f02e99cb846d3cd9d61b318525140214fdc0e98e" ], - "version": "==1.5.3" + "markers": "python_version != '3.2.*' and python_version != '3.1.*' and python_version != '3.0.*' and python_version != '3.3.*' and python_version >= '2.7'", + "version": "==1.5.4" }, "pycodestyle": { "hashes": [ @@ -307,22 +279,17 @@ "pyparsing": { "hashes": [ "sha256:0832bcf47acd283788593e7a0f542407bd9550a55a8a8435214a1960e04bcb04", - "sha256:281683241b25fe9b80ec9d66017485f6deff1af5cde372469134b56ca8447a07", - "sha256:8f1e18d3fd36c6795bb7e02a39fd05c611ffc2596c1e0d995d34d67630426c18", - "sha256:9e8143a3e15c13713506886badd96ca4b579a87fbdf49e550dbfc057d6cb218e", - "sha256:b8b3117ed9bdf45e14dcc89345ce638ec7e0e29b2b579fa1ecf32ce45ebac8a5", - "sha256:e4d45427c6e20a59bf4f88c639dcc03ce30d193112047f94012102f235853a58", "sha256:fee43f17a9c4087e7ed1605bd6df994c6173c1e977d7ade7b651292fab2bd010" ], "version": "==2.2.0" }, "pytest": { "hashes": [ - "sha256:26838b2bc58620e01675485491504c3aa7ee0faf335c37fcd5f8731ca4319591", - "sha256:32c49a69566aa7c333188149ad48b58ac11a426d5352ea3d8f6ce843f88199cb" + "sha256:8ea01fc4fcc8e1b1e305252b4bc80a1528019ab99fd3b88666c9dc38d754406c", + "sha256:90898786b3d0b880b47645bae7b51aa9bbf1e9d1e4510c2cfd15dd65c70ea0cd" ], "index": "pypi", - "version": "==3.6.1" + "version": "==3.6.2" }, "pytest-forked": { "hashes": [ @@ -353,11 +320,11 @@ }, "pytz": { "hashes": [ - "sha256:65ae0c8101309c45772196b21b74c46b2e5d11b6275c45d251b150d5da334555", - "sha256:c06425302f2cf668f1bba7a0a03f3c1d34d4ebeef2c72003da308b3947c7f749" + "sha256:a061aa0a9e06881eb8b3b2b43f05b9439d6583c206d0a6c340ff72a7b6669053", + "sha256:ffb9ef1de172603304d9d2819af6f5ece76f2e85ec10692a524dd876e72bf277" ], "index": "pypi", - "version": "==2018.4" + "version": "==2018.5" }, "requests": { "hashes": [ @@ -397,17 +364,18 @@ }, "sphinx-click": { "hashes": [ - "sha256:2d1ead3335ee43c4959ed1dd2b29156de1e2709b6d45ba42497fcd8d334c9c2c", - "sha256:b3973152d29fb86f0196e47878c96e2b8b1edbcc854268f3f82847277e5182cf" + "sha256:0550d3e5dcd6244847bd0861ebe64101a2ef302913866e0ccd9095b2aa230051", + "sha256:404784f724504e3da2cb056767ba64955c4bfb9bfca8cfedd7142a962bafd70f" ], "index": "pypi", - "version": "==1.2.0" + "version": "==1.3.0" }, "sphinxcontrib-websupport": { "hashes": [ "sha256:68ca7ff70785cbe1e7bccc71a48b5b6d965d79ca50629606c7861a21b206d9dd", "sha256:9de47f375baf1ea07cdb3436ff39d7a9c76042c10a769c52353ec46e4e8fc3b9" ], + "markers": "python_version != '3.2.*' and python_version != '3.1.*' and python_version != '3.0.*' and python_version != '3.3.*' and python_version >= '2.7'", "version": "==1.1.0" }, "stdeb": { @@ -441,17 +409,9 @@ "sha256:224291ee0d8c52d91b037fd90806f48c79bcd9994d3b0abc9e44b946a908fccd", "sha256:77b8424d41b31e68f437c6dd9cd567aebc9a860507cb42fbd880a5f822d966fe" ], + "markers": "python_version >= '2.6' and python_version != '3.0.*' and python_version != '3.1.*'", "version": "==4.23.4" }, - "typing": { - "hashes": [ - "sha256:3a887b021a77b292e151afb75323dea88a7bc1b3dfa92176cff8e44c8b68bddf", - "sha256:b2c689d54e1144bbcfd191b0832980a21c2dbcf7b5ff7a66248a60c90e951eb8", - "sha256:d400a9344254803a2368533e4533a4200d21eb7b6b729c173bc38201a74db3f2" - ], - "markers": "python_version < '3.5'", - "version": "==3.6.4" - }, "twine": { "hashes": [ "sha256:08eb132bbaec40c6d25b358f546ec1dc96ebd2638a86eea68769d9e67fe2b129", @@ -465,6 +425,7 @@ "sha256:a68ac5e15e76e7e5dd2b8f94007233e01effe3e50e8daddf69acfd81cb686baf", "sha256:b5725a0bd4ba422ab0e66e89e030c806576753ea3ee08554382c14e685d117b5" ], + "markers": "python_version >= '2.6' and python_version != '3.2.*' and python_version != '3.1.*' and python_version < '4' and python_version != '3.0.*' and python_version != '3.3.*'", "version": "==1.23" }, "virtualenv": { @@ -472,6 +433,7 @@ "sha256:2ce32cd126117ce2c539f0134eb89de91a8413a29baac49cbab3eb50e2026669", "sha256:ca07b4c0b54e14a91af9f34d0919790b016923d157afda5efdde55c96718f752" ], + "markers": "python_version != '3.0.*' and python_version != '3.1.*' and python_version != '3.2.*' and python_version >= '2.7'", "version": "==16.0.0" }, "virtualenv-clone": { diff --git a/pipenv/core.py b/pipenv/core.py index 4031a5bc..3838c7f8 100644 --- a/pipenv/core.py +++ b/pipenv/core.py @@ -41,10 +41,7 @@ from .utils import ( fs_str, clean_resolved_dep, ) -from ._compat import ( - TemporaryDirectory, - Path -) +from ._compat import TemporaryDirectory, Path from . import pep508checker, progress from .environments import ( PIPENV_COLORBLIND, @@ -67,7 +64,7 @@ from .environments import ( ) # Packages that should be ignored later. -BAD_PACKAGES = ('setuptools', 'pip', 'wheel', 'packaging', 'distribute') +BAD_PACKAGES = ("setuptools", "pip", "wheel", "packaging", "distribute") # Are we using the default Python? USING_DEFAULT_PYTHON = True if not PIPENV_HIDE_EMOJIS: @@ -76,20 +73,20 @@ if not PIPENV_HIDE_EMOJIS: if ((now.tm_mon == 10) and (now.tm_mday == 30)) or ( (now.tm_mon == 10) and (now.tm_mday == 31) ): - INSTALL_LABEL = '🎃 ' + 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 = '🎅 ' + INSTALL_LABEL = "🎅 " else: - INSTALL_LABEL = '🐍 ' - INSTALL_LABEL2 = crayons.normal('☤ ', bold=True) - STARTING_LABEL = ' ' + INSTALL_LABEL = "🐍 " + INSTALL_LABEL2 = crayons.normal("☤ ", bold=True) + STARTING_LABEL = " " else: - INSTALL_LABEL = ' ' - INSTALL_LABEL2 = ' ' - STARTING_LABEL = ' ' + 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. @@ -105,20 +102,18 @@ if PIPENV_NOSPIN: 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') + 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, - ) + if os.name == "nt": + p = find_windows_executable(os.path.join(location, "Scripts"), command) else: - p = os.path.join(location, 'bin', command) + p = os.path.join(location, "bin", command) else: - if command == 'python': + if command == "python": p = sys.executable if not os.path.exists(p): - if command == 'python': - p = sys.executable or system_which('python') + if command == "python": + p = sys.executable or system_which("python") else: p = system_which(command) return p @@ -131,15 +126,13 @@ 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 '.' + project_directory = project.project_directory or "." denv = dotenv.find_dotenv( - PIPENV_DOTENV_LOCATION or os.sep.join([project_directory, '.env']) + 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 - ), + crayons.normal("Loading .env environment variables...", bold=True), err=True, ) dotenv.load_dotenv(denv, override=True) @@ -147,23 +140,21 @@ def load_dot_env(): 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'] - ) + 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.')) + 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), + "{0} An error occurred while removing {1}!".format( + crayons.red("Error: ", bold=True), crayons.green(project.virtualenv_location), ), err=True, @@ -183,21 +174,21 @@ def import_requirements(r=None, dev=False): # Default path, if none is provided. if r is None: r = project.requirements_location - with open(r, 'r') as f: + 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 ')): + 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 - ) + "-e {0}".format(package.link) + if package.editable + else str(package.link) ) project.add_package_to_pipfile(package_string, dev=dev) else: @@ -209,22 +200,23 @@ def import_requirements(r=None, dev=False): def ensure_environment(): # Skip this on Windows... - if os.name != 'nt': - if 'LANG' not in os.environ: + 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'), + "{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='.'): +def import_from_code(path="."): from pipreqs import pipreqs + rs = [] try: for r in pipreqs.get_all_imports(path): @@ -240,15 +232,16 @@ def import_from_code(path='.'): def ensure_pipfile(validate=True, skip_requirements=False, system=False): """Creates a Pipfile for the project, if it doesn't exist.""" from .environments import PIPENV_VIRTUALENV + # Assert Pipfile exists. - python = which('python') if not (USING_DEFAULT_PYTHON or system) else None + 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) + "{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, ) @@ -257,7 +250,7 @@ def ensure_pipfile(validate=True, skip_requirements=False, system=False): if project.requirements_exists and not skip_requirements: click.echo( crayons.normal( - u'requirements.txt found, instead of Pipfile! Converting...', + u"requirements.txt found, instead of Pipfile! Converting...", bold=True, ) ) @@ -268,20 +261,18 @@ def ensure_pipfile(validate=True, skip_requirements=False, system=False): 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), + 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 - ), + crayons.normal(u"Creating a Pipfile for this project...", bold=True), err=True, ) # Create the pipfile if it doesn't exist. @@ -294,7 +285,7 @@ def ensure_pipfile(validate=True, skip_requirements=False, system=False): # Write changes out to disk. if changed: click.echo( - crayons.normal(u'Fixing package names in Pipfile...', bold=True), + crayons.normal(u"Fixing package names in Pipfile...", bold=True), err=True, ) project.write_toml(p) @@ -305,19 +296,19 @@ def find_python_from_py(python): Ask py.exe for its opinion. """ - py = system_which('py') + py = system_which("py") if not py: return None - version_args = ['-{0}'.format(python[0])] + version_args = ["-{0}".format(python[0])] if len(python) >= 2: - version_args.append('-{0}.{1}'.format(python[0], 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)'] + [py, ver_arg, "-c", "import sys; print(sys.executable)"] ) except subprocess.CalledProcessError: continue @@ -326,7 +317,7 @@ def find_python_from_py(python): python_exe = python_exe.decode(sys.getdefaultencoding()) python_exe = python_exe.strip() version = python_version(python_exe) - if (version or '').startswith(python): + if (version or "").startswith(python): return python_exe @@ -335,31 +326,31 @@ def find_python_in_path(python): This uses the PATH environment variable to locate an appropriate Python. """ - possibilities = ['python', 'python{0}'.format(python[0])] + 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]), + "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) + 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): + 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'): + if python.startswith("py"): return system_which(python) elif os.path.isabs(python): @@ -375,15 +366,16 @@ def find_a_system_python(python): def ensure_python(three=None, python=None): # Support for the PIPENV_PYTHON environment variable. from .environments import PIPENV_PYTHON + 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( + "You can specify specific versions of Python with:\n {0}".format( crayons.red( - '$ pipenv --python {0}'.format( - os.sep.join(('path', 'to', 'python')) + "$ pipenv --python {0}".format( + os.sep.join(("path", "to", "python")) ) ) ), @@ -398,25 +390,21 @@ def ensure_python(three=None, python=None): 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( + 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 - ): + 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),), + "{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, ) @@ -424,7 +412,7 @@ def ensure_python(three=None, python=None): # Add pyenv paths to PATH. activate_pyenv() path_to_python = None - USING_DEFAULT_PYTHON = (three is None and not python) + 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) @@ -437,10 +425,10 @@ def ensure_python(three=None, python=None): 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), + u"{0}: Python {1} {2}".format( + crayons.red("Warning", bold=True), crayons.blue(python), - u'was not found on your system...', + u"was not found on your system...", ), err=True, ) @@ -453,30 +441,28 @@ def ensure_python(three=None, python=None): # 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', + "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.6', - '3.7': '3.7.0', + "3.3": "3.3.7", + "3.4": "3.4.8", + "3.5": "3.5.5", + "3.6": "3.6.6", + "3.7": "3.7.0", } try: - if len(python.split('.')) == 2: + 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?', - ) + 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)): @@ -484,20 +470,18 @@ def ensure_python(three=None, python=None): 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), + 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), + "pyenv install {0} -s".format(version), timeout=PIPENV_INSTALL_TIMEOUT, block=False, ) @@ -506,7 +490,7 @@ def ensure_python(three=None, python=None): try: assert c.return_code == 0 except AssertionError: - click.echo(u'Something went wrong...') + 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) @@ -518,10 +502,10 @@ def ensure_python(three=None, python=None): 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), + "{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, ) @@ -548,12 +532,14 @@ def ensure_virtualenv(three=None, python=None, site_packages=False, pypi_mirror= if PIPENV_USE_SYSTEM: click.echo( crayons.red( - 'You are attempting to re-create a virtualenv that ' - 'Pipenv did not create. Aborting.' + "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, pypi_mirror=pypi_mirror) + do_create_virtualenv( + python=python, site_packages=site_packages, pypi_mirror=pypi_mirror + ) except KeyboardInterrupt: # If interrupted, cleanup the virtualenv. cleanup_virtualenv(bare=False) @@ -563,25 +549,26 @@ def ensure_virtualenv(three=None, python=None, site_packages=False, pypi_mirror= 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) + 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 "VIRTUAL_ENV" in os.environ: if not ( - PIPENV_YES or - click.confirm('Remove existing virtualenv?', default=True) + PIPENV_YES or click.confirm("Remove existing virtualenv?", default=True) ): abort() click.echo( - crayons.normal(u'Removing existing virtualenv...', bold=True), - err=True, + 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, pypi_mirror=pypi_mirror + three=three, + python=python, + site_packages=site_packages, + pypi_mirror=pypi_mirror, ) @@ -598,6 +585,7 @@ def ensure_project( ): """Ensures both Pipfile and virtualenv exist for the project.""" from .environments import PIPENV_USE_SYSTEM + # Automatically use an activated virtualenv. if PIPENV_USE_SYSTEM: system = True @@ -606,20 +594,23 @@ def ensure_project( # Skip virtualenv creation when --system was used. if not system: ensure_virtualenv( - three=three, python=python, site_packages=site_packages, pypi_mirror=pypi_mirror + three=three, + python=python, + site_packages=site_packages, + pypi_mirror=pypi_mirror, ) 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') + 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 '' + 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), + "{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)), @@ -628,25 +619,24 @@ def ensure_project( ) if not deploy: click.echo( - ' {0} will surely fail.' - ''.format(crayons.red('$ pipenv check')), + " {0} will surely fail." + "".format(crayons.red("$ pipenv check")), err=True, ) else: - click.echo(crayons.red('Deploy aborted.'), err=True) + 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) + 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) - ] + [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] @@ -665,15 +655,15 @@ def do_where(virtualenv=False, bare=True): 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`')), + "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)), + "Pipfile found at {0}.\n Considering this to be the project home." + "".format(crayons.green(location)), err=True, ) pass @@ -683,8 +673,7 @@ def do_where(virtualenv=False, bare=True): location = project.virtualenv_location if not bare: click.echo( - 'Virtualenv location: {0}'.format(crayons.green(location)), - err=True, + "Virtualenv location: {0}".format(crayons.green(location)), err=True ) else: click.echo(location) @@ -712,7 +701,7 @@ def do_install_dependencies( for c in procs: if concurrent: c.block() - if 'Ignoring' in c.out: + if "Ignoring" in c.out: click.echo(crayons.yellow(c.out.strip())) if verbose: click.echo(crayons.blue(c.out or c.err)) @@ -722,22 +711,20 @@ def do_install_dependencies( 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()), + "{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) + 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 - ) + crayons.normal(u"Installing dependencies from Pipfile...", bold=True) ) lockfile = split_file(project._lockfile) else: @@ -746,14 +733,14 @@ def do_install_dependencies( if not bare: click.echo( crayons.normal( - u'Installing dependencies from Pipfile.lock ({0})...'.format( - lockfile['_meta'].get('hash', {}).get('sha256')[-6:] + 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) + no_deps = not skip_lock deps_list, dev_deps_list = merge_deps( lockfile, project, @@ -771,28 +758,28 @@ def do_install_dependencies( 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()) + 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-') + 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))) + 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))) + 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 '' + 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') + 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, @@ -816,16 +803,12 @@ def do_install_dependencies( # Iterate over the hopefully-poorly-packaged dependencies... if failed_deps_list: click.echo( - crayons.normal( - u'Installing initially failed dependencies...', bold=True - ) + crayons.normal(u"Installing initially failed dependencies...", bold=True) ) - for dep, ignore_hash in progress.bar( - failed_deps_list, label=INSTALL_LABEL2 - ): + 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') + 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, @@ -846,10 +829,10 @@ def do_install_dependencies( 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('!'), + "{0} {1}{2}".format( + crayons.green("Success installing"), + crayons.green(dep.split("--hash")[0].strip()), + crayons.green("!"), ) ) @@ -860,10 +843,10 @@ def convert_three_to_python(three, python): """ if not python: if three is False: - return '2' + return "2" elif three is True: - return '3' + return "3" else: return python @@ -872,61 +855,64 @@ def convert_three_to_python(three, python): def do_create_virtualenv(python=None, site_packages=False, pypi_mirror=None): """Creates a virtualenv.""" click.echo( - crayons.normal(u'Creating a virtualenv for this project...', bold=True), + 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, ) - 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', + sys.executable, + "-m", + "virtualenv", project.virtualenv_location, - '--prompt=({0})'.format(project.name), + "--prompt=({0})".format(project.name), ] # Pass site-packages flag to virtualenv, if desired... if site_packages: - cmd.append('--system-site-packages') + cmd.append("--system-site-packages") else: # Default: use pew. cmd = [ sys.executable, - '-m', - 'pipenv.pew', - 'new', - '-d', - '-a', + "-m", + "pipenv.pew", + "new", + "-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), + 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))), + crayons.normal(u"to create virtualenv...", bold=True), + crayons.green("({0})".format(python_version(python))), ), err=True, ) - cmd = cmd + ['-p', python] + cmd = cmd + ["-p", python] if not project.is_venv_in_project(): - cmd = cmd + ['--', project.virtualenv_name] + cmd = cmd + ["--", project.virtualenv_name] # Actually create the virtualenv. with spinner(): try: - pip_config = {'PIP_INDEX_URL': fs_str(pypi_mirror)} if pypi_mirror else {} + pip_config = {"PIP_INDEX_URL": fs_str(pypi_mirror)} if pypi_mirror else {} c = delegator.run(cmd, block=False, timeout=PIPENV_TIMEOUT, env=pip_config) 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), + "{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), + crayons.normal("PATH", bold=True), ), err=True, ) @@ -935,32 +921,32 @@ def do_create_virtualenv(python=None, site_packages=False, pypi_mirror=None): # 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, + 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'] + 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'): + 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:] + version = fname[len(name) + 1 :] # Ignore implicit post releases in version number. - if '-' in version and version.split('-')[1].isdigit(): - version = version.split('-')[0] + if "-" in version and version.split("-")[1].isdigit(): + version = version.split("-")[0] return version def get_downloads_info(names_map, section): from .vendor.requirementslib import Requirement + info = [] p = project.parsed_pipfile for fname in os.listdir(project.download_location): @@ -974,10 +960,10 @@ def get_downloads_info(names_map, section): os.sep.join([project.download_location, fname]), ) c = delegator.run(cmd) - hash = c.out.split('--hash=')[1].strip() + 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, '') + specified_version = p[section].get(name, "") if is_required_version(version, specified_version): info.append(dict(name=name, version=version, hash=hash)) return info @@ -994,14 +980,15 @@ def do_lock( ): """Executes the freeze functionality.""" from .utils import get_vcs_deps + cached_lockfile = {} if not pre: - pre = project.settings.get('allow_prereleases') + pre = project.settings.get("allow_prereleases") if keep_outdated: if not project.lockfile_exists: click.echo( - '{0}: Pipfile.lock must exist to use --keep-outdated!'.format( - crayons.red('Warning', bold=True) + "{0}: Pipfile.lock must exist to use --keep-outdated!".format( + crayons.red("Warning", bold=True) ) ) sys.exit(1) @@ -1009,9 +996,9 @@ def do_lock( # Create the lockfile. lockfile = project._lockfile # Cleanup lockfile. - for section in ('default', 'develop'): + for section in ("default", "develop"): for k, v in lockfile[section].copy().items(): - if not hasattr(v, 'keys'): + if not hasattr(v, "keys"): del lockfile[section][k] # Ensure that develop inherits from default. dev_packages = project.dev_packages.copy() @@ -1020,41 +1007,41 @@ def do_lock( dev_packages[dev_package] = project.packages[dev_package] # Resolve dev-package dependencies, with pip-tools. pip_freeze = delegator.run( - '{0} freeze'.format(escape_grouped_arguments(which_pip(allow_global=system))) + "{0} freeze".format(escape_grouped_arguments(which_pip(allow_global=system))) ).out sections = { - 'dev': { - 'packages': project.dev_packages, - 'vcs': project.vcs_dev_packages, - 'pipfile_key': 'dev_packages', - 'lockfile_key': 'develop', - 'log_string': 'dev-packages', - 'dev': True + "dev": { + "packages": project.dev_packages, + "vcs": project.vcs_dev_packages, + "pipfile_key": "dev_packages", + "lockfile_key": "develop", + "log_string": "dev-packages", + "dev": True, + }, + "default": { + "packages": project.packages, + "vcs": project.vcs_packages, + "pipfile_key": "packages", + "lockfile_key": "default", + "log_string": "packages", + "dev": False, }, - 'default': { - 'packages': project.packages, - 'vcs': project.vcs_packages, - 'pipfile_key': 'packages', - 'lockfile_key': 'default', - 'log_string': 'packages', - 'dev': False - } } - for section_name in ['dev', 'default']: + for section_name in ["dev", "default"]: settings = sections[section_name] if write: # Alert the user of progress. click.echo( - u'{0} {1} {2}'.format( - crayons.normal('Locking'), - crayons.red('[{0}]'.format(settings['log_string'])), - crayons.normal('dependencies...'), + u"{0} {1} {2}".format( + crayons.normal("Locking"), + crayons.red("[{0}]".format(settings["log_string"])), + crayons.normal("dependencies..."), ), err=True, ) deps = convert_deps_to_pip( - settings['packages'], project, r=False, include_index=True + settings["packages"], project, r=False, include_index=True ) results = venv_resolve_deps( deps, @@ -1068,10 +1055,12 @@ def do_lock( ) # Add dependencies to lockfile. for dep in results: - is_top_level = dep['name'] in settings['packages'] - pipfile_entry = settings['packages'][dep['name']] if is_top_level else None - dep_lockfile = clean_resolved_dep(dep, is_top_level=is_top_level, pipfile_entry=pipfile_entry) - lockfile[settings['lockfile_key']].update(dep_lockfile) + is_top_level = dep["name"] in settings["packages"] + pipfile_entry = settings["packages"][dep["name"]] if is_top_level else None + dep_lockfile = clean_resolved_dep( + dep, is_top_level=is_top_level, pipfile_entry=pipfile_entry + ) + lockfile[settings["lockfile_key"]].update(dep_lockfile) # Add refs for VCS installs. # TODO: be smarter about this. vcs_reqs, vcs_lockfile = get_vcs_deps( @@ -1082,7 +1071,7 @@ def do_lock( clear=clear, pre=pre, allow_global=system, - dev=settings['dev'] + dev=settings["dev"], ) vcs_lines = [req.as_line() for req in vcs_reqs if req.editable] vcs_results = venv_resolve_deps( @@ -1096,30 +1085,28 @@ def do_lock( pypi_mirror=pypi_mirror, ) for dep in vcs_results: - normalized = pep423_name(dep['name']) - if not hasattr(dep, 'keys') or not hasattr(dep['name'], 'keys'): + normalized = pep423_name(dep["name"]) + if not hasattr(dep, "keys") or not hasattr(dep["name"], "keys"): continue - is_top_level = ( - dep['name'] in vcs_lockfile or - normalized in vcs_lockfile - ) + is_top_level = dep["name"] in vcs_lockfile or normalized in vcs_lockfile if is_top_level: try: - pipfile_entry = vcs_lockfile[dep['name']] + pipfile_entry = vcs_lockfile[dep["name"]] except KeyError: pipfile_entry = vcs_lockfile[normalized] else: pipfile_entry = None dep_lockfile = clean_resolved_dep( - dep, is_top_level=is_top_level, pipfile_entry=pipfile_entry, + dep, is_top_level=is_top_level, pipfile_entry=pipfile_entry ) vcs_lockfile.update(dep_lockfile) - lockfile[settings['lockfile_key']].update(vcs_lockfile) + lockfile[settings["lockfile_key"]].update(vcs_lockfile) # Support for --keep-outdated... if keep_outdated: for section_name, section in ( - ('default', project.packages), ('develop', project.dev_packages) + ("default", project.packages), + ("develop", project.dev_packages), ): for package_specified in section: norm_name = pep423_name(package_specified) @@ -1127,22 +1114,18 @@ def do_lock( if norm_name in cached_lockfile[section_name]: lockfile[section_name][norm_name] = cached_lockfile[ section_name - ][ - norm_name - ] + ][norm_name] # Overwrite any develop packages with default packages. - for default_package in lockfile['default']: - if default_package in lockfile['develop']: - lockfile['develop'][default_package] = lockfile['default'][ - default_package - ] + for default_package in lockfile["default"]: + if default_package in lockfile["develop"]: + lockfile["develop"][default_package] = lockfile["default"][default_package] if write: project.write_lockfile(lockfile) click.echo( - '{0}'.format( + "{0}".format( crayons.normal( - 'Updated Pipfile.lock ({0})!'.format( - lockfile['_meta'].get('hash', {}).get('sha256')[-6:] + "Updated Pipfile.lock ({0})!".format( + lockfile["_meta"].get("hash", {}).get("sha256")[-6:] ), bold=True, ) @@ -1156,24 +1139,23 @@ def do_lock( def do_purge(bare=False, downloads=False, allow_global=False, verbose=False): """Executes the purge functionality.""" from .vendor.requirementslib.models.requirements import Requirement + if downloads: if not bare: click.echo( - crayons.normal(u'Clearing out downloads directory...', bold=True) + crayons.normal(u"Clearing out downloads directory...", bold=True) ) shutil.rmtree(project.download_location) return freeze = delegator.run( - '{0} freeze'.format( + "{0} freeze".format( escape_grouped_arguments(which_pip(allow_global=allow_global)) ) ).out # Remove comments from the output, if any. installed = [ - line - for line in freeze.splitlines() - if not line.lstrip().startswith('#') + line for line in freeze.splitlines() if not line.lstrip().startswith("#") ] # Remove setuptools and friends from installed, if present. for package_name in BAD_PACKAGES: @@ -1191,20 +1173,20 @@ def do_purge(bare=False, downloads=False, allow_global=False, verbose=False): actually_installed.append(dep) if not bare: click.echo( - u'Found {0} installed package(s), purging...'.format( + u"Found {0} installed package(s), purging...".format( len(actually_installed) ) ) - command = '{0} uninstall {1} -y'.format( + command = "{0} uninstall {1} -y".format( escape_grouped_arguments(which_pip(allow_global=allow_global)), - ' '.join(actually_installed), + " ".join(actually_installed), ) if verbose: - click.echo('$ {0}'.format(command)) + click.echo("$ {0}".format(command)) c = delegator.run(command) if not bare: click.echo(crayons.blue(c.out)) - click.echo(crayons.green('Environment now purged and fresh!')) + click.echo(crayons.green("Environment now purged and fresh!")) def do_init( @@ -1224,6 +1206,7 @@ def do_init( ): """Executes the init functionality.""" from .environments import PIPENV_VIRTUALENV + cleanup_reqdir = False if not system: if not project.virtualenv_exists: @@ -1237,9 +1220,7 @@ def do_init( ensure_pipfile(system=system) if not requirements_dir: cleanup_reqdir = True - requirements_dir = TemporaryDirectory( - suffix='-requirements', prefix='pipenv-' - ) + requirements_dir = TemporaryDirectory(suffix="-requirements", prefix="pipenv-") # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored if (project.lockfile_exists and not ignore_pipfile) and not skip_lock: old_hash = project.get_lockfile_hash() @@ -1248,25 +1229,22 @@ def do_init( if deploy: click.echo( crayons.red( - 'Your Pipfile.lock ({0}) is out of date. Expected: ({1}).'.format( + "Your Pipfile.lock ({0}) is out of date. Expected: ({1}).".format( old_hash[-6:], new_hash[-6:] ) ) ) - click.echo( - crayons.normal('Aborting deploy.', bold=True), err=True - ) + click.echo(crayons.normal("Aborting deploy.", bold=True), err=True) requirements_dir.cleanup() sys.exit(1) elif (system or allow_global) and not (PIPENV_VIRTUALENV): click.echo( crayons.red( - u'Pipfile.lock ({0}) out of date, but installation ' - u'uses {1}... re-building lockfile must happen in ' - u'isolation. Please rebuild lockfile in a virtualenv. ' - u'Continuing anyway...'.format( - crayons.white(old_hash[-6:]), - crayons.white('--system') + u"Pipfile.lock ({0}) out of date, but installation " + u"uses {1}... re-building lockfile must happen in " + u"isolation. Please rebuild lockfile in a virtualenv. " + u"Continuing anyway...".format( + crayons.white(old_hash[-6:]), crayons.white("--system") ), bold=True, ), @@ -1275,32 +1253,38 @@ def do_init( else: click.echo( crayons.red( - u'Pipfile.lock ({0}) out of date, updating to ({1})...'.format( + u"Pipfile.lock ({0}) out of date, updating to ({1})...".format( old_hash[-6:], new_hash[-6:] ), bold=True, ), err=True, ) - do_lock(system=system, pre=pre, keep_outdated=keep_outdated, write=True, pypi_mirror=pypi_mirror) + do_lock( + system=system, + pre=pre, + keep_outdated=keep_outdated, + write=True, + pypi_mirror=pypi_mirror, + ) # Write out the lockfile if it doesn't exist. if not project.lockfile_exists and not skip_lock: # Unless we're in a virtualenv not managed by pipenv, abort if we're # using the system's python. if (system or allow_global) and not (PIPENV_VIRTUALENV): click.echo( - '{0}: --system is intended to be used for Pipfile installation, ' - 'not installation of specific packages. Aborting.'.format( - crayons.red('Warning', bold=True) + "{0}: --system is intended to be used for Pipfile installation, " + "not installation of specific packages. Aborting.".format( + crayons.red("Warning", bold=True) ), err=True, ) - click.echo('See also: --deploy flag.', err=True) + click.echo("See also: --deploy flag.", err=True) requirements_dir.cleanup() sys.exit(1) else: click.echo( - crayons.normal(u'Pipfile.lock not found, creating...', bold=True), + crayons.normal(u"Pipfile.lock not found, creating...", bold=True), err=True, ) do_lock( @@ -1325,13 +1309,12 @@ def do_init( requirements_dir.cleanup() # Hint the user what to do to activate the virtualenv. - if not allow_global and not deploy and 'PIPENV_ACTIVE' not in os.environ: + if not allow_global and not deploy and "PIPENV_ACTIVE" not in os.environ: click.echo( "To activate this project's virtualenv, run {0}.\n" "Alternatively, run a command " "inside the virtualenv with {1}.".format( - crayons.red('pipenv shell'), - crayons.red('pipenv run'), + crayons.red("pipenv shell"), crayons.red("pipenv run") ) ) @@ -1354,101 +1337,104 @@ def pip_install( from notpip._internal import logger as piplogger from notpip._vendor.pyparsing import ParseException from .vendor.requirementslib import Requirement + if verbose: click.echo( - crayons.normal('Installing {0!r}'.format(package_name), bold=True), - err=True, + crayons.normal("Installing {0!r}".format(package_name), bold=True), err=True ) piplogger.setLevel(logging.INFO) # Create files for hash mode. - if not package_name.startswith('-e ') and (not ignore_hashes) and ( - r is None - ): + if not package_name.startswith("-e ") and (not ignore_hashes) and (r is None): fd, r = tempfile.mkstemp( - prefix='pipenv-', suffix='-requirement.txt', dir=requirements_dir + prefix="pipenv-", suffix="-requirement.txt", dir=requirements_dir ) - with os.fdopen(fd, 'w') as f: + with os.fdopen(fd, "w") as f: f.write(package_name) # Install dependencies when a package is a VCS dependency. try: req = Requirement.from_line( - package_name.split('--hash')[0].split('--trusted-host')[0] + package_name.split("--hash")[0].split("--trusted-host")[0] ).vcs except (ParseException, ValueError) as e: - click.echo('{0}: {1}'.format(crayons.red('WARNING'), e), err=True) + click.echo("{0}: {1}".format(crayons.red("WARNING"), e), err=True) click.echo( - '{0}... You will have to reinstall any packages that failed to install.'.format( - crayons.red('ABORTING INSTALL') + "{0}... You will have to reinstall any packages that failed to install.".format( + crayons.red("ABORTING INSTALL") ), err=True, ) click.echo( - 'You may have to manually run {0} when you are finished.'.format( - crayons.normal('pipenv lock', bold=True) + "You may have to manually run {0} when you are finished.".format( + crayons.normal("pipenv lock", bold=True) ) ) sys.exit(1) if req: no_deps = False # Don't specify a source directory when using --system. - if not allow_global and ('PIP_SRC' not in os.environ): - src = '--src {0}'.format( + if not allow_global and ("PIP_SRC" not in os.environ): + src = "--src {0}".format( escape_grouped_arguments(project.virtualenv_src_location) ) else: - src = '' + src = "" else: - src = '' + src = "" # Try installing for each source in project.sources. if index: if not is_valid_url(index): - index = project.find_source(index).get('url') - sources = [{'url': index}] + index = project.find_source(index).get("url") + sources = [{"url": index}] if extra_indexes: if isinstance(extra_indexes, six.string_types): extra_indexes = [extra_indexes] for idx in extra_indexes: try: - extra_src = project.find_source(idx).get('url') + extra_src = project.find_source(idx).get("url") except SourceNotFound: extra_src = idx if extra_src != index: - sources.append({'url': extra_src}) + sources.append({"url": extra_src}) else: for idx in project.pipfile_sources: - if idx['url'] != sources[0]['url']: - sources.append({'url': idx['url']}) + if idx["url"] != sources[0]["url"]: + sources.append({"url": idx["url"]}) else: sources = project.pipfile_sources if pypi_mirror: - sources = [create_mirror_source(pypi_mirror) if is_pypi_url(source['url']) else source for source in sources] - if package_name.startswith('-e '): - install_reqs = ' -e "{0}"'.format(package_name.split('-e ')[1]) + sources = [ + create_mirror_source(pypi_mirror) if is_pypi_url(source["url"]) else source + for source in sources + ] + if package_name.startswith("-e "): + install_reqs = ' -e "{0}"'.format(package_name.split("-e ")[1]) elif r: - install_reqs = ' -r {0}'.format(escape_grouped_arguments(r)) + install_reqs = " -r {0}".format(escape_grouped_arguments(r)) else: install_reqs = ' "{0}"'.format(package_name) # Skip hash-checking mode, when appropriate. if r: with open(r) as f: - if '--hash' not in f.read(): + if "--hash" not in f.read(): ignore_hashes = True else: - if '--hash' not in install_reqs: + if "--hash" not in install_reqs: ignore_hashes = True - verbose_flag = '--verbose' if verbose else '' + verbose_flag = "--verbose" if verbose else "" if not ignore_hashes: - install_reqs += ' --require-hashes' - no_deps = '--no-deps' if no_deps else '' - pre = '--pre' if pre else '' + install_reqs += " --require-hashes" + no_deps = "--no-deps" if no_deps else "" + pre = "--pre" if pre else "" quoted_pip = which_pip(allow_global=allow_global) quoted_pip = escape_grouped_arguments(quoted_pip) - upgrade_strategy = '--upgrade --upgrade-strategy=only-if-needed' if selective_upgrade else '' - pip_command = '{0} install {4} {5} {6} {7} {3} {1} {2} --exists-action w'.format( + upgrade_strategy = ( + "--upgrade --upgrade-strategy=only-if-needed" if selective_upgrade else "" + ) + pip_command = "{0} install {4} {5} {6} {7} {3} {1} {2} --exists-action w".format( quoted_pip, install_reqs, - ' '.join(prepare_pip_source_args(sources)), + " ".join(prepare_pip_source_args(sources)), no_deps, pre, src, @@ -1456,12 +1442,12 @@ def pip_install( upgrade_strategy, ) if verbose: - click.echo('$ {0}'.format(pip_command), err=True) + click.echo("$ {0}".format(pip_command), err=True) cache_dir = Path(PIPENV_CACHE_DIR) pip_config = { - 'PIP_CACHE_DIR': fs_str(cache_dir.as_posix()), - 'PIP_WHEEL_DIR': fs_str(cache_dir.joinpath('wheels').as_posix()), - 'PIP_DESTINATION_DIR': fs_str(cache_dir.joinpath('pkgs').as_posix()), + "PIP_CACHE_DIR": fs_str(cache_dir.as_posix()), + "PIP_WHEEL_DIR": fs_str(cache_dir.joinpath("wheels").as_posix()), + "PIP_DESTINATION_DIR": fs_str(cache_dir.joinpath("pkgs").as_posix()), } c = delegator.run(pip_command, block=block, env=pip_config) return c @@ -1470,15 +1456,15 @@ def pip_install( def pip_download(package_name): cache_dir = Path(PIPENV_CACHE_DIR) pip_config = { - 'PIP_CACHE_DIR': fs_str(cache_dir.as_posix()), - 'PIP_WHEEL_DIR': fs_str(cache_dir.joinpath('wheels').as_posix()), - 'PIP_DESTINATION_DIR': fs_str(cache_dir.joinpath('pkgs').as_posix()), + "PIP_CACHE_DIR": fs_str(cache_dir.as_posix()), + "PIP_WHEEL_DIR": fs_str(cache_dir.joinpath("wheels").as_posix()), + "PIP_DESTINATION_DIR": fs_str(cache_dir.joinpath("pkgs").as_posix()), } for source in project.sources: cmd = '{0} download "{1}" -i {2} -d {3}'.format( escape_grouped_arguments(which_pip()), package_name, - source['url'], + source["url"], project.download_location, ) c = delegator.run(cmd, env=pip_config) @@ -1491,28 +1477,28 @@ def pip_download(package_name): def which_pip(allow_global=False): """Returns the location of virtualenv-installed pip.""" if allow_global: - if 'VIRTUAL_ENV' in os.environ: - return which('pip', location=os.environ['VIRTUAL_ENV']) + if "VIRTUAL_ENV" in os.environ: + return which("pip", location=os.environ["VIRTUAL_ENV"]) - for p in ('pip', 'pip3', 'pip2'): + for p in ("pip", "pip3", "pip2"): where = system_which(p) if where: return where - return which('pip') + return which("pip") def system_which(command, mult=False): """Emulates the system's which. Returns None if not found.""" - _which = 'which -a' if not os.name == 'nt' else 'where' - c = delegator.run('{0} {1}'.format(_which, command)) + _which = "which -a" if not os.name == "nt" else "where" + c = delegator.run("{0} {1}".format(_which, command)) try: # Which Not found... if c.return_code == 127: click.echo( - '{}: the {} system utility is required for Pipenv to find Python installations properly.' - '\n Please install it.'.format( - crayons.red('Warning', bold=True), crayons.red(_which) + "{}: the {} system utility is required for Pipenv to find Python installations properly." + "\n Please install it.".format( + crayons.red("Warning", bold=True), crayons.red(_which) ), err=True, ) @@ -1522,34 +1508,29 @@ def system_which(command, mult=False): result = c.out.strip() or c.err.strip() if mult: - return result.split('\n') + return result.split("\n") else: - return result.split('\n')[0] + return result.split("\n")[0] def format_help(help): """Formats the help string.""" - help = help.replace('Options:', str(crayons.normal('Options:', bold=True))) + help = help.replace("Options:", str(crayons.normal("Options:", bold=True))) help = help.replace( - 'Usage: pipenv', - str('Usage: {0}'.format(crayons.normal('pipenv', bold=True))), + "Usage: pipenv", str("Usage: {0}".format(crayons.normal("pipenv", bold=True))) ) - help = help.replace(' check', str(crayons.red(' check', bold=True))) - help = help.replace(' clean', str(crayons.red(' clean', bold=True))) - help = help.replace(' graph', str(crayons.red(' graph', bold=True))) - help = help.replace( - ' install', str(crayons.magenta(' install', bold=True)) - ) - help = help.replace(' lock', str(crayons.green(' lock', bold=True))) - help = help.replace(' open', str(crayons.red(' open', bold=True))) - help = help.replace(' run', str(crayons.yellow(' run', bold=True))) - help = help.replace(' shell', str(crayons.yellow(' shell', bold=True))) - help = help.replace(' sync', str(crayons.green(' sync', bold=True))) - help = help.replace( - ' uninstall', str(crayons.magenta(' uninstall', bold=True)) - ) - help = help.replace(' update', str(crayons.green(' update', bold=True))) + help = help.replace(" check", str(crayons.red(" check", bold=True))) + help = help.replace(" clean", str(crayons.red(" clean", bold=True))) + help = help.replace(" graph", str(crayons.red(" graph", bold=True))) + help = help.replace(" install", str(crayons.magenta(" install", bold=True))) + help = help.replace(" lock", str(crayons.green(" lock", bold=True))) + help = help.replace(" open", str(crayons.red(" open", bold=True))) + help = help.replace(" run", str(crayons.yellow(" run", bold=True))) + help = help.replace(" shell", str(crayons.yellow(" shell", bold=True))) + help = help.replace(" sync", str(crayons.green(" sync", bold=True))) + help = help.replace(" uninstall", str(crayons.magenta(" uninstall", bold=True))) + help = help.replace(" update", str(crayons.green(" update", bold=True))) additional_help = """ Usage Examples: Create a new project using Python 3.7, specifically: @@ -1574,72 +1555,67 @@ Usage Examples: $ {8} Commands:""".format( - crayons.red('pipenv --three'), - crayons.red('pipenv --python 3.7'), - crayons.red('pipenv install --dev'), - crayons.red('pipenv lock'), - crayons.red('pipenv graph'), - crayons.red('pipenv install -e .'), - crayons.red('pipenv lock --pre'), - crayons.red('pipenv check'), - crayons.red('pipenv run pip freeze'), + crayons.red("pipenv --three"), + crayons.red("pipenv --python 3.7"), + crayons.red("pipenv install --dev"), + crayons.red("pipenv lock"), + crayons.red("pipenv graph"), + crayons.red("pipenv install -e ."), + crayons.red("pipenv lock --pre"), + crayons.red("pipenv check"), + crayons.red("pipenv run pip freeze"), ) - help = help.replace('Commands:', additional_help) + help = help.replace("Commands:", additional_help) return help def format_pip_error(error): + error = error.replace("Expected", str(crayons.green("Expected", bold=True))) + error = error.replace("Got", str(crayons.red("Got", bold=True))) error = error.replace( - 'Expected', str(crayons.green('Expected', bold=True)) - ) - error = error.replace('Got', str(crayons.red('Got', bold=True))) - error = error.replace( - 'THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE', + "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE", str( crayons.red( - 'THESE PACKAGES DO NOT MATCH THE HASHES FROM Pipfile.lock!', - bold=True, + "THESE PACKAGES DO NOT MATCH THE HASHES FROM Pipfile.lock!", bold=True ) ), ) error = error.replace( - 'someone may have tampered with them', - str(crayons.red('someone may have tampered with them')), - ) - error = error.replace( - 'option to pip install', 'option to \'pipenv install\'' + "someone may have tampered with them", + str(crayons.red("someone may have tampered with them")), ) + error = error.replace("option to pip install", "option to 'pipenv install'") return error def format_pip_output(out, r=None): - def gen(out): - for line in out.split('\n'): + for line in out.split("\n"): # Remove requirements file information from pip9 output. - if '(from -r' in line: - yield line[: line.index('(from -r')] + if "(from -r" in line: + yield line[: line.index("(from -r")] else: yield line - out = '\n'.join([l for l in gen(out)]) + out = "\n".join([l for l in gen(out)]) return out def warn_in_virtualenv(): from .environments import PIPENV_USE_SYSTEM, PIPENV_VIRTUALENV + # Only warn if pipenv isn't already active. - pipenv_active = os.environ.get('PIPENV_ACTIVE') + pipenv_active = os.environ.get("PIPENV_ACTIVE") if (PIPENV_USE_SYSTEM or PIPENV_VIRTUALENV) and not pipenv_active: click.echo( - '{0}: Pipenv found itself running within a virtual environment, ' - 'so it will automatically use that environment, instead of ' - 'creating its own for any project. You can set ' - '{1} to force pipenv to ignore that environment and create ' - 'its own instead.'.format( - crayons.green('Courtesy Notice'), - crayons.normal('PIPENV_IGNORE_VIRTUALENVS=1', bold=True), + "{0}: Pipenv found itself running within a virtual environment, " + "so it will automatically use that environment, instead of " + "creating its own for any project. You can set " + "{1} to force pipenv to ignore that environment and create " + "its own instead.".format( + crayons.green("Courtesy Notice"), + crayons.normal("PIPENV_IGNORE_VIRTUALENVS=1", bold=True), ), err=True, ) @@ -1648,7 +1624,7 @@ def warn_in_virtualenv(): def ensure_lockfile(keep_outdated=False, pypi_mirror=None): """Ensures that the lockfile is up-to-date.""" if not keep_outdated: - keep_outdated = project.settings.get('keep_outdated') + keep_outdated = project.settings.get("keep_outdated") # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored if project.lockfile_exists: old_hash = project.get_lockfile_hash() @@ -1656,7 +1632,7 @@ def ensure_lockfile(keep_outdated=False, pypi_mirror=None): if new_hash != old_hash: click.echo( crayons.red( - u'Pipfile.lock ({0}) out of date, updating to ({1})...'.format( + u"Pipfile.lock ({0}) out of date, updating to ({1})...".format( old_hash[-6:], new_hash[-6:] ), bold=True, @@ -1670,30 +1646,26 @@ def ensure_lockfile(keep_outdated=False, pypi_mirror=None): def do_py(system=False): try: - click.echo(which('python', allow_global=system)) + click.echo(which("python", allow_global=system)) except AttributeError: - click.echo(crayons.red('No project found!')) + click.echo(crayons.red("No project found!")) def do_outdated(pypi_mirror=None): from .vendor.requirementslib import Requirement + packages = {} - results = delegator.run('{0} freeze'.format(which('pip'))).out.strip( - ).split( - '\n' - ) + results = delegator.run("{0} freeze".format(which("pip"))).out.strip().split("\n") results = filter(bool, results) for result in results: dep = Requirement.from_line(result) packages.update(dep.as_pipfile()) updated_packages = {} lockfile = do_lock(write=False, pypi_mirror=pypi_mirror) - for section in ('develop', 'default'): + for section in ("develop", "default"): for package in lockfile[section]: try: - updated_packages[package] = lockfile[section][package][ - 'version' - ] + updated_packages[package] = lockfile[section][package]["version"] except KeyError: pass outdated = [] @@ -1706,7 +1678,7 @@ def do_outdated(pypi_mirror=None): ) for package, new_version, old_version in outdated: click.echo( - 'Package {0!r} out-of-date: {1!r} installed, {2!r} available.'.format( + "Package {0!r} out-of-date: {1!r} installed, {2!r} available.".format( package, old_version, new_version ) ) @@ -1737,7 +1709,7 @@ def do_install( from notpip._internal.exceptions import PipError requirements_directory = TemporaryDirectory( - suffix='-requirements', prefix='pipenv-' + suffix="-requirements", prefix="pipenv-" ) if selective_upgrade: keep_outdated = True @@ -1747,7 +1719,7 @@ def do_install( skip_requirements = True else: skip_requirements = False - concurrent = (not sequential) + concurrent = not sequential # Ensure that virtualenv is available. ensure_project( three=three, @@ -1760,20 +1732,20 @@ def do_install( ) # Load the --pre settings from the Pipfile. if not pre: - pre = project.settings.get('allow_prereleases') + pre = project.settings.get("allow_prereleases") if not keep_outdated: - keep_outdated = project.settings.get('keep_outdated') + keep_outdated = project.settings.get("keep_outdated") remote = requirements and is_valid_url(requirements) # Warn and exit if --system is used without a pipfile. if (system and package_name) and not (PIPENV_VIRTUALENV): click.echo( - '{0}: --system is intended to be used for Pipfile installation, ' - 'not installation of specific packages. Aborting.'.format( - crayons.red('Warning', bold=True) + "{0}: --system is intended to be used for Pipfile installation, " + "not installation of specific packages. Aborting.".format( + crayons.red("Warning", bold=True) ), err=True, ) - click.echo('See also: --deploy flag.', err=True) + click.echo("See also: --deploy flag.", err=True) requirements_directory.cleanup() sys.exit(1) # Automatically use an activated virtualenv. @@ -1782,15 +1754,13 @@ def do_install( # Check if the file is remote or not if remote: fd, temp_reqs = tempfile.mkstemp( - prefix='pipenv-', - suffix='-requirement.txt', - dir=requirements_directory.name, + prefix="pipenv-", suffix="-requirement.txt", dir=requirements_directory.name ) requirements_url = requirements # Download requirements file click.echo( crayons.normal( - u'Remote requirements file provided! Downloading...', bold=True + u"Remote requirements file provided! Downloading...", bold=True ), err=True, ) @@ -1799,7 +1769,7 @@ def do_install( except IOError: click.echo( crayons.red( - u'Unable to find requirements file at {0}.'.format( + u"Unable to find requirements file at {0}.".format( crayons.normal(requirements) ) ), @@ -1814,8 +1784,7 @@ def do_install( error, traceback = None, None click.echo( crayons.normal( - u'Requirements file provided! Importing into Pipfile...', - bold=True, + u"Requirements file provided! Importing into Pipfile...", bold=True ), err=True, ) @@ -1823,18 +1792,16 @@ def do_install( import_requirements(r=project.path_to(requirements), dev=dev) except (UnicodeDecodeError, PipError) as e: # Don't print the temp file path if remote since it will be deleted. - req_path = requirements_url if remote else project.path_to( - requirements - ) + req_path = requirements_url if remote else project.path_to(requirements) error = ( - u'Unexpected syntax in {0}. Are you sure this is a ' - 'requirements.txt style file?'.format(req_path) + u"Unexpected syntax in {0}. Are you sure this is a " + "requirements.txt style file?".format(req_path) ) traceback = e except AssertionError as e: error = ( - u'Requirements file doesn\'t appear to exist. Please ensure the file exists in your ' - 'project directory or you provided the correct path.' + u"Requirements file doesn't appear to exist. Please ensure the file exists in your " + "project directory or you provided the correct path." ) traceback = e finally: @@ -1849,30 +1816,28 @@ def do_install( sys.exit(1) if code: click.echo( - crayons.normal( - u'Discovering imports from local codebase...', bold=True - ) + crayons.normal(u"Discovering imports from local codebase...", bold=True) ) for req in import_from_code(code): - click.echo(' Found {0}!'.format(crayons.green(req))) + click.echo(" Found {0}!".format(crayons.green(req))) project.add_package_to_pipfile(req) # Capture -e argument and assign it to following package_name. more_packages = list(more_packages) - if package_name == '-e': + if package_name == "-e": if not more_packages: - raise click.BadArgumentUsage('Please provide path to editable package') - package_name = ' '.join([package_name, more_packages.pop(0)]) + raise click.BadArgumentUsage("Please provide path to editable package") + package_name = " ".join([package_name, more_packages.pop(0)]) # capture indexes and extra indexes line = [package_name] + more_packages - line = ' '.join(str(s) for s in line).strip() - index_indicators = ['-i', '--index', '--extra-index-url'] + line = " ".join(str(s) for s in line).strip() + index_indicators = ["-i", "--index", "--extra-index-url"] index, extra_indexes = None, None if any(line.endswith(s) for s in index_indicators): # check if cli option is not end of command - raise click.BadArgumentUsage('Please provide index value') + raise click.BadArgumentUsage("Please provide index value") if any(s in line for s in index_indicators): - line, index = split_argument(line, short='i', long_='index', num=1) - line, extra_indexes = split_argument(line, long_='extra-index-url') + line, index = split_argument(line, short="i", long_="index", num=1) + line, extra_indexes = split_argument(line, long_="extra-index-url") package_names = line.split() package_name = package_names[0] if len(package_names) > 1: @@ -1880,14 +1845,17 @@ def do_install( else: more_packages = [] # Capture . argument and assign it to nothing - if package_name == '.': + if package_name == ".": package_name = False # Install editable local packages before locking - this gives us access to dist-info if project.pipfile_exists and ( # double negatives are for english readability, leave them alone. - (not project.lockfile_exists and not deploy) or (not project.virtualenv_exists and not system) + (not project.lockfile_exists and not deploy) + or (not project.virtualenv_exists and not system) ): - section = project.editable_packages if not dev else project.editable_dev_packages + section = ( + project.editable_packages if not dev else project.editable_dev_packages + ) for package in section.keys(): converted = convert_deps_to_pip( {package: section[package]}, project=project, r=False @@ -1904,22 +1872,17 @@ def do_install( # the items specified if selective_upgrade: from .vendor.requirementslib import Requirement + for i, package_name in enumerate(package_names[:]): section = project.packages if not dev else project.dev_packages package = Requirement.from_line(package_name) package__name, package__val = package.pipfile_entry try: - if not is_star(section[package__name]) and is_star( - package__val - ): + if not is_star(section[package__name]) and is_star(package__val): # Support for VCS dependencies. package_names[i] = convert_deps_to_pip( - {package_name: section[package__name]}, - project=project, - r=False, - )[ - 0 - ] + {package_name: section[package__name]}, project=project, r=False + )[0] except KeyError: pass # Install all dependencies, if none was provided. @@ -1928,7 +1891,7 @@ def do_install( if package_name is False: # Update project settings with pre preference. if pre: - project.update_settings({'allow_prereleases': pre}) + project.update_settings({"allow_prereleases": pre}) do_init( dev=dev, allow_global=system, @@ -1946,12 +1909,11 @@ def do_install( # This is for if the user passed in dependencies, then we want to maek sure we else: from .vendor.requirementslib import Requirement + for package_name in package_names: click.echo( crayons.normal( - u'Installing {0}...'.format( - crayons.green(package_name, bold=True) - ), + u"Installing {0}...".format(crayons.green(package_name, bold=True)), bold=True, ) ) @@ -1974,17 +1936,17 @@ def do_install( try: converted = Requirement.from_line(package_name) except ValueError as e: - click.echo('{0}: {1}'.format(crayons.red('WARNING'), e)) + click.echo("{0}: {1}".format(crayons.red("WARNING"), e)) requirements_directory.cleanup() sys.exit(1) if converted.is_vcs and not converted.editable: click.echo( - '{0}: You installed a VCS dependency in non-editable mode. ' - 'This will work fine, but sub-dependencies will not be resolved by {1}.' - '\n To enable this sub-dependency functionality, specify that this dependency is editable.' - ''.format( - crayons.red('Warning', bold=True), - crayons.red('$ pipenv lock'), + "{0}: You installed a VCS dependency in non-editable mode. " + "This will work fine, but sub-dependencies will not be resolved by {1}." + "\n To enable this sub-dependency functionality, specify that this dependency is editable." + "".format( + crayons.red("Warning", bold=True), + crayons.red("$ pipenv lock"), ) ) click.echo(crayons.blue(format_pip_output(c.out))) @@ -1993,32 +1955,29 @@ def do_install( assert c.return_code == 0 except AssertionError: click.echo( - '{0} An error occurred while installing {1}!'.format( - crayons.red('Error: ', bold=True), - crayons.green(package_name), + "{0} An error occurred while installing {1}!".format( + crayons.red("Error: ", bold=True), crayons.green(package_name) ), err=True, ) click.echo(crayons.blue(format_pip_error(c.err)), err=True) - if 'setup.py egg_info' in c.err: + if "setup.py egg_info" in c.err: click.echo( "This is likely caused by a bug in {0}. " "Report this to its maintainers.".format( - crayons.green(package_name), + crayons.green(package_name) ), err=True, ) requirements_directory.cleanup() sys.exit(1) click.echo( - '{0} {1} {2} {3}{4}'.format( - crayons.normal('Adding', bold=True), + "{0} {1} {2} {3}{4}".format( + crayons.normal("Adding", bold=True), crayons.green(package_name, bold=True), crayons.normal("to Pipfile's", bold=True), - crayons.red( - '[dev-packages]' if dev else '[packages]', bold=True - ), - crayons.normal('...', bold=True), + crayons.red("[dev-packages]" if dev else "[packages]", bold=True), + crayons.normal("...", bold=True), ) ) # Add the package to the Pipfile. @@ -2026,13 +1985,11 @@ def do_install( project.add_package_to_pipfile(package_name, dev) except ValueError as e: click.echo( - '{0} {1}'.format( - crayons.red('ERROR (PACKAGE NOT INSTALLED):'), e - ) + "{0} {1}".format(crayons.red("ERROR (PACKAGE NOT INSTALLED):"), e) ) # Update project settings with pre preference. if pre: - project.update_settings({'allow_prereleases': pre}) + project.update_settings({"allow_prereleases": pre}) do_init( dev=dev, system=system, @@ -2043,7 +2000,7 @@ def do_install( requirements_dir=requirements_directory, deploy=deploy, pypi_mirror=pypi_mirror, - skip_lock=skip_lock + skip_lock=skip_lock, ) requirements_directory.cleanup() sys.exit(0) @@ -2063,6 +2020,7 @@ def do_uninstall( pypi_mirror=None, ): from .environments import PIPENV_USE_SYSTEM + # Automatically use an activated virtualenv. if PIPENV_USE_SYSTEM: system = True @@ -2073,61 +2031,53 @@ def do_uninstall( # Un-install all dependencies, if --all was provided. if all is True: click.echo( - crayons.normal( - u'Un-installing all packages from virtualenv...', bold=True - ) + crayons.normal(u"Un-installing all packages from virtualenv...", bold=True) ) do_purge(allow_global=system, verbose=verbose) sys.exit(0) # Uninstall [dev-packages], if --dev was provided. if all_dev: - if 'dev-packages' not in project.parsed_pipfile: + if "dev-packages" not in project.parsed_pipfile: click.echo( crayons.normal( - 'No {0} to uninstall.'.format( - crayons.red('[dev-packages]') - ), + "No {0} to uninstall.".format(crayons.red("[dev-packages]")), bold=True, ) ) sys.exit(0) click.echo( crayons.normal( - u'Un-installing {0}...'.format(crayons.red('[dev-packages]')), - bold=True, + u"Un-installing {0}...".format(crayons.red("[dev-packages]")), bold=True ) ) package_names = project.dev_packages.keys() if package_name is False and not all_dev: - click.echo(crayons.red('No package provided!'), err=True) + click.echo(crayons.red("No package provided!"), err=True) sys.exit(1) for package_name in package_names: - click.echo(u'Un-installing {0}...'.format(crayons.green(package_name))) - cmd = '{0} uninstall {1} -y'.format( - escape_grouped_arguments(which_pip(allow_global=system)), - package_name, + click.echo(u"Un-installing {0}...".format(crayons.green(package_name))) + cmd = "{0} uninstall {1} -y".format( + escape_grouped_arguments(which_pip(allow_global=system)), package_name ) if verbose: - click.echo('$ {0}'.format(cmd)) + click.echo("$ {0}".format(cmd)) c = delegator.run(cmd) click.echo(crayons.blue(c.out)) if pipfile_remove: - in_packages = project.get_package_name_in_pipfile( - package_name, dev=False) + in_packages = project.get_package_name_in_pipfile(package_name, dev=False) in_dev_packages = project.get_package_name_in_pipfile( - package_name, dev=True) + package_name, dev=True + ) if not in_dev_packages and not in_packages: click.echo( - 'No package {0} to remove from Pipfile.'.format( + "No package {0} to remove from Pipfile.".format( crayons.green(package_name) ) ) continue click.echo( - u'Removing {0} from Pipfile...'.format( - crayons.green(package_name) - ) + u"Removing {0} from Pipfile...".format(crayons.green(package_name)) ) # Remove package from both packages and dev-packages. project.remove_package_from_pipfile(package_name, dev=True) @@ -2140,20 +2090,17 @@ def do_shell(three=None, python=False, fancy=False, shell_args=None, pypi_mirror # Ensure that virtualenv is available. ensure_project(three=three, python=python, validate=False, pypi_mirror=pypi_mirror) # Set an environment variable, so we know we're in the environment. - os.environ['PIPENV_ACTIVE'] = '1' + os.environ["PIPENV_ACTIVE"] = "1" # Support shell compatibility mode. if PIPENV_SHELL_FANCY: fancy = True from .shells import choose_shell + shell = choose_shell() click.echo("Launching subshell in virtual environment…", err=True) - fork_args = ( - project.virtualenv_location, - project.project_directory, - shell_args, - ) + fork_args = (project.virtualenv_location, project.project_directory, shell_args) if fancy: shell.fork(*fork_args) @@ -2163,8 +2110,8 @@ def do_shell(three=None, python=False, fancy=False, shell_args=None, pypi_mirror shell.fork_compat(*fork_args) except (AttributeError, ImportError): click.echo( - u'Compatibility mode not supported. ' - u'Trying to continue as well-configured shell…', + u"Compatibility mode not supported. " + u"Trying to continue as well-configured shell…", err=True, ) shell.fork(*fork_args) @@ -2172,34 +2119,35 @@ def do_shell(three=None, python=False, fancy=False, shell_args=None, pypi_mirror def inline_activate_virtualenv(): try: - activate_this = which('activate_this.py') + activate_this = which("activate_this.py") if not activate_this or not os.path.exists(activate_this): click.echo( - u'{0}: activate_this.py not found. Your environment is most ' - u'certainly not activated. Continuing anyway...' - u''.format(crayons.red('Warning', bold=True)), + u"{0}: activate_this.py not found. Your environment is most " + u"certainly not activated. Continuing anyway..." + u"".format(crayons.red("Warning", bold=True)), err=True, ) return with open(activate_this) as f: - code = compile(f.read(), activate_this, 'exec') + code = compile(f.read(), activate_this, "exec") exec(code, dict(__file__=activate_this)) # Catch all errors, just in case. except Exception: click.echo( - u'{0}: There was an unexpected error while activating your virtualenv. Continuing anyway...' - ''.format(crayons.red('Warning', bold=True)), + u"{0}: There was an unexpected error while activating your virtualenv. Continuing anyway..." + "".format(crayons.red("Warning", bold=True)), err=True, ) def do_run_nt(script): import subprocess + command = system_which(script.command) - options = {'universal_newlines': True} - if command: # Try to use CreateProcess directly if possible. + options = {"universal_newlines": True} + if command: # Try to use CreateProcess directly if possible. p = subprocess.Popen([command] + script.args, **options) - else: # Command not found, maybe this is a shell built-in? + else: # Command not found, maybe this is a shell built-in? p = subprocess.Popen(script.cmdify(), shell=True, **options) p.communicate() sys.exit(p.returncode) @@ -2210,23 +2158,23 @@ def do_run_posix(script, command): if not command_path: if project.has_script(command): click.echo( - '{0}: the command {1} (from {2}) could not be found within {3}.' - ''.format( - crayons.red('Error', bold=True), + "{0}: the command {1} (from {2}) could not be found within {3}." + "".format( + crayons.red("Error", bold=True), crayons.red(script.command), crayons.normal(command, bold=True), - crayons.normal('PATH', bold=True), + crayons.normal("PATH", bold=True), ), err=True, ) else: click.echo( - '{0}: the command {1} could not be found within {2} or Pipfile\'s {3}.' - ''.format( - crayons.red('Error', bold=True), + "{0}: the command {1} could not be found within {2} or Pipfile's {3}." + "".format( + crayons.red("Error", bold=True), crayons.red(command), - crayons.normal('PATH', bold=True), - crayons.normal('[scripts]', bold=True), + crayons.normal("PATH", bold=True), + crayons.normal("[scripts]", bold=True), ), err=True, ) @@ -2240,6 +2188,7 @@ def do_run(command, args, three=None, python=False, pypi_mirror=None): Args are appended to the command in [scripts] section of project if found. """ from .cmdparse import ScriptEmptyError + # Ensure that virtualenv is available. ensure_project(three=three, python=python, validate=False, pypi_mirror=pypi_mirror) load_dot_env() @@ -2249,16 +2198,30 @@ def do_run(command, args, three=None, python=False, pypi_mirror=None): script = project.build_script(command, args) except ScriptEmptyError: click.echo("Can't run script {0!r}-it's empty?", err=True) - if os.name == 'nt': + if os.name == "nt": do_run_nt(script) else: do_run_posix(script, command=command) -def do_check(three=None, python=False, system=False, unused=False, ignore=None, args=None, pypi_mirror=None): +def do_check( + three=None, + python=False, + system=False, + unused=False, + ignore=None, + args=None, + pypi_mirror=None, +): if not system: # Ensure that virtualenv is available. - ensure_project(three=three, python=python, validate=False, warn=False, pypi_mirror=pypi_mirror) + ensure_project( + three=three, + python=python, + validate=False, + warn=False, + pypi_mirror=pypi_mirror, + ) if not args: args = [] if unused: @@ -2272,24 +2235,23 @@ def do_check(three=None, python=False, system=False, unused=False, ignore=None, if deps_required: click.echo( crayons.normal( - 'The following dependencies appear unused, and may be safe for removal:' + "The following dependencies appear unused, and may be safe for removal:" ) ) for dep in deps_required: - click.echo(' - {0}'.format(crayons.green(dep))) + click.echo(" - {0}".format(crayons.green(dep))) sys.exit(1) else: sys.exit(0) - click.echo(crayons.normal(u'Checking PEP 508 requirements...', bold=True)) + click.echo(crayons.normal(u"Checking PEP 508 requirements...", bold=True)) if system: - python = system_which('python') + python = system_which("python") else: - python = which('python') + python = which("python") # Run the PEP 508 checker in the virtualenv. c = delegator.run( '"{0}" {1}'.format( - python, - escape_grouped_arguments(pep508checker.__file__.rstrip('cdo')), + python, escape_grouped_arguments(pep508checker.__file__.rstrip("cdo")) ) ) results = simplejson.loads(c.out) @@ -2297,15 +2259,15 @@ def do_check(three=None, python=False, system=False, unused=False, ignore=None, p = pipfile.Pipfile.load(project.pipfile_location) failed = False # Assert each specified requirement. - for marker, specifier in p.data['_meta']['requires'].items(): + for marker, specifier in p.data["_meta"]["requires"].items(): if marker in results: try: assert results[marker] == specifier except AssertionError: failed = True click.echo( - 'Specifier {0} does not match {1} ({2}).' - ''.format( + "Specifier {0} does not match {1} ({2})." + "".format( crayons.green(marker), crayons.blue(specifier), crayons.red(results[marker]), @@ -2313,24 +2275,27 @@ def do_check(three=None, python=False, system=False, unused=False, ignore=None, err=True, ) if failed: - click.echo(crayons.red('Failed!'), err=True) + click.echo(crayons.red("Failed!"), err=True) sys.exit(1) else: - click.echo(crayons.green('Passed!')) - click.echo( - crayons.normal(u'Checking installed package safety...', bold=True) - ) - path = pep508checker.__file__.rstrip('cdo') - path = os.sep.join(__file__.split(os.sep)[:-1] + ['patched', 'safety.zip']) + click.echo(crayons.green("Passed!")) + click.echo(crayons.normal(u"Checking installed package safety...", bold=True)) + path = pep508checker.__file__.rstrip("cdo") + path = os.sep.join(__file__.split(os.sep)[:-1] + ["patched", "safety.zip"]) if not system: - python = which('python') + python = which("python") else: - python = system_which('python') + python = system_which("python") if ignore: - ignored = '--ignore {0}'.format('--ignore '.join(ignore)) - click.echo(crayons.normal('Notice: Ignoring CVE(s) {0}'.format(crayons.yellow(', '.join(ignore)))), err=True) + ignored = "--ignore {0}".format("--ignore ".join(ignore)) + click.echo( + crayons.normal( + "Notice: Ignoring CVE(s) {0}".format(crayons.yellow(", ".join(ignore))) + ), + err=True, + ) else: - ignored = '' + ignored = "" c = delegator.run( '"{0}" {1} check --json --key=1ab8d58f-5122e025-83674263-bc1e79e0 {2}'.format( python, escape_grouped_arguments(path), ignored @@ -2339,93 +2304,92 @@ def do_check(three=None, python=False, system=False, unused=False, ignore=None, try: results = simplejson.loads(c.out) except ValueError: - click.echo('An error occurred:', err=True) + click.echo("An error occurred:", err=True) click.echo(c.err, err=True) sys.exit(1) for (package, resolved, installed, description, vuln) in results: click.echo( - '{0}: {1} {2} resolved ({3} installed)!'.format( + "{0}: {1} {2} resolved ({3} installed)!".format( crayons.normal(vuln, bold=True), crayons.green(package), crayons.red(resolved, bold=False), crayons.red(installed, bold=True), ) ) - click.echo('{0}'.format(description)) + click.echo("{0}".format(description)) click.echo() if not results: - click.echo(crayons.green('All good!')) + click.echo(crayons.green("All good!")) else: sys.exit(1) def do_graph(bare=False, json=False, json_tree=False, reverse=False): import pipdeptree + try: - python_path = which('python') + python_path = which("python") except AttributeError: click.echo( - u'{0}: {1}'.format( - crayons.red('Warning', bold=True), - u'Unable to display currently-installed dependency graph information here. ' - u'Please run within a Pipenv project.', + u"{0}: {1}".format( + crayons.red("Warning", bold=True), + u"Unable to display currently-installed dependency graph information here. " + u"Please run within a Pipenv project.", ), err=True, ) sys.exit(1) if reverse and json: click.echo( - u'{0}: {1}'.format( - crayons.red('Warning', bold=True), - u'Using both --reverse and --json together is not supported. ' - u'Please select one of the two options.', + u"{0}: {1}".format( + crayons.red("Warning", bold=True), + u"Using both --reverse and --json together is not supported. " + u"Please select one of the two options.", ), err=True, ) sys.exit(1) if reverse and json_tree: click.echo( - u'{0}: {1}'.format( - crayons.red('Warning', bold=True), - u'Using both --reverse and --json-tree together is not supported. ' - u'Please select one of the two options.', + u"{0}: {1}".format( + crayons.red("Warning", bold=True), + u"Using both --reverse and --json-tree together is not supported. " + u"Please select one of the two options.", ), err=True, ) sys.exit(1) if json and json_tree: click.echo( - u'{0}: {1}'.format( - crayons.red('Warning', bold=True), - u'Using both --json and --json-tree together is not supported. ' - u'Please select one of the two options.', + u"{0}: {1}".format( + crayons.red("Warning", bold=True), + u"Using both --json and --json-tree together is not supported. " + u"Please select one of the two options.", ), err=True, ) sys.exit(1) - flag = '' + flag = "" if json: - flag = '--json' + flag = "--json" if json_tree: - flag = '--json-tree' + flag = "--json-tree" if reverse: - flag = '--reverse' + flag = "--reverse" if not project.virtualenv_exists: click.echo( - u'{0}: No virtualenv has been created for this project yet! Consider ' - u'running {1} first to automatically generate one for you or see' - u'{2} for further instructions.'.format( - crayons.red('Warning', bold=True), - crayons.green('`pipenv install`'), - crayons.green('`pipenv install --help`'), + u"{0}: No virtualenv has been created for this project yet! Consider " + u"running {1} first to automatically generate one for you or see" + u"{2} for further instructions.".format( + crayons.red("Warning", bold=True), + crayons.green("`pipenv install`"), + crayons.green("`pipenv install --help`"), ), err=True, ) sys.exit(1) cmd = '"{0}" {1} {2}'.format( - python_path, - escape_grouped_arguments(pipdeptree.__file__.rstrip('cdo')), - flag, + python_path, escape_grouped_arguments(pipdeptree.__file__.rstrip("cdo")), flag ) # Run dep-tree. c = delegator.run(cmd) @@ -2433,28 +2397,34 @@ def do_graph(bare=False, json=False, json_tree=False, reverse=False): if json: data = [] for d in simplejson.loads(c.out): - if d['package']['key'] not in BAD_PACKAGES: + if d["package"]["key"] not in BAD_PACKAGES: data.append(d) click.echo(simplejson.dumps(data, indent=4)) sys.exit(0) elif json_tree: + def traverse(obj): if isinstance(obj, list): - return [traverse(package) for package in obj if package['key'] not in BAD_PACKAGES] + return [ + traverse(package) + for package in obj + if package["key"] not in BAD_PACKAGES + ] else: - obj['dependencies'] = traverse(obj['dependencies']) + obj["dependencies"] = traverse(obj["dependencies"]) return obj + data = traverse(simplejson.loads(c.out)) click.echo(simplejson.dumps(data, indent=4)) sys.exit(0) else: - for line in c.out.split('\n'): + for line in c.out.split("\n"): # Ignore bad packages as top level. - if line.split('==')[0] in BAD_PACKAGES and not reverse: + if line.split("==")[0] in BAD_PACKAGES and not reverse: continue # Bold top-level packages. - if not line.startswith(' '): + if not line.startswith(" "): click.echo(crayons.normal(line, bold=True)) # Echo the rest. else: @@ -2463,11 +2433,11 @@ def do_graph(bare=False, json=False, json_tree=False, reverse=False): click.echo(c.out) if c.return_code != 0: click.echo( - '{0} {1}'.format( - crayons.red('ERROR: ', bold=True), - crayons.white('{0}'.format(c.err, bold=True)), + "{0} {1}".format( + crayons.red("ERROR: ", bold=True), + crayons.white("{0}".format(c.err, bold=True)), ), - err=True + err=True, ) # Return its return code. sys.exit(c.return_code) @@ -2492,47 +2462,57 @@ def do_sync( # The lock file needs to exist because sync won't write to it. if not project.lockfile_exists: click.echo( - '{0}: Pipfile.lock is missing! You need to run {1} first.'.format( - crayons.red('Error', bold=True), - crayons.red('$ pipenv lock', bold=True), + "{0}: Pipfile.lock is missing! You need to run {1} first.".format( + crayons.red("Error", bold=True), crayons.red("$ pipenv lock", bold=True) ), err=True, ) sys.exit(1) # Ensure that virtualenv is available if not system. - ensure_project(three=three, python=python, validate=False, deploy=deploy, pypi_mirror=pypi_mirror) + ensure_project( + three=three, + python=python, + validate=False, + deploy=deploy, + pypi_mirror=pypi_mirror, + ) # Install everything. - requirements_dir = TemporaryDirectory( - suffix='-requirements', prefix='pipenv-' - ) + requirements_dir = TemporaryDirectory(suffix="-requirements", prefix="pipenv-") do_init( dev=dev, verbose=verbose, concurrent=(not sequential), requirements_dir=requirements_dir, - ignore_pipfile=True, # Don't check if Pipfile and lock match. + ignore_pipfile=True, # Don't check if Pipfile and lock match. pypi_mirror=pypi_mirror, deploy=deploy, system=system, ) requirements_dir.cleanup() - click.echo(crayons.green('All dependencies are now up-to-date!')) + click.echo(crayons.green("All dependencies are now up-to-date!")) def do_clean( - ctx, three=None, python=None, dry_run=False, bare=False, verbose=False, pypi_mirror=None + ctx, + three=None, + python=None, + dry_run=False, + bare=False, + verbose=False, + pypi_mirror=None, ): # Ensure that virtualenv is available. from .vendor.requirementslib import Requirement + ensure_project(three=three, python=python, validate=False, pypi_mirror=pypi_mirror) ensure_lockfile(pypi_mirror=pypi_mirror) installed_package_names = [] - pip_freeze_command = delegator.run('{0} freeze'.format(which_pip())) - for line in pip_freeze_command.out.split('\n'): + pip_freeze_command = delegator.run("{0} freeze".format(which_pip())) + for line in pip_freeze_command.out.split("\n"): installed = line.strip() - if not installed or installed.startswith('#'): # Comment or empty. + if not installed or installed.startswith("#"): # Comment or empty. continue r = Requirement.from_line(installed).requirement # Ignore editable installations. @@ -2540,23 +2520,19 @@ def do_clean( installed_package_names.append(r.name.lower()) else: if verbose: - click.echo('Ignoring {0}.'.format(repr(r.name)), err=True) + click.echo("Ignoring {0}.".format(repr(r.name)), err=True) # Remove known "bad packages" from the list. for bad_package in BAD_PACKAGES: if bad_package in installed_package_names: if verbose: - click.echo('Ignoring {0}.'.format(repr(bad_package)), err=True) - del installed_package_names[ - installed_package_names.index(bad_package) - ] + click.echo("Ignoring {0}.".format(repr(bad_package)), err=True) + del installed_package_names[installed_package_names.index(bad_package)] # Intelligently detect if --dev should be used or not. - develop = [k.lower() for k in project.lockfile_content['develop'].keys()] - default = [k.lower() for k in project.lockfile_content['default'].keys()] + develop = [k.lower() for k in project.lockfile_content["develop"].keys()] + default = [k.lower() for k in project.lockfile_content["default"].keys()] for used_package in set(develop + default): if used_package in installed_package_names: - del installed_package_names[ - installed_package_names.index(used_package) - ] + del installed_package_names[installed_package_names.index(used_package)] failure = False for apparent_bad_package in installed_package_names: if dry_run: @@ -2564,15 +2540,12 @@ def do_clean( else: click.echo( crayons.white( - 'Uninstalling {0}...'.format(repr(apparent_bad_package)), - bold=True, + "Uninstalling {0}...".format(repr(apparent_bad_package)), bold=True ) ) # Uninstall the package. c = delegator.run( - '{0} uninstall {1} -y'.format( - which_pip(), apparent_bad_package - ) + "{0} uninstall {1} -y".format(which_pip(), apparent_bad_package) ) if c.return_code != 0: failure = True