Пример #1
0
 def __init__(self, message):
     extra = [
         "{} {}".format(
             crayons.red("The operation failed...", bold=True),
             crayons.red(
                 "A dependency conflict was detected and could not be resolved."
             ),
         )
     ]
     PipenvException.__init__(self, message, extra=extra)
Пример #2
0
 def __init__(self, message, no_version_found=False):
     extra = (
         "{}: Your dependencies could not be resolved. You likely have a "
         "mismatch in your sub-dependencies.\n  "
         "First try clearing your dependency cache with {}, then try the original command again.\n "
         "Alternatively, you can use {} to bypass this mechanism, then run "
         "{} to inspect the situation.\n  "
         "Hint: try {} if it is a pre-release dependency."
         "".format(
             crayons.red("Warning", bold=True),
             crayons.yellow("$ pipenv lock --clear"),
             crayons.yellow("$ pipenv install --skip-lock"),
             crayons.yellow("$ pipenv graph"),
             crayons.yellow("$ pipenv lock --pre"),
         ),
     )
     if "no version found at all" in message:
         no_version_found = True
     message = crayons.yellow(f"{message}")
     if no_version_found:
         message = "{}\n{}".format(
             message,
             crayons.cyan(
                 "Please check your version specifier and version number. "
                 "See PEP440 for more information."
             )
         )
     PipenvException.__init__(self, message, extra=extra)
Пример #3
0
class PipenvFileError(FileError):
    formatted_message = "{0} {{0}} {{1}}".format(
        crayons.red("ERROR:", bold=True)
    )

    def __init__(self, filename, message=None, **kwargs):
        extra = kwargs.pop("extra", [])
        if not message:
            message = crayons.normal("Please ensure that the file exists!", bold=True)
        message = self.formatted_message.format(
            crayons.normal(f"{filename} not found!", bold=True),
            message
        )
        FileError.__init__(self, filename=filename, hint=decode_for_output(message), **kwargs)
        self.extra = extra

    def show(self, file=None):
        if file is None:
            file = vistir.misc.get_text_stderr()
        if self.extra:
            if isinstance(self.extra, STRING_TYPES):
                self.extra = [self.extra]
            for extra in self.extra:
                click_echo(decode_for_output(extra, file), file=file)
        click_echo(self.message, file=file)
Пример #4
0
 def __init__(self, filename="Pipfile.lock", extra=None, **kwargs):
     extra = kwargs.pop("extra", [])
     message = "{} {} {}".format(
         crayons.normal("You need to run", bold=True),
         crayons.red("$ pipenv lock", bold=True),
         crayons.normal("before you can continue.", bold=True))
     super().__init__(filename, message=message, extra=extra, **kwargs)
Пример #5
0
def run_open(state, module, *args, **kwargs):
    """View a given module in your editor.

    This uses the EDITOR environment variable. You can temporarily override it,
    for example:

        EDITOR=atom pipenv open requests
    """
    from ..core import ensure_project, inline_activate_virtual_environment

    # Ensure that virtualenv is available.
    ensure_project(
        state.project,
        three=state.three,
        python=state.python,
        validate=False,
        pypi_mirror=state.pypi_mirror,
    )
    c = subprocess_run([
        state.project._which("python"),
        "-c",
        "import {0}; print({0}.__file__)".format(module),
    ])
    if c.returncode:
        echo(crayons.red("Module not found!"))
        sys.exit(1)
    if "__init__.py" in c.stdout:
        p = os.path.dirname(c.stdout.strip().rstrip("cdo"))
    else:
        p = c.stdout.strip().rstrip("cdo")
    echo(crayons.normal(f"Opening {p!r} in your EDITOR.", bold=True))
    inline_activate_virtual_environment(state.project)
    edit(filename=p)
    return 0
Пример #6
0
 def __init__(self, filename="Pipfile", extra=None, **kwargs):
     extra = kwargs.pop("extra", [])
     message = ("{} {}".format(
         crayons.red("Aborting!", bold=True),
         crayons.normal(
             "Please ensure that the file exists and is located in your"
             " project root directory.",
             bold=True)))
     super().__init__(filename, message=message, extra=extra, **kwargs)
Пример #7
0
 def __init__(self, message=None, ctx=None, **kwargs):
     formatted_message = "{0}: {1}"
     msg_prefix = crayons.red("ERROR:", bold=True)
     if not message:
         message = "Pipenv encountered a problem and had to exit."
     message = formatted_message.format(msg_prefix, crayons.normal(message, bold=True))
     self.message = message
     extra = kwargs.pop("extra", [])
     UsageError.__init__(self, decode_for_output(message), ctx)
     self.extra = extra
Пример #8
0
 def __init__(self, option_name="system", message=None, ctx=None, **kwargs):
     extra = kwargs.pop("extra", [])
     extra += [
         "{}: --system is intended to be used for Pipfile installation, "
         "not installation of specific packages. Aborting.".format(
             crayons.red("Warning", bold=True)
         ),
     ]
     if message is None:
         message = str(
             crayons.cyan("See also: {}".format(crayons.normal("--deploy flag.")))
         )
     super().__init__(option_name, message=message, ctx=ctx, extra=extra, **kwargs)
Пример #9
0
 def __init__(self, message=None, **kwargs):
     if not message:
         message = "Failed to create virtual environment."
     self.message = message
     extra = kwargs.pop("extra", None)
     if extra is not None and isinstance(extra, STRING_TYPES):
         # note we need the format interpolation because ``crayons.ColoredString``
         # is not an actual string type but is only a preparation for interpolation
         # so replacement or parsing requires this step
         extra = ANSI_REMOVAL_RE.sub("", f"{extra}")
         if "KeyboardInterrupt" in extra:
             extra = str(
                 crayons.red("Virtualenv creation interrupted by user", bold=True)
             )
         self.extra = extra = [extra]
     VirtualenvException.__init__(self, message, extra=extra)
Пример #10
0
 def show(self, file=None):
     if file is None:
         file = vistir.misc.get_text_stderr()
     click_echo("{} {}".format(
         crayons.red("Error running command: "),
         crayons.normal(decode_for_output(f"$ {self.cmd}", file),
                        bold=True)),
                err=True)
     if self.out:
         click_echo("{} {}".format(crayons.normal("OUTPUT: "),
                                   decode_for_output(self.out, file)),
                    err=True)
     if self.err:
         click_echo("{} {}".format(crayons.normal("STDERR: "),
                                   decode_for_output(self.err, file)),
                    err=True)
Пример #11
0
class PipenvException(ClickException):
    message = "{0}: {{0}}".format(crayons.red("ERROR", bold=True))

    def __init__(self, message=None, **kwargs):
        if not message:
            message = "Pipenv encountered a problem and had to exit."
        extra = kwargs.pop("extra", [])
        message = self.message.format(message)
        ClickException.__init__(self, message)
        self.extra = extra

    def show(self, file=None):
        if file is None:
            file = vistir.misc.get_text_stderr()
        if self.extra:
            if isinstance(self.extra, STRING_TYPES):
                self.extra = [self.extra]
            for extra in self.extra:
                extra = "[pipenv.exceptions.{!s}]: {}".format(
                    self.__class__.__name__, extra)
                extra = decode_for_output(extra, file)
                click_echo(extra, file=file)
        click_echo(decode_for_output(f"{self.message}", file), file=file)
Пример #12
0
def cli(
    ctx,
    state,
    where=False,
    venv=False,
    py=False,
    envs=False,
    rm=False,
    bare=False,
    man=False,
    support=None,
    help=False,
    site_packages=None,
    **kwargs,
):
    from pipenv.utils.spinner import create_spinner

    from ..core import (
        cleanup_virtualenv,
        do_clear,
        do_py,
        do_where,
        ensure_project,
        format_help,
        system_which,
        warn_in_virtualenv,
    )

    if man:
        if system_which("man"):
            path = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                "pipenv.1")
            os.execle(system_which("man"), "man", path, os.environ)
            return 0
        else:
            secho(
                "man does not appear to be available on your system.",
                fg="yellow",
                bold=True,
                err=True,
            )
            return 1
    if envs:
        echo(
            "The following environment variables can be set, to do various things:\n"
        )
        for key in state.project.__dict__:
            if key.startswith("PIPENV"):
                echo(f"  - {crayons.normal(key, bold=True)}")
        echo("\nYou can learn more at:\n   {}".format(
            crayons.green(
                "https://pipenv.pypa.io/en/latest/advanced/#configuration-with-environment-variables"
            )))
        return 0
    warn_in_virtualenv(state.project)
    if ctx.invoked_subcommand is None:
        # --where was passed...
        if where:
            do_where(state.project, bare=True)
            return 0
        elif py:
            do_py(state.project, ctx=ctx)
            return 0
        # --support was passed...
        elif support:
            from ..help import get_pipenv_diagnostics

            get_pipenv_diagnostics(state.project)
            return 0
        # --clear was passed...
        elif state.clear:
            do_clear(state.project)
            return 0
        # --venv was passed...
        elif venv:
            # There is no virtualenv yet.
            if not state.project.virtualenv_exists:
                echo(
                    "{}({}){}".format(
                        crayons.red(
                            "No virtualenv has been created for this project"),
                        crayons.normal(state.project.project_directory,
                                       bold=True),
                        crayons.red(" yet!"),
                    ),
                    err=True,
                )
                ctx.abort()
            else:
                echo(state.project.virtualenv_location)
                return 0
        # --rm was passed...
        elif rm:
            # Abort if --system (or running in a virtualenv).
            if state.project.s.PIPENV_USE_SYSTEM or environments.is_in_virtualenv(
            ):
                echo(
                    crayons.red(
                        "You are attempting to remove a virtualenv that "
                        "Pipenv did not create. Aborting."))
                ctx.abort()
            if state.project.virtualenv_exists:
                loc = state.project.virtualenv_location
                echo(
                    crayons.normal("{} ({})...".format(
                        crayons.normal("Removing virtualenv", bold=True),
                        crayons.green(loc),
                    )))
                with create_spinner(text="Running...",
                                    setting=state.project.s):
                    # Remove the virtualenv.
                    cleanup_virtualenv(state.project, bare=True)
                return 0
            else:
                echo(
                    crayons.red(
                        "No virtualenv has been created for this project yet!",
                        bold=True,
                    ),
                    err=True,
                )
                ctx.abort()
    # --python or --three was passed...
    if (state.python or state.three is not None) or state.site_packages:
        ensure_project(
            state.project,
            three=state.three,
            python=state.python,
            warn=True,
            site_packages=state.site_packages,
            pypi_mirror=state.pypi_mirror,
            clear=state.clear,
        )
    # Check this again before exiting for empty ``pipenv`` command.
    elif ctx.invoked_subcommand is None:
        # Display help to user, if no commands were passed.
        echo(format_help(ctx.get_help()))
Пример #13
0
def update(ctx, state, bare=False, dry_run=None, outdated=False, **kwargs):
    """Runs lock, then sync."""
    from ..core import do_lock, do_outdated, do_sync, ensure_project

    ensure_project(
        state.project,
        three=state.three,
        python=state.python,
        pypi_mirror=state.pypi_mirror,
        warn=(not state.quiet),
        site_packages=state.site_packages,
        clear=state.clear,
    )
    if not outdated:
        outdated = bool(dry_run)
    if outdated:
        do_outdated(
            state.project,
            clear=state.clear,
            pre=state.installstate.pre,
            pypi_mirror=state.pypi_mirror,
        )
    packages = [p for p in state.installstate.packages if p]
    editable = [p for p in state.installstate.editables if p]
    if not packages:
        echo("{} {} {} {}{}".format(
            crayons.normal("Running", bold=True),
            crayons.yellow("$ pipenv lock", bold=True),
            crayons.normal("then", bold=True),
            crayons.yellow("$ pipenv sync", bold=True),
            crayons.normal(".", bold=True),
        ))
    else:
        for package in packages + editable:
            if package not in state.project.all_packages:
                echo(
                    "{}: {} was not found in your Pipfile! Aborting."
                    "".format(
                        crayons.red("Warning", bold=True),
                        crayons.green(package, bold=True),
                    ),
                    err=True,
                )
                ctx.abort()
    do_lock(
        state.project,
        ctx=ctx,
        clear=state.clear,
        pre=state.installstate.pre,
        keep_outdated=state.installstate.keep_outdated,
        pypi_mirror=state.pypi_mirror,
        write=not state.quiet,
    )
    do_sync(
        state.project,
        dev=state.installstate.dev,
        three=state.three,
        python=state.python,
        bare=bare,
        dont_upgrade=not state.installstate.keep_outdated,
        user=False,
        clear=state.clear,
        unused=False,
        sequential=state.installstate.sequential,
        pypi_mirror=state.pypi_mirror,
    )
Пример #14
0
def patched_cli(ctx, working_dir, python):

    if working_dir:
        if not os.path.isdir(working_dir):
            working_dir = os.path.dirname(working_dir)
        os.environ["PIPENV_PIPFILE"] = os.path.join(working_dir, "Pipfile")

    # we need to import environments and modify PIPENV_PIPFILE
    # to ensure that Project is imported with the right value
    from pipenv import environments
    environments.PIPENV_PIPFILE = os.environ.get("PIPENV_PIPFILE")
    from pipenv.project import Project

    if PYENV_INSTALLED:

        workon = None
        venv_name = None

        if python and python.startswith(PYENV_ROOT) and "bin/python" in python:
            workon = os.path.dirname(os.path.dirname(python))
            workon = os.path.join(workon, "envs")

        try:
            venv_name = Project().virtualenv_name
        except AttributeError:
            # AttributeError is raised when pipenv does not find a valid
            # Pipfile and attempts spliting None
            pass

        if not workon and venv_name:
            versions = delegator.run("pyenv versions").out.splitlines(
                keepends=False)
            for v in versions:
                v = v.split()
                v = v[0] if v[0] != "*" else v[1]
                if "/envs/" in v:
                    if v.endswith(venv_name):
                        workon = os.path.join(PYENV_ROOT, "versions",
                                              os.path.dirname(v.strip()))
                        break

        if not workon:
            c = delegator.run("pyenv which python")
            c.block()
            workon = os.path.dirname(os.path.dirname(c.out.strip()))
            workon = os.path.join(workon, "envs")

        os.environ["WORKON_HOME"] = workon
        ctx.call_on_close(venv_symlink(workon, venv_name))

    if python:
        ctx.args = ["--python", python] + ctx.args

    try:
        venv_exists = Project().virtualenv_exists
    except:
        venv_exists = False

    if not ("install" in ctx.args or venv_exists):
        click.echo(
            crayons.red(
                "No virtualenv has been created for this project yet!"),
            err=True,
        )
        ctx.abort()

    ctx.invoke(cli, ctx.args)